fsanyoto commited on
Commit
792ee39
·
verified ·
1 Parent(s): e88a3a3

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (43) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. api/amazon_relational.py +50 -106
  4. api/automation_engine.py +271 -11
  5. api/meta_relational.py +51 -31
  6. api/odoo_relational.py +443 -172
  7. api/routes_connectors.py +540 -8
  8. api/routes_grid.py +255 -11
  9. api/routes_keychain.py +22 -0
  10. api/routes_odoo_tables.py +534 -13
  11. api/routes_sheet.py +594 -42
  12. platform/core/connector_directory.py +6 -0
  13. platform/core/connector_spec.py +395 -0
  14. platform/core/relations.py +873 -20
  15. platform/core/schema_overlay.py +103 -0
  16. platform/core/user_tables.py +68 -0
  17. platform/modules/sheet.py +302 -6
  18. web/src/connectors/ConnectorModal.tsx +82 -4
  19. web/src/connectors/ConnectorsPage.tsx +259 -182
  20. web/src/connectors/DatabasesTab.tsx +255 -51
  21. web/src/connectors/RelationshipDiagram.tsx +18 -1
  22. web/src/customer-grid/RecordDetail.css +61 -0
  23. web/src/customer-grid/RecordDetail.tsx +729 -76
  24. web/src/customer-grid/RecordRail.tsx +23 -2
  25. web/src/customer-grid/ViewSidebar.tsx +18 -1
  26. web/src/customer-grid/apiBridge.ts +81 -14
  27. web/src/customer-grid/types.ts +219 -31
  28. web/src/filter-kit/SheetFilterPopup.tsx +171 -0
  29. web/src/sheet/BindingEditor.tsx +468 -203
  30. web/src/sheet/KeyTips.tsx +18 -2
  31. web/src/sheet/Ribbon.tsx +240 -84
  32. web/src/sheet/SheetGrid.tsx +435 -70
  33. web/src/sheet/SheetPage.tsx +50 -36
  34. web/src/sheet/SheetRail.tsx +31 -1
  35. web/src/sheet/formulaEval.ts +522 -0
  36. web/src/sheet/sheetState.ts +335 -49
  37. web/src/shell/Shell.tsx +230 -64
  38. web/src/shell/icons.tsx +105 -0
  39. web/src/shell/nav.ts +24 -0
  40. web/src/shell/shell.css +64 -0
  41. web/src/styles/wave52/ribbon.css +39 -2
  42. web/src/styles/wave53/ribbon-pop.css +69 -0
  43. web/src/styles/wave53/sheet-rail.css +67 -0
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "8bd282e",
3
  "releases": [
4
  {
5
  "version": "v71",
 
1
  {
2
+ "current": "a1b9ea0",
3
  "releases": [
4
  {
5
  "version": "v71",
VERSION CHANGED
@@ -1 +1 @@
1
- 8bd282e
 
1
+ a1b9ea0
api/amazon_relational.py CHANGED
@@ -44,6 +44,7 @@ if str(_API.parent.parent / "platform") not in sys.path:
44
  sys.path.insert(0, str(_API.parent.parent / "platform"))
45
 
46
  import odoo_relational as _odoo # noqa: E402
 
47
  from harness import amazon_schema, amazon_store, datastore # noqa: E402
48
 
49
  Refused = _odoo.Refused
@@ -57,104 +58,42 @@ PREFIX = "ut_amzn_"
57
  #: exist on one side and not the other.
58
  SOURCE = {PREFIX + t: amazon_store.table_name(t) for t in amazon_store.TABLES}
59
 
60
- LABELS = {
61
- PREFIX + "orders": "Amazon orders",
62
- PREFIX + "order_items": "Amazon order items",
63
- PREFIX + "listings": "Amazon listings",
64
- PREFIX + "settlements": "Amazon settlements",
65
- PREFIX + "inventory": "Amazon inventory",
66
- PREFIX + "pricing": "Amazon pricing and Buy Box",
67
- PREFIX + "brand_analytics": "Amazon brand analytics",
68
- }
69
-
70
- #: The column each grid shows first. ⚠ Every one of these is a name Amazon's own reports use, so a
71
- #: table whose header does not carry it simply has no pinned column rather than a broken one.
72
- PINNED = {
73
- PREFIX + "orders": "amazon_order_id",
74
- PREFIX + "order_items": "amazon_order_id",
75
- PREFIX + "listings": "seller_sku",
76
- PREFIX + "settlements": "settlement_id",
77
- PREFIX + "inventory": "asin",
78
- PREFIX + "pricing": "parent_asin",
79
- PREFIX + "brand_analytics": "search_term",
80
- }
81
-
82
- #: ⭐ THE ROW IDENTITY PER TABLE, IN FALLING PREFERENCE. A flat-file report has no `id` column the
83
- #: way Graph does, so each table names the columns that identify one of its rows. When none is
84
- #: present the row is keyed by a hash of its own content (see `_row_id`), which still gives a
85
- #: STABLE id across re-syncs — that is what makes the delete-then-insert merge idempotent instead
86
- #: of appending a second copy of every row each time.
87
- IDENTITY = {
88
- PREFIX + "orders": ("amazon_order_id",),
89
- PREFIX + "order_items": ("order_item_id", "amazon_order_id"),
90
- PREFIX + "listings": ("seller_sku", "asin1", "asin"),
91
- PREFIX + "settlements": ("settlement_id",),
92
- PREFIX + "inventory": ("asin", "fnsku", "msku"),
93
- PREFIX + "pricing": ("child_asin", "parent_asin"),
94
- PREFIX + "brand_analytics": ("search_term",),
95
- }
96
-
97
- #: (this table's column) -> (target ut_ key, the column it matches there).
98
- #: ⛔ AMAZON TO AMAZON ONLY — see R12 in the header. Emitted only when BOTH sides carry the column,
99
- #: which for a measured-at-sync table is not knowable until it has synced.
100
- #: ⭐⭐ THE JOIN MAP, DERIVED FROM AMAZON'S OWN PUBLISHED MODELS (2026-09-04), NOT FROM MEMORY.
101
- #:
102
- #: Identifier fields were extracted from the vendor OpenAPI models and the key overlap read off:
103
- #: `ASIN` orders · finances · fba_inventory · listings_items · catalog · pricing
104
- #: `SellerSKU`/`sku` orders · finances · fba_inventory · listings_items · pricing · awd
105
- #: `AmazonOrderId` orders · finances
106
- #: `OrderItemId` orders · finances
107
- #: `FnSKU` finances · fba_inventory · listings_items
108
- #:
109
- #: ⭐ **AMAZON HAS TWO SPINES, AND EVERY USEFUL JOIN HANGS OFF ONE OF THEM:**
110
- #: · the PRODUCT spine — **ASIN** (Amazon's identifier) and **seller SKU** (ours). Not
111
- #: interchangeable: one ASIN can carry several of our SKUs, and a SKU maps to one ASIN.
112
- #: · the TRANSACTION spine — **amazon_order_id**, refined by **order_item_id** at line level.
113
- #:
114
- #: ⛔⛔ A LINK IS DECLARED HERE AND VERIFIED AT SPAWN, NEVER ASSUMED. Five of seven tables are
115
- #: `measured_at_sync`, so their column names are not known until a real report arrives. Every entry
116
- #: below is a HYPOTHESIS about a column name until `_fields_for` confirms BOTH sides carry it; an
117
- #: unconfirmed link simply does not render. **That is why a wrong guess here is cheap and a wrong
118
- #: guess in a JOIN would not be.**
119
- #:
120
- #: ⛔ R12 STILL HOLDS: these are Amazon-to-Amazon only. Nothing joins to `product_data`, to
121
- #: `ut_odoo_*`, or to the hand-maintained ASIN mastersheet.
122
- #:
123
- #: ⚠ Column names are the REPORT's, not the API model's — the report flattens `SellerSKU` to `sku`
124
- #: and `AmazonOrderId` to `amazon-order-id` -> `amazon_order_id`. [[a-picker-name-is-not-a-wire-name]]
125
- LINKS = {
126
- # ── the TRANSACTION spine ──────────────────────────────────────────────────────────────
127
- PREFIX + "order_items": [
128
- ("amazon_order_id", PREFIX + "orders", "amazon_order_id"),
129
- # ⚠ the order report carries `sku`; listings key on `seller_sku`. Same value, two spellings.
130
- ("sku", PREFIX + "listings", "seller_sku"),
131
- ],
132
- PREFIX + "orders": [
133
- ("sku", PREFIX + "listings", "seller_sku"),
134
- ],
135
- # ⚠ SETTLEMENTS IS THE MONEY-TO-ORDER BRIDGE and the single most valuable join here: it is what
136
- # turns "an order happened" into "this is what we were actually paid for it". The V2 settlement
137
- # report carries the order id per line.
138
- PREFIX + "settlements": [
139
- ("amazon_order_id", PREFIX + "orders", "amazon_order_id"),
140
- ("sku", PREFIX + "listings", "seller_sku"),
141
- ],
142
- # ── the PRODUCT spine ──────────────────────────────────────────────────────────────────
143
- PREFIX + "pricing": [
144
- ("child_asin", PREFIX + "listings", "asin1"),
145
- ("sku", PREFIX + "listings", "seller_sku"),
146
- ],
147
- # ⚠ THE LEDGER KEYS ON `msku`, NOT `sku` — the FBA inventory vocabulary calls the seller's own
148
- # SKU the MSKU (merchant SKU). Same value, a third spelling, and the reason this map is derived
149
- # rather than assumed.
150
- PREFIX + "inventory": [
151
- ("msku", PREFIX + "listings", "seller_sku"),
152
- ("asin", PREFIX + "listings", "asin1"),
153
- ],
154
- # ⚠ brand_analytics is keyed by SEARCH TERM, not by product, so it joins to nothing by default.
155
- # Its ASIN columns are the top-clicked ASINs for a term, which is a different relationship from
156
- # "this row is about this product" and would be misleading as a link.
157
- }
158
 
159
  #: Columns whose NAME makes them a date whatever they are stored as. Amazon reports ISO-8601.
160
  _DATEISH = ("purchase_date", "last_updated_date", "payments_date", "settlement_start_date",
@@ -229,18 +168,23 @@ def _fields_for(cur, key):
229
  # map above declare hypotheses about report column names before any report has been seen.
230
  # ⚠ A TABLE MAY NOW CARRY SEVERAL LINKS. The first version allowed one, which could express the
231
  # transaction spine or the product spine but never both, and Amazon's data needs both.
232
- for col, target, on in LINKS.get(key, ()):
233
- if col not in names:
 
 
 
 
 
 
 
234
  continue
235
- if not any(c[0] == on for c in mirror_columns(cur, SOURCE.get(target, ""))):
 
236
  continue
237
  out.append(_odoo._preset({
238
- # ⚠ THE FIELD KEY CARRIES THE SOURCE COLUMN, not just the target. Two links to the
239
- # same table (orders by id and by sku) would otherwise collide on one key and the
240
- # second would silently overwrite the first.
241
- "key": f"{target}_link__{col}", "label": f"{LABELS[target]} by {_label(col)}",
242
  "type": "link", "source": "overlay", "default": True,
243
- "link": {"table": target, "on": on, "from": col},
244
  }, flow="amazon_relational"))
245
  out.append(_odoo._preset(_odoo._refreshed_field(), flow="amazon_relational"))
246
  return out
 
44
  sys.path.insert(0, str(_API.parent.parent / "platform"))
45
 
46
  import odoo_relational as _odoo # noqa: E402
47
+ from core import connector_spec # noqa: E402
48
  from harness import amazon_schema, amazon_store, datastore # noqa: E402
49
 
50
  Refused = _odoo.Refused
 
58
  #: exist on one side and not the other.
59
  SOURCE = {PREFIX + t: amazon_store.table_name(t) for t in amazon_store.TABLES}
60
 
61
+ #: ⭐⭐ **THE TABLE SHAPE IS NOW READ FROM `platform/core/connector_spec.py`, NOT TYPED HERE**
62
+ #: (W53-T37, contract C2). `LABELS`, `PINNED`, `IDENTITY` and `LINKS` keep their module-level
63
+ #: names because `verify_amazon`, `verify_meta.section_connector_spec` and the connector routes all
64
+ #: read them BY NAME — but each is a DERIVED VIEW over ONE declaration now, so the shape can no
65
+ #: longer be stated twice and say two things. Every comment that used to justify a literal here
66
+ #: (the two spines, R12, the report-vs-API spellings, the cardinalities) travelled with the values
67
+ #: into `connector_spec.AMAZON_TABLES`; read it there.
68
+ _SPEC = {s.key: s for s in connector_spec.tables_for("amazon")}
69
+
70
+ #: ⛔ A `ut_*` KEY THAT `amazon_store` SPAWNS BUT THE SPEC DOES NOT DECLARE IS ABSENT FROM ALL FOUR
71
+ #: DICTS BELOW, ON PURPOSE. `verify_amazon.section_relational` asserts the four key sets equal
72
+ #: `SOURCE`'s, so the drift reddens a gate rather than raising at import inside a live Space, and
73
+ #: it names the missing table instead of a KeyError deep in `apply_plan`.
74
+ LABELS = {k: _SPEC[k].label for k in SOURCE if k in _SPEC}
75
+
76
+ #: The column each grid shows first. ⚠ Every one is a name Amazon's own reports use, so a table
77
+ #: whose header does not carry it simply has no pinned column rather than a broken one.
78
+ PINNED = {k: _SPEC[k].pinned for k in SOURCE if k in _SPEC}
79
+
80
+ #: ⭐ THE ROW IDENTITY PER TABLE, IN FALLING PREFERENCE — a flat-file report has no `id` column the
81
+ #: way Graph does. When none is present the row is keyed by a hash of its own content (`_row_id`),
82
+ #: which still gives a STABLE id across re-syncs and is what makes the delete-then-insert merge
83
+ #: idempotent instead of appending a second copy of every row each time.
84
+ IDENTITY = {k: tuple(_SPEC[k].identity) for k in SOURCE if k in _SPEC}
85
+
86
+ #: `{ut_ key: [(this table's column, target ut_ key, the column it matches there), ...]}`.
87
+ #: ⚠ THE CARDINALITY IS DROPPED HERE AND KEPT IN THE SPEC. This view stays a 3-tuple because that
88
+ #: is the shape `verify_amazon.section_relational` unpacks; `connector_spec.edges_for` is what
89
+ #: `_fields_for` actually renders from, and it carries all four.
90
+ #: ⛔ AMAZON TO AMAZON ONLY (R12), and a link is DECLARED in the spec but VERIFIED AT SPAWN: five of
91
+ #: seven tables are `measured_at_sync`, so every entry is a hypothesis about a report column name
92
+ #: until `_fields_for` confirms BOTH sides carry it. A wrong guess here is cheap; a wrong guess in a
93
+ #: JOIN would not be. A table with no links is absent rather than present-and-empty, matching the
94
+ #: dict this replaced.
95
+ LINKS = {k: [(c, t, o) for c, t, o, _cardinality in _SPEC[k].links]
96
+ for k in SOURCE if k in _SPEC and _SPEC[k].links}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  #: Columns whose NAME makes them a date whatever they are stored as. Amazon reports ISO-8601.
99
  _DATEISH = ("purchase_date", "last_updated_date", "payments_date", "settlement_start_date",
 
168
  # map above declare hypotheses about report column names before any report has been seen.
169
  # ⚠ A TABLE MAY NOW CARRY SEVERAL LINKS. The first version allowed one, which could express the
170
  # transaction spine or the product spine but never both, and Amazon's data needs both.
171
+ # ⭐⭐ THE EDGE'S KEY AND LABEL COME FROM `connector_spec.edges_for`, NOT FROM AN f-STRING HERE
172
+ # (W53-T37). `f"{target}_link__{from_col}"` and `f"{label} by {_label(from_col)}"` are ONE
173
+ # convention shared by every connector: the source column is in the key because two links to
174
+ # the same target (orders by id and by sku) would otherwise collide on one key and the second
175
+ # would silently overwrite the first. Meta carried the older `f"{target}_link"` and therefore
176
+ # carried that collision, latent; a shared generator is what retires it for the next connector
177
+ # too, instead of each module re-typing the rule and one of them getting it wrong.
178
+ for edge in connector_spec.edges_for(key):
179
+ if edge["from_col"] not in names:
180
  continue
181
+ if not any(c[0] == edge["to_col"]
182
+ for c in mirror_columns(cur, SOURCE.get(edge["target"], ""))):
183
  continue
184
  out.append(_odoo._preset({
185
+ "key": edge["key"], "label": edge["label"],
 
 
 
186
  "type": "link", "source": "overlay", "default": True,
187
+ "link": {"table": edge["target"], "on": edge["to_col"], "from": edge["from_col"]},
188
  }, flow="amazon_relational"))
189
  out.append(_odoo._preset(_odoo._refreshed_field(), flow="amazon_relational"))
190
  return out
api/automation_engine.py CHANGED
@@ -13770,7 +13770,7 @@ def _rollup_fold(fn, values, ftype="text"):
13770
  LINKABLE_MODULES = ("customer_data", "product_data")
13771
 
13772
 
13773
- def _module_limit(subject, cause, recommendation, effect="unresolvable"):
13774
  """A refusal in `core.user_tables::limit_report`'s vocabulary — `{subject, effect, cause,
13775
  recommendation}`, the same four keys `perm_scope.Unresolvable.as_limit()` puts on the wire.
13776
 
@@ -13778,9 +13778,20 @@ def _module_limit(subject, cause, recommendation, effect="unresolvable"):
13778
  this engine cannot reach used to resolve to `{}` and blank the column, which reads exactly
13779
  like "there are no linked records". A reason a caller can render is the difference between a
13780
  measurement and a lie.
 
 
 
 
 
 
 
 
13781
  """
13782
- return {"subject": str(subject), "effect": effect,
13783
- "cause": str(cause), "recommendation": str(recommendation)}
 
 
 
13784
 
13785
 
13786
  def _module_link_fields(key):
@@ -13901,6 +13912,112 @@ def _module_table(rt, key, memo, want_rows=False):
13901
  return table, None
13902
 
13903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13904
  def _resolve_table(rt, store, key, memo, want_rows=False):
13905
  """A database by key, from EITHER namespace — `(table_or_None, limit_or_None)`.
13906
 
@@ -13909,9 +14026,31 @@ def _resolve_table(rt, store, key, memo, want_rows=False):
13909
  the TARGET table were two separate `store.get(...)` calls, C5 named only the target, and a
13910
  target-only fix leaves a link DECLARED ON `customer_data` returning 0 rows touched — which
13911
  reads exactly like "nothing needed doing".
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13912
  """
13913
- hit = (store or {}).get(str(key or ""))
 
13914
  if hit is not None:
 
 
 
 
 
13915
  return hit, None
13916
  return _module_table(rt, key, memo, want_rows=want_rows)
13917
 
@@ -14083,9 +14222,18 @@ def relation_cells(rt, table_key, tables=None):
14083
  if not links and not rollups:
14084
  return {}, limits
14085
  rows = (t or {}).get("rows") or {}
14086
- if not rows and t is not None and not t.get("_rows_built", True):
 
14087
  # A registry source: NOW the pool is worth its cost, because this table really does
14088
  # declare relations. One fetch, memoised, shared with every link and rollup below.
 
 
 
 
 
 
 
 
14089
  t, limit = _resolve_table(rt, store, table_key, memo, want_rows=True)
14090
  if limit is not None:
14091
  limits.append(limit)
@@ -14108,12 +14256,22 @@ def relation_cells(rt, table_key, tables=None):
14108
  want_rows=True)
14109
  if linked is None:
14110
  refused.add(lk_key)
14111
- limits.append(limit if limit is not None else _module_limit(
14112
- lk_key,
14113
- f"this link points at '{bag.get('table')}', which is not a database this "
14114
- f"workspace holds",
14115
- "re-point the link at an existing database, or delete the column; a link whose "
14116
- "target is gone is not a relation"))
 
 
 
 
 
 
 
 
 
 
14117
  continue
14118
  linked_types[lk_key] = {str(lf.get("key")): str(lf.get("type") or "text")
14119
  for lf in (linked.get("fields") or [])}
@@ -14130,6 +14288,108 @@ def relation_cells(rt, table_key, tables=None):
14130
  inverse_index.setdefault(target_id, []).append(
14131
  (str(source_id), source_row or {}))
14132
  resolved[lk_key] = {str(rid): inverse_index.get(str(rid), []) for rid in rows}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14133
  elif bag.get("on"):
14134
  idx = _linked_rows_by_join(linked, str(bag["on"]))
14135
  from_key = _link_from_key(fields, bag)
 
13770
  LINKABLE_MODULES = ("customer_data", "product_data")
13771
 
13772
 
13773
+ def _module_limit(subject, cause, recommendation, effect="unresolvable", limit=None):
13774
  """A refusal in `core.user_tables::limit_report`'s vocabulary — `{subject, effect, cause,
13775
  recommendation}`, the same four keys `perm_scope.Unresolvable.as_limit()` puts on the wire.
13776
 
 
13778
  this engine cannot reach used to resolve to `{}` and blank the column, which reads exactly
13779
  like "there are no linked records". A reason a caller can render is the difference between a
13780
  measurement and a lie.
13781
+
13782
+ ⭐ W53-T40 — `limit` IS OPTIONAL AND IS OMITTED UNLESS A NUMBER IS THE POINT, which keeps
13783
+ every refusal already shipped byte-identical. `core.user_tables.limit_report` carries the key
13784
+ on exactly the reports where a CEILING is the subject (`{'subject': 'rows', 'limit': 0,
13785
+ 'effect': 'read_through', ...}`), and the two W53-T40 reports below are that shape: a
13786
+ read-through grain whose ceiling here is 0, and a second-hop fan-out whose ceiling is
13787
+ `LINK_THROUGH_MAX_IDS`. Naming the number in prose alone would leave a caller parsing English
13788
+ to find out how much it did not get.
13789
  """
13790
+ out = {"subject": str(subject), "effect": effect,
13791
+ "cause": str(cause), "recommendation": str(recommendation)}
13792
+ if limit is not None:
13793
+ out["limit"] = int(limit)
13794
+ return out
13795
 
13796
 
13797
  def _module_link_fields(key):
 
13912
  return table, None
13913
 
13914
 
13915
+ def _as_field_limit(lk_key, base, context):
13916
+ """⭐ W53-T40 — ONE REFUSAL, RE-SUBJECTED FROM THE DATABASE IT IS ABOUT TO THE COLUMN IT BLANKS.
13917
+
13918
+ `_resolve_table` refuses in terms of the DATABASE it could not read, which is the right
13919
+ subject for its own caller and the WRONG one for a link: what a client renders is a COLUMN,
13920
+ and "which field is blank, and why" is the entire question `relation_cells`' second return
13921
+ value exists to answer. Every other refusal that function raises is already keyed on the field
13922
+ key; this keeps a refusal that arrives from one layer down in the same vocabulary.
13923
+
13924
+ ⛔ THE CAUSE AND THE RECOMMENDATION ARE CARRIED VERBATIM, never restated. The layer that
13925
+ refused knows why it refused; paraphrasing it here would be a second account of one fact, and
13926
+ the two would drift the first time the lower one is corrected. `context` is PREPENDED, so the
13927
+ route is stated and then the reason follows in the words of whoever had it.
13928
+ """
13929
+ base = base or {}
13930
+ return _module_limit(
13931
+ lk_key, (str(context or "").strip() + " " + str(base.get("cause") or "")).strip(),
13932
+ str(base.get("recommendation") or ""),
13933
+ effect=str(base.get("effect") or "unresolvable"), limit=base.get("limit"))
13934
+
13935
+
13936
+ def _mirror_table(rt, key, defn):
13937
+ """⭐⭐ W53-T40 (d)+(b) — A READ-THROUGH DATABASE'S ROWS, FROM THE CONNECTOR MIRROR, or a
13938
+ REFUSAL that names the field, the cause and the fix. `(table_or_None, limit_or_None)`.
13939
+
13940
+ ⛔ THIS IS TWO ARMS AND THEY ARE THE TICKET'S (d) AND (b), IN THAT ORDER.
13941
+
13942
+ (d) **NO READER REGISTERED ⇒ REFUSE, LOUDLY.** A read-through grid's stored document is a
13943
+ real definition with `rows: {}` — never `None` — so the old `if linked is None` refusal
13944
+ in `relation_cells` could not see it: the link fell through to the ordinary join arm,
13945
+ `_linked_rows_by_join` indexed an empty dict, every cell resolved to `[]`, and the
13946
+ column was permanently blank with NO `limit_report`. That is the one case
13947
+ `relation_cells`' own docstring says cannot happen, and it happened because the guard
13948
+ was keyed on the wrong sentinel. Re-keying it means making THIS function answer the
13949
+ real question — "are this database's rows resolvable here?" — so the existing `is None`
13950
+ test becomes true for the structurally-rows-absent case rather than being duplicated.
13951
+
13952
+ (b) **A READER IS REGISTERED ⇒ WALK IT.** The rows already exist and are already served:
13953
+ `routes_odoo_tables.GRID_SOURCES` renders them through `routes_tables._read_through_rows`,
13954
+ published as `core.perm_scope._MIRROR_READER` by `routes_tables._register_mirror`. What
13955
+ was missing was a CALLER. This is the caller.
13956
+
13957
+ ⭐⭐ THE SENTINEL IS `core.user_tables.materialises`, NOT A HAND-READ `readThrough` KEY, and
13958
+ the difference is a cold process. `materialises` is three-tier — the app-layer
13959
+ `register_read_through` set, then the definition's own `readThrough` STAMP written by
13960
+ `odoo_relational._ensure_table_inplace`, then the default — so a worker that never served a
13961
+ read-through grid still gets the right answer. A hand-read of the stamp alone would be one
13962
+ of those tiers pretending to be all three ([[one-evaluator-per-question]]).
13963
+
13964
+ ⛔ THE SHAPE IS COPIED FROM `core.perm_scope._read_user_table`, NOT INVENTED HERE. That
13965
+ function has carried exactly this branch since W38 — refuse when `_MIRROR_READER is None`,
13966
+ otherwise project the declared field keys and hand back the reader's rows — and a second
13967
+ spelling of it would be a second opinion about what a read-through read is.
13968
+
13969
+ ⚠ THE DOCUMENT IS COPIED, NEVER MUTATED. `store` is the live `user_tables` bucket; writing
13970
+ mirror rows into it would materialise the very grain R6 forbids materialising, in memory,
13971
+ silently, and then hand it to whatever reads the store next.
13972
+
13973
+ ⚠ `rt` RIDES INTO THE READER AS ITS THIRD ARGUMENT. `routes_tables._c1_mirror_rows` names
13974
+ that parameter `st` and passes it straight through to `_read_through_rows(..., rt=st)`, whose
13975
+ docstring says why it must be the SESSION'S runtime: one Space process serves every tenant
13976
+ and `datastore.ro_con()` reads a process-global path, so the tenant handle is the only thing
13977
+ standing between a relation pass and another tenant's mirror.
13978
+ """
13979
+ from core import perm_scope # lazy: the cycle rule `_ut()` documents
13980
+ key = str(key or "")
13981
+ reader = getattr(perm_scope, "_MIRROR_READER", None)
13982
+ if reader is None:
13983
+ # (d). ⛔ ASCII ONLY: this rides out in `limits` and can reach a client (standing rule 2).
13984
+ return None, _module_limit(
13985
+ key,
13986
+ f"'{key}' is served READ-THROUGH from the connector mirror, so it stores no rows in "
13987
+ f"this workspace document (row_limit 0), and no mirror reader is registered in this "
13988
+ f"process. A link resolved against its stored rows would find none and render a "
13989
+ f"permanently blank column that looks configured",
13990
+ "call `perm_scope.register_mirror(...)` from the app layer before resolving a "
13991
+ "relation at this grain (importing `routes_tables` does it), or read the grain "
13992
+ "directly through the API, where every total is a SQL count over the whole table",
13993
+ effect="read_through", limit=0)
13994
+ fields = list((defn or {}).get("fields") or [])
13995
+ wanted = {str(f.get("key")) for f in fields if f.get("key")}
13996
+ try:
13997
+ raw = list(reader(key, wanted, rt) or ())
13998
+ except Exception as e: # noqa: BLE001
13999
+ # ⛔ A MIRROR THAT CANNOT ANSWER IS A REASON, NOT AN OUTAGE, and `perm_scope.Unresolvable`
14000
+ # already carries the four keys this vocabulary wants: reuse them rather than flattening
14001
+ # a stated cause into `str(e)`.
14002
+ cause = str(getattr(e, "cause", "") or "") or f"{type(e).__name__}: {e}"
14003
+ return None, _module_limit(
14004
+ key,
14005
+ f"'{key}' is served READ-THROUGH from the connector mirror and the mirror could not "
14006
+ f"answer for it: {cause}",
14007
+ str(getattr(e, "recommendation", "") or "")
14008
+ or ("retry once the connector mirror has finished opening on this process, or read "
14009
+ "the grain a window at a time through the API"),
14010
+ effect=str(getattr(e, "effect", "") or "read_through"), limit=0)
14011
+ # `pid` IS THE ROW ID on every read-through grid — `routes_tables` stamps it onto each row it
14012
+ # serves and `_read_through_rows` keeps it through the projection. A row without one cannot be
14013
+ # addressed by a link cell at all, so it is dropped rather than given an invented id.
14014
+ table = dict(defn or {})
14015
+ table["key"] = key
14016
+ table["rows"] = {str(r.get("pid")): dict(r) for r in raw if (r or {}).get("pid") is not None}
14017
+ table["_rows_built"] = True
14018
+ return table, None
14019
+
14020
+
14021
  def _resolve_table(rt, store, key, memo, want_rows=False):
14022
  """A database by key, from EITHER namespace — `(table_or_None, limit_or_None)`.
14023
 
 
14026
  the TARGET table were two separate `store.get(...)` calls, C5 named only the target, and a
14027
  target-only fix leaves a link DECLARED ON `customer_data` returning 0 rows touched — which
14028
  reads exactly like "nothing needed doing".
14029
+
14030
+ ⭐⭐ W53-T40 — AND THAT IS ALSO WHY THE READ-THROUGH BRANCH LANDS HERE RATHER THAN IN EITHER
14031
+ CALLER. `_PRODUCT_LINK_BLOCKER` named this symbol as "the door BOTH of them go through", so a
14032
+ third namespace — the connector MIRROR — is one branch here instead of two branches that must
14033
+ be kept in step. A stored document is never `None`, so before this branch existed a
14034
+ read-through target came back as a real definition with `rows: {}` and every caller read that
14035
+ as "no linked records".
14036
+
14037
+ ⚠ ONLY WHEN `want_rows`. The field contract of a read-through grid is in the stored document
14038
+ like everybody else's, and `relation_cells` resolves the source table fields-only precisely so
14039
+ a table with no links pays nothing. Reaching the mirror for a fields-only resolve would put a
14040
+ 256,593-row read behind a dict scan.
14041
+
14042
+ ⚠ MEMOISED ON A TUPLE KEY. `_module_table` memoises on the bare key; a mirror table for the
14043
+ same key is a different object with a different cost, and both can be wanted in one pass (the
14044
+ bridge of a two-hop is resolved once per link field).
14045
  """
14046
+ key = str(key or "")
14047
+ hit = (store or {}).get(key)
14048
  if hit is not None:
14049
+ if want_rows and not _ut().materialises(key, defn=hit):
14050
+ cached = memo.get(("mirror", key))
14051
+ if cached is None:
14052
+ cached = memo[("mirror", key)] = _mirror_table(rt, key, hit)
14053
+ return cached
14054
  return hit, None
14055
  return _module_table(rt, key, memo, want_rows=want_rows)
14056
 
 
14222
  if not links and not rollups:
14223
  return {}, limits
14224
  rows = (t or {}).get("rows") or {}
14225
+ if not rows and t is not None and (not t.get("_rows_built", True)
14226
+ or not _ut().materialises(table_key, defn=t)):
14227
  # A registry source: NOW the pool is worth its cost, because this table really does
14228
  # declare relations. One fetch, memoised, shared with every link and rollup below.
14229
+ # ⭐⭐ W53-T40 (d) — AND A READ-THROUGH SOURCE TAKES THE SAME SECOND FETCH, for a reason
14230
+ # that is not symmetry. `_rows_built` is the REGISTRY sentinel; a read-through `ut_*`
14231
+ # document carries no such key, so `.get("_rows_built", True)` answered True, `rows` stayed
14232
+ # `{}`, and a link DECLARED ON a read-through grain returned `{}` cells with no limit —
14233
+ # the same silent blank on the source side that (d) ends on the target side. The predicate
14234
+ # is `materialises`, the one evaluator of "are this database's rows stored here", and the
14235
+ # cheap-by-construction guarantee is untouched because this sits BELOW the declaration
14236
+ # check: a table with no links and no rollups has already returned.
14237
  t, limit = _resolve_table(rt, store, table_key, memo, want_rows=True)
14238
  if limit is not None:
14239
  limits.append(limit)
 
14256
  want_rows=True)
14257
  if linked is None:
14258
  refused.add(lk_key)
14259
+ if str((limit or {}).get("effect")) == "read_through":
14260
+ # ⭐ W53-T40 (d) — THE NEW REFUSAL IS RE-SUBJECTED ONTO THE FIELD, and ONLY the new
14261
+ # one. `_module_table`'s pre-existing refusals are passed through in their own
14262
+ # words exactly as they always were; re-keying those would churn a report other
14263
+ # callers already read. This arm did not exist before this ticket, so nothing
14264
+ # downstream has an older reading of it to protect.
14265
+ limits.append(_as_field_limit(
14266
+ lk_key, limit,
14267
+ f"this link points at '{bag.get('table')}' and its rows could not be read."))
14268
+ else:
14269
+ limits.append(limit if limit is not None else _module_limit(
14270
+ lk_key,
14271
+ f"this link points at '{bag.get('table')}', which is not a database this "
14272
+ f"workspace holds",
14273
+ "re-point the link at an existing database, or delete the column; a link "
14274
+ "whose target is gone is not a relation"))
14275
  continue
14276
  linked_types[lk_key] = {str(lf.get("key")): str(lf.get("type") or "text")
14277
  for lf in (linked.get("fields") or [])}
 
14288
  inverse_index.setdefault(target_id, []).append(
14289
  (str(source_id), source_row or {}))
14290
  resolved[lk_key] = {str(rid): inverse_index.get(str(rid), []) for rid in rows}
14291
+ elif bag.get("through"):
14292
+ # ⭐⭐ W53-T40 (b)+(c) — THE TWO-HOP TRAVERSAL, AND IT IS TRAVERSAL, NOT AGGREGATION.
14293
+ # R12 keeps aggregation at depth 1; this walks `source -> bridge -> target` and hands
14294
+ # the TARGET ROWS back in the same `resolved[link][row_id] = [(id, row), ...]` shape
14295
+ # every one-hop arm above produces, so every rollup, cap and cell below is unchanged.
14296
+ #
14297
+ # ⛔ THE INDEX IS `_linked_rows_by_join` ON BOTH HOPS AND THE NORMALISER IS
14298
+ # `_join_norm` ON BOTH SIDES OF BOTH. `_join_norm`'s own docstring says why: a join is
14299
+ # a comparison, and a comparison normalised in two places is one edit from silently
14300
+ # reporting zero. A second spelling here would be four half-comparisons instead of two.
14301
+ #
14302
+ # ⛔ THE ROUTE THIS SHIPS FOR IS `customer_data -> ut_odoo_order_lines ->
14303
+ # product_data`, and it is the ONLY route Odoo declares between a partner and a
14304
+ # product: `sale.order.line` carries `order_partner_id` and `product_id`, both stored.
14305
+ # ⛔ THERE IS NO INVOICE ROUTE AND THERE MUST NOT BE ONE THROUGH THIS GRAIN. Invoice to
14306
+ # line to product is THREE hops and the first of them, `invoice_origin`, is FREE TEXT
14307
+ # filled on 34.1% of posted invoices — a depth-3 path over a weak hop returns a
14308
+ # confidently wrong number rather than an error.
14309
+ through_key = str(bag.get("through") or "")
14310
+ on_key = str(bag.get("on") or "")
14311
+ hop_in = str(bag.get("throughOn") or "")
14312
+ hop_out = str(bag.get("throughTo") or "")
14313
+ from_key = _link_from_key(fields, bag)
14314
+ if not (on_key and hop_in and hop_out and from_key):
14315
+ # ⛔ REFUSED, NOT BLANK — the same law the one-hop arm below follows. A route with
14316
+ # a missing leg has no second hop to make; resolving it to `[]` would render a
14317
+ # permanently blank column that looks configured. `_clean_link` refuses this shape
14318
+ # at the definition door, so reaching here means a bag that never went through it.
14319
+ refused.add(lk_key)
14320
+ limits.append(_module_limit(
14321
+ lk_key,
14322
+ f"this link travels through '{through_key}' but the route is incomplete. A "
14323
+ f"two-hop join names four columns: `from` on '{table_key}', `throughOn` and "
14324
+ f"`throughTo` on the bridge, and `on` on '{bag.get('table')}'. Present here: "
14325
+ f"from={from_key or '(none)'}, throughOn={hop_in or '(none)'}, "
14326
+ f"throughTo={hop_out or '(none)'}, on={on_key or '(none)'}",
14327
+ "declare every leg of the route on the link, or remove `through` and let it "
14328
+ "be the one-hop join it is actually configured as"))
14329
+ continue
14330
+ # THE BRIDGE, THROUGH THE SAME DOOR AS THE SOURCE AND THE TARGET. This is where the
14331
+ # read-through refusal lands for the shipped route: `ut_odoo_order_lines` stores no
14332
+ # rows in this document on purpose, so `_resolve_table` reaches the mirror for it, or
14333
+ # refuses with a cause and a fix when no reader is registered in this process.
14334
+ bridge, limit = _resolve_table(rt, store, through_key, memo, want_rows=True)
14335
+ if bridge is None:
14336
+ refused.add(lk_key)
14337
+ limits.append(_as_field_limit(
14338
+ lk_key, limit,
14339
+ f"this link travels {table_key} -> {through_key} -> {bag.get('table')} and "
14340
+ f"the bridge could not be read.") if limit is not None else _module_limit(
14341
+ lk_key,
14342
+ f"this link travels through '{through_key}', which is not a database this "
14343
+ f"workspace holds",
14344
+ "re-point the link's `through` at an existing database, or delete the "
14345
+ "column; a route across a database that is gone is not a relation"))
14346
+ continue
14347
+ bridge_idx = _linked_rows_by_join(bridge, hop_in)
14348
+ target_idx = _linked_rows_by_join(linked, on_key)
14349
+ cap = int(_ut().LINK_THROUGH_MAX_IDS)
14350
+
14351
+ def _walk(row, _bidx=bridge_idx, _tidx=target_idx, _cap=cap):
14352
+ """One source row's DISTINCT target records, and whether the ceiling stopped it.
14353
+
14354
+ ⚠ DE-DUPED ON THE TARGET ROW ID. A customer orders the same SKU on twenty lines;
14355
+ twenty copies of one product in the cell would be a count of LINES wearing the
14356
+ label of a set of PRODUCTS.
14357
+ """
14358
+ seen, out = set(), []
14359
+ for _bid, brow in _bidx.get(_join_norm((row or {}).get(from_key)), ()):
14360
+ for tid, trow in _tidx.get(_join_norm((brow or {}).get(hop_out)), ()):
14361
+ if tid in seen:
14362
+ continue
14363
+ if len(out) >= _cap:
14364
+ return out, True
14365
+ seen.add(tid)
14366
+ out.append((tid, trow))
14367
+ return out, False
14368
+
14369
+ two_hop, capped = {}, 0
14370
+ for rid, row in rows.items():
14371
+ hits_2, hit_cap = _walk(row)
14372
+ two_hop[str(rid)] = hits_2
14373
+ capped += 1 if hit_cap else 0
14374
+ resolved[lk_key] = two_hop
14375
+ if capped:
14376
+ # ⭐⭐ STANDING RULE 1'S SECOND SENTENCE, AND IT IS THE HALF THAT GETS DROPPED: a
14377
+ # limit that genuinely cannot be removed is REPORTED, with cause and a recommended
14378
+ # fix, never silently enforced. ⛔ AND THIS ONE IS LOUDER THAN THE `LINK_MAX_IDS`
14379
+ # display cap, because it is a different quantity: the display cap slices the CELL
14380
+ # and leaves `resolved` whole for the rollups, while this bounds `resolved`
14381
+ # ITSELF — so a rollup folded over a capped row describes a subset.
14382
+ # ⛔ ASCII ONLY: this rides out in `limits` and can reach a client.
14383
+ limits.append(_module_limit(
14384
+ lk_key,
14385
+ f"this link travels {table_key} -> {through_key} -> {bag.get('table')}, and "
14386
+ f"{capped} of {len(rows)} rows reached the {cap}-record fan-out ceiling on "
14387
+ f"the second hop. Those cells, and any rollup folded over them, describe the "
14388
+ f"first {cap} distinct records rather than the whole set",
14389
+ "narrow the route with a `filter` on the link, or read the bridge grain "
14390
+ "directly through the API, where every total is a SQL count over the whole "
14391
+ "table rather than over a resolved window",
14392
+ effect="capped", limit=cap))
14393
  elif bag.get("on"):
14394
  idx = _linked_rows_by_join(linked, str(bag["on"]))
14395
  from_key = _link_from_key(fields, bag)
api/meta_relational.py CHANGED
@@ -40,10 +40,14 @@ if str(_API.parent.parent / "platform") not in sys.path:
40
  sys.path.insert(0, str(_API.parent.parent / "platform"))
41
 
42
  import odoo_relational as _odoo # noqa: E402
 
43
  from harness import datastore, meta_store # noqa: E402
44
 
45
  Refused = _odoo.Refused
46
 
 
 
 
47
  ACCOUNTS_KEY = "ut_meta_ad_accounts"
48
  CAMPAIGNS_KEY = "ut_meta_campaigns"
49
  ADSETS_KEY = "ut_meta_adsets"
@@ -51,36 +55,47 @@ ADS_KEY = "ut_meta_ads"
51
  CREATIVES_KEY = "ut_meta_creatives"
52
  INSIGHTS_KEY = "ut_meta_insights"
53
 
54
- #: ut_* key -> the mirror table `meta_store` writes.
55
- SOURCE = {
56
- ACCOUNTS_KEY: "meta_ad_accounts",
57
- CAMPAIGNS_KEY: "meta_campaigns",
58
- ADSETS_KEY: "meta_adsets",
59
- ADS_KEY: "meta_ads",
60
- CREATIVES_KEY: "meta_creatives",
61
- INSIGHTS_KEY: meta_store.INSIGHTS_TABLE,
62
- }
63
-
64
- LABELS = {
65
- ACCOUNTS_KEY: "Meta ad accounts", CAMPAIGNS_KEY: "Meta campaigns",
66
- ADSETS_KEY: "Meta ad sets", ADS_KEY: "Meta ads",
67
- CREATIVES_KEY: "Meta creatives", INSIGHTS_KEY: "Meta insights (daily)",
68
- }
 
 
 
69
 
70
  #: The column each grid shows first. Everything else keeps the API's own order, which is the order
71
  #: the schema was measured in — a reader comparing the grid to Graph sees the same sequence.
72
- PINNED = {ACCOUNTS_KEY: "name", CAMPAIGNS_KEY: "name", ADSETS_KEY: "name",
73
- ADS_KEY: "name", CREATIVES_KEY: "name", INSIGHTS_KEY: "date_start"}
74
 
75
- #: (this table's column) -> (target ut_ key, the column it matches there). Derived links, so a
 
 
 
 
 
 
 
76
  #: person can walk account -> campaign -> ad set -> ad in the product the way they do in Ads
77
- #: Manager. ⚠ Only emitted when BOTH sides exist in the mirror.
78
- LINKS = {
79
- CAMPAIGNS_KEY: ("account_id", ACCOUNTS_KEY, "account_id"),
80
- ADSETS_KEY: ("campaign_id", CAMPAIGNS_KEY, "id"),
81
- ADS_KEY: ("adset_id", ADSETS_KEY, "id"),
82
- INSIGHTS_KEY: ("ad_id", ADS_KEY, "id"),
83
- }
 
 
84
 
85
  #: DuckDB type -> `core.user_tables.UT_FIELD_TYPES` member. ⚠ `_clean_field` returns None for an
86
  #: unknown type, which DELETES the column on the next read rather than erroring — so this map only
@@ -131,7 +146,7 @@ def _fields_for(cur, key):
131
  if not cols:
132
  return []
133
  pinned = PINNED.get(key)
134
- link = LINKS.get(key)
135
  out = []
136
  for name, dtype in cols:
137
  f = {"key": name, "label": _label(name), "type": _ftype(name, dtype),
@@ -139,13 +154,18 @@ def _fields_for(cur, key):
139
  "impressions", "clicks", "date_start"),
140
  "pinned": name == pinned}
141
  out.append(_odoo._preset(f, flow="meta_relational"))
142
- if link:
143
- col, target, on = link
144
- if any(c[0] == col for c in cols):
 
 
 
 
145
  out.append(_odoo._preset(
146
- {"key": f"{target}_link", "label": LABELS[target], "type": "link",
147
  "source": "overlay", "default": True,
148
- "link": {"table": target, "on": on, "from": col}}, flow="meta_relational"))
 
149
  out.append(_odoo._preset(_odoo._refreshed_field(), flow="meta_relational"))
150
  return out
151
 
 
40
  sys.path.insert(0, str(_API.parent.parent / "platform"))
41
 
42
  import odoo_relational as _odoo # noqa: E402
43
+ from core import connector_spec # noqa: E402
44
  from harness import datastore, meta_store # noqa: E402
45
 
46
  Refused = _odoo.Refused
47
 
48
+ #: The six tables this module spawns, as names rather than repeated string literals. ⚠ They are the
49
+ #: same six keys `connector_spec.META_TABLES` declares; `INSIGHTS_KEY` is the one still USED below,
50
+ #: so a typo in it grows `SOURCE` a seventh entry and `verify_meta`'s coverage leg reddens.
51
  ACCOUNTS_KEY = "ut_meta_ad_accounts"
52
  CAMPAIGNS_KEY = "ut_meta_campaigns"
53
  ADSETS_KEY = "ut_meta_adsets"
 
55
  CREATIVES_KEY = "ut_meta_creatives"
56
  INSIGHTS_KEY = "ut_meta_insights"
57
 
58
+ #: ⭐⭐ **THE TABLE SHAPE IS NOW READ FROM `platform/core/connector_spec.py`, NOT TYPED HERE**
59
+ #: (W53-T37, contract C2). `SOURCE`, `LABELS`, `PINNED`, `IDENTITY` and `LINKS` keep their
60
+ #: module-level names because gates and routes read them BY NAME — but each is a DERIVED VIEW over
61
+ #: ONE declaration now, and Amazon's copy of the same five dicts is derived from the same file. Two
62
+ #: connectors stating one shape in two dialects is what C2 exists to end.
63
+ _SPEC = {s.key: s for s in connector_spec.tables_for("meta")}
64
+
65
+ #: ut_* key -> the mirror table `meta_store` writes, in the spec's declaration order (which is the
66
+ #: order `meta_store` syncs them, and the order `plan` therefore walks).
67
+ SOURCE = {k: s.source for k, s in _SPEC.items()}
68
+ #: ⚠ ONE ENTRY STAYS DERIVED FROM THE LOADER RATHER THAN FROM THE SPEC, ON PURPOSE. The daily
69
+ #: insights grain is the only Meta mirror table whose name `meta_store` also owns
70
+ #: (`meta_store.INSIGHTS_TABLE`), and reading it from there keeps `verify_meta`'s Meta-source parity
71
+ #: leg a REAL cross-check for that table instead of comparing the spec with itself. The other five
72
+ #: mirror names exist only in the spec, so there is nothing to hold them against.
73
+ SOURCE[INSIGHTS_KEY] = meta_store.INSIGHTS_TABLE
74
+
75
+ LABELS = {k: s.label for k, s in _SPEC.items()}
76
 
77
  #: The column each grid shows first. Everything else keeps the API's own order, which is the order
78
  #: the schema was measured in — a reader comparing the grid to Graph sees the same sequence.
79
+ PINNED = {k: s.pinned for k, s in _SPEC.items()}
 
80
 
81
+ #: ⭐ THE ROW IDENTITY PER TABLE, IN FALLING PREFERENCE, NEW IN W53-T37 — this module had no
82
+ #: `IDENTITY` at all before the spec declared one. ⚠ NOTHING IN THIS MODULE READS IT YET: `_read`
83
+ #: keys every row on the Graph `id` inline, so this is the spec's answer made reachable by name for
84
+ #: the callers that will ask (the relation engine, the connector detail door), not a behaviour
85
+ #: change. Wiring a consumer that did not exist is a different ticket.
86
+ IDENTITY = {k: tuple(s.identity) for k, s in _SPEC.items()}
87
+
88
+ #: `{ut_ key: [(this table's column, target ut_ key, the column it matches there), ...]}`, so a
89
  #: person can walk account -> campaign -> ad set -> ad in the product the way they do in Ads
90
+ #: Manager. ⚠ Only emitted when this table's own mirror carries the column.
91
+ #: ⛔⛔ **A LIST PER KEY, NOT A SCALAR 3-TUPLE** (W53-T37, and it is the point of the ticket). The
92
+ #: old scalar could hold exactly one edge per table, and the key it generated was
93
+ #: `f"{target}_link"` — so a SECOND edge to the same target would have collided on both the field
94
+ #: key and the field label and silently overwritten the first. Meta's chain is linear today, so
95
+ #: nothing collided and no gate was red; it was latent, and Amazon had already fixed the same
96
+ #: defect. The shape and the generated key are now Amazon's, from one shared generator.
97
+ LINKS = {k: [(c, t, o) for c, t, o, _cardinality in s.links]
98
+ for k, s in _SPEC.items() if s.links}
99
 
100
  #: DuckDB type -> `core.user_tables.UT_FIELD_TYPES` member. ⚠ `_clean_field` returns None for an
101
  #: unknown type, which DELETES the column on the next read rather than erroring — so this map only
 
146
  if not cols:
147
  return []
148
  pinned = PINNED.get(key)
149
+ names = {c[0] for c in cols}
150
  out = []
151
  for name, dtype in cols:
152
  f = {"key": name, "label": _label(name), "type": _ftype(name, dtype),
 
154
  "impressions", "clicks", "date_start"),
155
  "pinned": name == pinned}
156
  out.append(_odoo._preset(f, flow="meta_relational"))
157
+ # ⭐⭐ EVERY EDGE OF THIS TABLE, FROM THE SHARED GENERATOR (W53-T37). `connector_spec.edges_for`
158
+ # mints `f"{target}_link__{from_col}"` and `f"{target label} by {source column}"` — Amazon's
159
+ # convention, now everyone's. ⛔ THE SOURCE COLUMN IS IN THE KEY ON PURPOSE: this loop used to
160
+ # read a single scalar link and key it `f"{target}_link"`, so a second edge to one target would
161
+ # have overwritten the first on both the key and the label, with nothing raising.
162
+ for edge in connector_spec.edges_for(key):
163
+ if edge["from_col"] in names:
164
  out.append(_odoo._preset(
165
+ {"key": edge["key"], "label": edge["label"], "type": "link",
166
  "source": "overlay", "default": True,
167
+ "link": {"table": edge["target"], "on": edge["to_col"],
168
+ "from": edge["from_col"]}}, flow="meta_relational"))
169
  out.append(_odoo._preset(_odoo._refreshed_field(), flow="meta_relational"))
170
  return out
171
 
api/odoo_relational.py CHANGED
@@ -49,8 +49,10 @@ the oracle's predicate as an explicit `payment_state` condition pair.
49
  """
50
  import datetime as _dt
51
 
52
- #: Royal Imports only (R1). A tenant slug that is not this one gets a refusal, never a spawn:
53
- #: nurilab has no Odoo mirror behind these tables and would get empty locked databases.
 
 
54
  RI_SLUGS = ("", "royal-imports")
55
 
56
  INVOICES_KEY = "ut_odoo_invoices"
@@ -921,20 +923,30 @@ def module_link_fields(key):
921
  `ut_odoo_invoices` answers the ALL-CHANNELS question (the Amazon partner alone is 75% of the
922
  raw balance), so the same key would carry two numbers 4x apart depending on which pass ran
923
  last. That is the second-source-for-one-fact defect this module refuses everywhere else.
924
- * ⭐⭐ **D-492, CHECKED BEFORE ANYTHING NEW WAS ADDED (W46-T42, 2026-08-30) AND IT STILL
925
- HOLDS.** The register says two links a prior instruction DECLARED were never built. Read off
926
- this function at HEAD, both are confirmed absent and neither was faked to close the row:
927
- `customer_data` returns `invoices`, `orders` and `agent_link` and no *"Products ordered"*;
928
- `product_data` returns `[]` unconditionally (the `if str(key or "") != "customer_data"`
929
- guard on the first line), so *"Customers who ordered"* is never declared at all. They are
930
- the SAME two-hop blocker, not two independent misses, and `_PRODUCT_LINK_BLOCKER` below is
931
- their single stated reason. ⛔ A link declared to close D-492 without that blocker lifted
932
- would render permanently blank with no `limit_report`, which is worse than the open row.
933
-
934
- * **NO LINK ON `product_data` AT ALL** — see `_PRODUCT_LINK_BLOCKER` below for what it would
935
- take. Declaring one anyway is the worst available outcome: `ut_odoo_order_lines` EXISTS in
936
- the store with zero rows, so `_resolve_table` finds it, nothing is refused, no
937
- `limit_report` is raised, and the column renders permanently blank while looking configured.
 
 
 
 
 
 
 
 
 
 
938
 
939
  ⚠ THE FIELD BAG IS SHAPED FOR THE RENDER WIRE THAT DOES NOT EXIST YET. `routes_customers` /
940
  `routes_products` still build their field lists from `aios_grid` alone, so today these columns
@@ -966,159 +978,141 @@ def module_link_fields(key):
966
  "description": "The agent record for this account, matched on the agent name. Blank "
967
  "when the account has no agent or carries more than one.",
968
  "link": {"table": AGENTS_KEY, "on": AGENT_NAME_KEY, "from": AGENT_NAME_KEY}},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
969
  )]
970
 
971
 
972
- #: ⛔⛔ "PRODUCTS ORDERED" / "CUSTOMERS WHO ORDERED" CANNOT BE DECLARED HERE YET, AND THE REASON IS
973
- #: NOT A MISSING DECLARATION — IT IS A MISSING PRIMITIVE. Recorded as data so the next lane reads
974
- #: a measurement rather than an empty function.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
975
  #:
976
- #: WHAT ODOO SAYS (read from `ir.model.fields`, not assumed): `product.product` declares NO
977
- #: COMMERCIAL relation to `res.partner`. ⚠ THE SENTENCE HERE USED TO SAY "no relation to
978
- #: `res.partner` AT ALL", and D-492 is right that this was OVERSTATED — corrected 2026-08-30 in
979
- #: W46-T42 rather than left standing, because a claim a reader can falsify in one grep costs the
980
- #: surviving conclusion its authority. `product.product` inherits `mail.thread`, so
981
- #: `message_partner_ids` (the generic FOLLOWERS relation) is a genuine many2many to `res.partner`
982
- #: on this model. It is not a customer relation: a follower is whoever subscribed to the record's
983
- #: chatter, it answers no question about who ORDERED the product, and joining through it would
984
- #: mint a "customers who ordered" column populated by subscriptions. The other partner-shaped
985
- #: field is `seller_ids`, an unstored one2many to `product.supplierinfo`, which is VENDORS. So the
986
- #: evidence changes and THE CONCLUSION SURVIVES: the one declared path between a customer
987
- #: and a product is `sale.order.line`, which carries `order_partner_id` (many2one to `res.partner`)
988
- #: and `product_id` (many2one to `product.product`), both stored. So the relation is real, Odoo
989
- #: does not declare it directly, and it is exactly TWO HOPS.
990
  #:
991
- #: WHY NEITHER HOP IS EXPRESSIBLE TODAY:
992
- #: 1. `relation_cells` resolves a link with ONE index lookup — `_linked_rows_by_join(target, on)`
993
- #: probed by the source row's single `from` value. There is no `through` leg in the bag
994
- #: vocabulary (`core.user_tables._clean_link` accepts table/on/from/inverse/reciprocal/via/
995
- #: single/filter, and returns None for anything mis-shaped) and no two-hop branch in the
996
- #: engine. ⚠ `via` IS NOT A TABLE HOP and reading it as one is the easy mistake here:
997
- #: `_clean_via` demands topic/source_dim/target_dim/target_key/scope_key/measure and refuses
998
- #: unless the dims belong to a semantic topic, and `automation_engine` reads a link bag's
999
- #: `via` ZERO times.
1000
- #: 2. ⛔⛔ THE BRIDGE HAS ROWS. THIS ITEM SAID THE OPPOSITE UNTIL W46-T41 MEASURED IT, and the
1001
- #: correction changes what the missing piece IS. `routes_odoo_tables.GRID_SOURCES` already
1002
- #: serves `ut_odoo_order_lines` from the DuckDB mirror by SQL (`sale_order_line` joined to
1003
- #: `sale_order` on the confirmed scope), `routes_tables._read_through_rows` renders it, and
1004
- #: `routes_tables._register_mirror` publishes that reader as `core.perm_scope._MIRROR_READER`.
1005
- #: MEASURED 2026-08-29: 256,593 in-scope rows, 256,502 of them carrying a `product_id`
1006
- #: (`_ORDER_LINE_GRAIN` below). What is empty is the `user_tables` DOCUMENT, not the system:
1007
- #: `row_limit` answers 0 and `plan()` builds zero python rows, by design and on purpose.
1008
- #: So the absence is A CALLER, not data — `automation_engine._resolve_table` returns the
1009
- #: stored doc first (`hit = (store or {}).get(key); if hit is not None: return hit, None`) and
1010
- #: carries no mirror branch at all, while `_linked_rows_by_join` indexes only
1011
- #: `(linked or {}).get("rows")`.
1012
- #: 2b. ⛔⛔ AND THAT IS WHY DECLARING THE LINK ANYWAY IS THE WORST AVAILABLE OUTCOME, in the
1013
- #: words of the engine's own docstring. `relation_cells` says of its second return value:
1014
- #: *"A link whose target cannot be reached is SKIPPED … and a `limit_report`-shaped dict says
1015
- #: which field, why, and what to do … a link with no matching records and a link that could
1016
- #: not be resolved BOTH leave the key out of `cells`, and only this list tells them apart."*
1017
- #: The function was rewritten expressly to end the silent blank. For a read-through target it
1018
- #: still produces one, and the reason is small and exact: the refusal predicate is
1019
- #: `if linked is None`, and `_resolve_table` hands back a stored definition, which is never
1020
- #: None. So this link lands in the ONE case the docstring says cannot happen — no `cells` key
1021
- #: AND no `limits` entry, indistinguishable from "no matching records" by the very
1022
- #: discriminator that docstring names. The guard is not missing; it is KEYED ON THE WRONG
1023
- #: SENTINEL. Standing rule 1's second sentence fails on that path, which is the whole reason
1024
- #: the link is refused here rather than declared.
1025
- #: 3. `inverse` cannot carry the other end either. It reads the source row's STORED cell, and a
1026
- #: registry module stores no rows here: its grid is assembled per render from the tenant pool,
1027
- #: so the reciprocal cell a pool row would need is precisely the projection being computed.
1028
  #:
1029
- #: WHAT IT WOULD TAKE (four parts, one ticket, and none of them in this file):
1030
- #: (a) a `through` leg on the link bag, resolved as a two-hop join in `automation_engine`;
1031
- #: (b) bridge rows served from the DuckDB MIRROR rather than the `user_tables` document, because
1032
- #: order lines are read-through on purpose and materialising them is the thing R6 forbade.
1033
- #: ⭐ The reader for (b) ALREADY EXISTS and is already registered; what (b) needs is the door
1034
- #: into it — a read-through branch in `_resolve_table`, the one symbol the other two both
1035
- #: pass through;
1036
- #: (c) a cap-and-report story for the fan-out under standing rule 1 — the widest customer's
1037
- #: basket and the widest product's buyer list both need a display cap plus a
1038
- #: `limit_report`-shaped account of it, never a silent truncation;
1039
- #: (d) ⭐ THE CHEAPEST OF THE FOUR AND THE ONE THAT STOPS THE SILENT FAILURE ON ITS OWN: re-key
1040
- #: `relation_cells`' refusal off `linked is None` and onto "resolved a document whose rows
1041
- #: are structurally absent". The signal is already written and already durable —
1042
- #: `_ensure_table_inplace` in this module stamps `readThrough: True` on exactly those
1043
- #: definitions, and `core.user_tables.materialises` reads it. Landing (d) first converts
1044
- #: every premature link at a read-through grain from a permanently blank column into a
1045
- #: `limit_report` that names the field and the fix.
1046
  #:
1047
- #: ⭐⭐ W46-T41 — IT IS THREE HOPS FOR AN INVOICE, NOT TWO, AND THE WAVE'S OWN DOCUMENTS SAY TWO.
1048
- #: Recorded because the correction outlives the ticket. `ut_odoo_order_lines` IS `sale.order.line`,
1049
- #: which hangs off `sale.order` and NOT off `account.move`, so the two readings differ:
1050
- #: • ORDER -> LINE -> PRODUCT is genuinely two hops, and it is what C5's own wording describes
1051
- #: ("keyed by `order_id` and `product_id`"). This grain can serve it the day (a)+(b) land.
1052
- #: • INVOICE -> LINE -> PRODUCT through THIS grain is THREE hops, and the first of them is a
1053
- #: free-text hint rather than a key: `invoice_fields`' existing `order_link` matches
1054
- #: `origin_order` (Odoo's `invoice_origin`, a NAME) to `order_no`. MEASURED 2026-08-29:
1055
- #: `invoice_origin` is filled on 10,706 of 31,418 posted customer invoices (34.1%), of which
1056
- #: 10,683 match a `sale_order.name`; `_sync_state` shows the `account_move.cols.invoice_origin`
1057
- #: backfill still in phase `running` at 35,000 of 236,811 rows since 2026-08-15. So the first
1058
- #: hop of that route is a third populated and its own backfill is unfinished.
1059
- #: ⚠ THE HONEST TWO-HOP ROUTE FOR AN INVOICE IS THE OTHER GRAIN, and it is named here rather than
1060
- #: built because it is blocked by the identical engine gap. `account_move_line` carries `move_id`,
1061
- #: `product_id` AND `sale_line_id`, so INVOICE -> `ut_odoo_gl_lines` -> PRODUCT is a real two hops
1062
- #: (measured 2026-08-29: 477,852 of 511,167 posted customer invoice lines carry a `product_id`,
1063
- #: across 30,164 of 31,418 invoices). Two things stand in the way: `ut_odoo_gl_lines` is the OTHER
1064
- #: read-through grain, so items 2 and 2b above apply to it unchanged, and `gl_line_fields` does not
1065
- #: expose `product_id` today. A future ticket takes that route; this one does not.
1066
- _PRODUCT_LINK_BLOCKER = {
1067
- "subject": "product_data / customer_data: Products ordered and Customers who ordered",
1068
  "effect": "unresolvable",
1069
- # ⛔ THE `cause` CHANGED IN W46-T41 AND THE OLD ONE WAS WRONG IN A LOAD-BEARING WAY. It read
1070
- # "the bridge grain ut_odoo_order_lines is read-through by design and stores no rows to walk",
1071
- # which is true of the `user_tables` DOCUMENT and false of the system: the rows are measured,
1072
- # served and registered elsewhere. A blocker that blames missing DATA sends the next lane to
1073
- # materialise 256,593 rows, which is the one thing R6 forbade; a blocker that names the missing
1074
- # CALLER sends it to the three symbols in `blocked_by`.
1075
- # ⚠ ASCII ONLY IN THESE VALUES. They travel into `plan()`'s `limits` report and can reach a
1076
- # client, where standing rule 2 forbids an em dash or an en dash.
1077
- "cause": "the only relation Odoo declares between a partner and a product runs through "
1078
- "sale.order.line (order_partner_id then product_id), which is two hops, and the "
1079
- "relation engine resolves ONE. The bridge rows are NOT missing: measured 2026-08-29 "
1080
- "on the DuckDB mirror, ut_odoo_order_lines holds 256,593 in-scope rows of which "
1081
- "256,502 carry a product_id, and they are ALREADY SERVED to the grid by "
1082
- "routes_odoo_tables.GRID_SOURCES through routes_tables._read_through_rows, whose "
1083
- "reader is registered as core.perm_scope._MIRROR_READER. What is absent is a caller: "
1084
- "automation_engine._resolve_table returns the stored user_tables document first and "
1085
- "carries no read-through branch, and the link vocabulary in "
1086
- "core.user_tables._clean_link has no `through` key (its `via` is a semantic-topic "
1087
- "measure route, not a table hop, and the engine never reads it). So a link declared "
1088
- "today fails SILENTLY rather than loudly, and the engine's own docstring says why "
1089
- "that is the worst outcome available: relation_cells promises that an unreachable "
1090
- "target is skipped WITH a limit_report, because a link with no matching records and "
1091
- "a link that could not be resolved both leave the key out of cells and only that "
1092
- "report tells them apart. Its refusal is keyed on `linked is None`, and a stored "
1093
- "definition is never None, so this link lands in the one case that docstring says "
1094
- "cannot happen: no cell, no limit report, and a permanently blank column that looks "
1095
- "configured. The guard is not missing, it is keyed on the wrong sentinel. That is "
1096
- "why the link is refused here instead of declared",
1097
- "recommendation": "four parts, one ticket, and neither file is this one. (a) "
1098
- "platform/core/user_tables.py::_clean_link accepts a `through` key in the "
1099
- "link vocabulary and validates its target the way it validates `table`. "
1100
- "(b) aios-web/api/automation_engine.py opens the door and walks the second "
1101
- "hop: give _resolve_table a read-through branch that calls the registered "
1102
- "mirror reader instead of returning an empty stored document, then teach "
1103
- "relation_cells to resolve table -> through -> target. (c) both halves need "
1104
- "a fan-out display cap that is REPORTED through limit_report rather than "
1105
- "applied silently, per standing rule 1. (d) cheapest and independently "
1106
- "worth doing FIRST: re-key relation_cells' refusal from `linked is None` "
1107
- "onto `the resolved document stores no rows here`, which the readThrough "
1108
- "stamp already written by odoo_relational._ensure_table_inplace answers, so "
1109
- "that a premature link at a read-through grain reports instead of "
1110
- "blanking. Until these land, keep refusing the link: a blank configured "
1111
- "column is worse than an absent one",
1112
- # ⭐ THE BLOCKING SYMBOLS AS DATA, NOT PROSE, so `verify_odoo_relational.py` can read the
1113
- # source of each one and go RED the day the blocking property stops holding. A refusal whose
1114
- # reason has silently expired is precisely the defect that tripwire exists to prevent.
1115
- # ⚠ `_resolve_table` is in the list although the prose leads with the other two, and that is
1116
- # deliberate: it is the door BOTH of them go through, so a mirror branch landing there would
1117
- # unblock this ticket while `relation_cells` and `_clean_link` still read exactly as today.
1118
- "blocked_by": ("platform/core/user_tables.py::_clean_link",
1119
- "aios-web/api/automation_engine.py::_resolve_table",
1120
- "aios-web/api/automation_engine.py::relation_cells"),
1121
- "rows_exist_at": "aios-web/api/routes_odoo_tables.py::GRID_SOURCES['ut_odoo_order_lines'] -> "
1122
  "routes_tables._read_through_rows (the same reader is registered as "
1123
  "core.perm_scope._MIRROR_READER by routes_tables._register_mirror)",
1124
  }
@@ -1157,7 +1151,7 @@ _PRODUCT_LINK_BLOCKER = {
1157
  #: the label "DBA" would put a SECOND definition of one fact under one name, which is the
1158
  #: defect `module_link_fields`' own "NO ROLLUPS" note refuses for `ar_outstanding` and which
1159
  #: this module refuses everywhere else.
1160
- #: ⚠ ASCII ONLY IN THESE VALUES, like `_PRODUCT_LINK_BLOCKER` above: they travel into `plan()`'s
1161
  #: `limits` report and can reach a client, where standing rule 2 forbids an em dash or an en dash.
1162
  _DBA_NAME_BLOCKER = {
1163
  "subject": "ut_odoo_invoices: the DBA or trade name",
@@ -1875,6 +1869,215 @@ def authoritative_schema_snapshot():
1875
  return models, errors
1876
 
1877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1878
  #: ⭐⭐ W49-T25 / C6 — THE COMPILED REGISTRY GRIDS, AND THIS MAP IS WHERE THE WHOLE TICKET LIVES.
1879
  #:
1880
  #: `TABLES` above declares the eight mirror grids owned by THIS file. The products and customers
@@ -2614,9 +2817,59 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp):
2614
 
2615
 
2616
  def is_royal(tenant):
 
 
 
 
 
 
 
 
2617
  return str(tenant or "").strip().lower() in RI_SLUGS
2618
 
2619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2620
  def refresh(rt, tenant, username="automation", cur=None, today=None):
2621
  """THE entry point — the store-resync path and the route both call this.
2622
 
@@ -2624,16 +2877,34 @@ def refresh(rt, tenant, username="automation", cur=None, today=None):
2624
  still carries a `refreshed` stamp, so a stale worklist is at least LEGIBLE rather than
2625
  silently authoritative.
2626
  """
2627
- if not is_royal(tenant):
2628
- raise Refused(f"tenant {tenant!r} has no Odoo mirror behind these tables (R1: Royal "
2629
- f"Imports only); refusing to spawn empty locked databases")
2630
- # ⭐⭐ W31-T45 / D-169 — THE SLUG GATE ABOVE AND THE FILE GATE HERE ANSWER DIFFERENT QUESTIONS,
2631
- # and this is the one place in the codebase where that is easy to miss. `is_royal` asks "is
2632
- # this tenant ENTITLED to Odoo databases"; it says nothing about WHICH DuckDB file this process
2633
- # has open. A worker pinned to another tenant's store (AIOS_DUCKDB_PATH, or a `use_path` in a
2634
- # provisioning script) passes `is_royal("royal-imports")` and then WRITES tenant #0's locked
2635
- # databases from another customer's rows — a spawn, not a read, so the wrong numbers become
2636
- # durable. Entitlement is not residency.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2637
  # ⚠ It runs when `cur` is LENT too, not only when we open one: the resync loop and the boot
2638
  # rebuild both hand a cursor in, and a lent cursor is exactly the case where nobody re-checks.
2639
  if rt is not None:
 
49
  """
50
  import datetime as _dt
51
 
52
+ #: ⛔ ROUTE ENTITLEMENT, NOT THE SPAWN GATE — `refresh()` stopped reading this at W53-T39 / R3,
53
+ #: which admits on CONFIGURED CREDENTIALS (`available()`) so a second Odoo tenant needs no edit.
54
+ #: It stays because five modules outside this one still gate ROUTES on `is_royal`, and because
55
+ #: `is_royal("")` is deliberately True with a `verify_automation` leg pinning that.
56
  RI_SLUGS = ("", "royal-imports")
57
 
58
  INVOICES_KEY = "ut_odoo_invoices"
 
923
  `ut_odoo_invoices` answers the ALL-CHANNELS question (the Amazon partner alone is 75% of the
924
  raw balance), so the same key would carry two numbers 4x apart depending on which pass ran
925
  last. That is the second-source-for-one-fact defect this module refuses everywhere else.
926
+ * ⭐⭐ **D-492 IS HALF CLOSED, AND THE HALF THAT CLOSED IS THE ONE WITH A MECHANISM (W53-T40,
927
+ 2026-09-05).** The register said two links a prior instruction DECLARED were never built.
928
+ W46-T42 confirmed both absent and refused to fake either; both were the SAME missing
929
+ primitive, and W53-T40 built it. So `customer_data` now returns `invoices`, `orders`,
930
+ `agent_link` AND `products_ordered` — a resolving two-hop column, not a blank one. ⛔ THE
931
+ OLD WARNING HERE READ *"a link declared to close D-492 without that blocker lifted would
932
+ render permanently blank with no `limit_report`"*, and it stays true as a WARNING: what
933
+ changed is that the blocker was lifted first, in the order its own prescription named.
934
+ ⚠ *"Customers who ordered"* on `product_data` is STILL not declared, and its reason has
935
+ changed from unresolvable to simply undeclared — see the next bullet.
936
+
937
+ * **NO LINK ON `product_data` AT ALL, AND IT IS NO LONGER A BLOCKED ONE.** The `if str(key or
938
+ "") != "customer_data"` guard on the first line of this function is why, and that is now the
939
+ whole reason: since W53-T40 the engine walks `source -> through -> target` in either
940
+ direction, so `product_data.product_id -> ut_odoo_order_lines.product_id ->
941
+ ut_odoo_order_lines.partner_id -> customer_data.pid` is a route the same `through` arm would
942
+ resolve today. W53-T40's `done-when` named ONE direction, so one direction shipped; the
943
+ reverse is a declaration nobody has asked for, not a missing primitive. ⛔ THE HISTORICAL
944
+ HAZARD IS RECORDED BECAUSE IT IS WHAT THE FIX WAS ABOUT: declaring this link BEFORE that
945
+ ticket was the worst available outcome, because `ut_odoo_order_lines` EXISTS in the store
946
+ with zero rows, `_resolve_table` found it, nothing was refused, no `limit_report` was
947
+ raised, and the column rendered permanently blank while looking configured. That path is
948
+ closed — `_resolve_table` now reaches the mirror or REPORTS — but the shape of the mistake
949
+ is worth keeping.
950
 
951
  ⚠ THE FIELD BAG IS SHAPED FOR THE RENDER WIRE THAT DOES NOT EXIST YET. `routes_customers` /
952
  `routes_products` still build their field lists from `aios_grid` alone, so today these columns
 
978
  "description": "The agent record for this account, matched on the agent name. Blank "
979
  "when the account has no agent or carries more than one.",
980
  "link": {"table": AGENTS_KEY, "on": AGENT_NAME_KEY, "from": AGENT_NAME_KEY}},
981
+ # ⭐⭐ W53-T40 / D-492 — "PRODUCTS ORDERED", THE TWO-HOP THAT USED TO BE REFUSED HERE.
982
+ # `_PRODUCT_LINK_BLOCKER` stood below this list and named four missing parts; all four
983
+ # landed in W53-T40 and the blocker was retired with them (see the note where it stood).
984
+ #
985
+ # ⛔ THE ROUTE IS THE ONE ODOO DECLARES, AND IT IS THE ONLY ONE. `product.product` has no
986
+ # commercial relation to `res.partner` — `message_partner_ids` is the chatter FOLLOWERS
987
+ # many2many and `seller_ids` is VENDORS — so the single declared path is `sale.order.line`,
988
+ # which carries `order_partner_id` (many2one to `res.partner`) and `product_id` (many2one
989
+ # to `product.product`), both stored. ORDER -> LINE -> PRODUCT is genuinely TWO hops.
990
+ # ⛔ AND THE INVOICE ROUTE IS STILL REFUSED. Invoice to line to product through this grain
991
+ # is THREE hops and its first is `invoice_origin`, free text filled on 34.1% of posted
992
+ # invoices (10,706 of 31,418, measured 2026-08-29) whose backfill is unfinished. A depth-3
993
+ # path over a weak hop returns a confidently wrong number instead of an error.
994
+ #
995
+ # ⚠ THE COLUMN SPELLINGS, EACH TAKEN FROM THE GRAIN THAT OWNS IT rather than retyped:
996
+ # `from` `customer_data.pid` IS the `res.partner` id (CUSTOMER_JOIN_FROM).
997
+ # `throughOn` `order_line_fields()` spells `order_partner_id` as JOIN_KEY, `partner_id`.
998
+ # `throughTo` the line's `product.product` id, PRODUCT_JOIN_KEY.
999
+ # `on` `product_data` carries Odoo's own id under PRODUCT_JOIN_KEY BESIDE its
1000
+ # hashed `pid` (W33-T43 / R2). ⛔ IT CANNOT BE `pid` HERE: `product_data.pid`
1001
+ # is `crc32(default_code)`, so joining a line's product id to it would match
1002
+ # nothing while looking exactly like a configured column.
1003
+ #
1004
+ # ⚠ `default: False`, AND THAT IS A COST STATEMENT RATHER THAN TIMIDITY. The bridge is
1005
+ # read-through: resolving this column reaches the connector mirror for 256,593 order
1006
+ # lines. The other two links resolve out of documents already in hand, so they may paint
1007
+ # on first render; this one is OFFERED and painted when asked for.
1008
+ {"key": "products_ordered", "label": "Products ordered", "type": "link", "source": "odoo",
1009
+ "derived": True, "default": False,
1010
+ "description": "Every product this customer has ordered on a confirmed order, resolved "
1011
+ "through the order lines. Distinct products, not a count of lines.",
1012
+ "link": {"table": "product_data", "on": PRODUCT_JOIN_KEY, "from": CUSTOMER_JOIN_FROM,
1013
+ "through": ORDER_LINES_KEY, "throughOn": JOIN_KEY,
1014
+ "throughTo": PRODUCT_JOIN_KEY}},
1015
  )]
1016
 
1017
 
1018
+ #: ⭐⭐ W53-T40, 2026-09-05 — `_PRODUCT_LINK_BLOCKER` STOOD HERE AND IS **RETIRED**, BECAUSE ALL
1019
+ #: FOUR PARTS OF ITS OWN PRESCRIPTION LANDED. It is removed rather than left with a stale `effect`,
1020
+ #: and this note is what stands in its place: a refusal that has expired is a lie no test notices,
1021
+ #: and the tripwire in `verify_odoo_relational.py` existed to catch exactly the day it expired.
1022
+ #:
1023
+ #: WHAT IT SAID, AND WHAT ANSWERED IT — part by part, in the order it prescribed:
1024
+ #: (d) *"re-key `relation_cells`' refusal from `linked is None` onto 'the resolved document
1025
+ #: stores no rows here'"*. ANSWERED at `automation_engine._mirror_table` + `_resolve_table`:
1026
+ #: the sentinel is `core.user_tables.materialises` (the three-tier predicate OVER the
1027
+ #: `readThrough` stamp, not a hand-read of the stamp), and `_resolve_table` now answers
1028
+ #: `(None, limit)` for a database whose rows are structurally absent, so the existing
1029
+ #: `is None` test became true for that case instead of being duplicated beside it. A
1030
+ #: premature link at a read-through grain now REPORTS with a cause and a fix.
1031
+ #: (a) *"`_clean_link` accepts a `through` key and validates its target the way it validates
1032
+ #: `table`"*. ANSWERED at `core.user_tables._clean_link`: `through` is validated by
1033
+ #: `is_linkable_target`, joined by `throughOn` / `throughTo` (the bridge's two ends, which
1034
+ #: are genuinely different columns), refused without an `on`, and refused when the bridge IS
1035
+ #: the target.
1036
+ #: (b) *"give `_resolve_table` a read-through branch that calls the registered mirror reader,
1037
+ #: then teach `relation_cells` to resolve table -> through -> target"*. ANSWERED at
1038
+ #: `automation_engine._mirror_table` (the door) and `relation_cells`' `through` arm (the
1039
+ #: walk). The reader was never missing — `routes_odoo_tables.GRID_SOURCES` has served these
1040
+ #: rows through `routes_tables._read_through_rows` all along, registered as
1041
+ #: `core.perm_scope._MIRROR_READER`. What was missing was a CALLER, and that was the whole
1042
+ #: correction W46-T41 made to this blocker's `cause`.
1043
+ #: (c) *"a fan-out display cap that is REPORTED through limit_report"*. ANSWERED at
1044
+ #: `core.user_tables.LINK_THROUGH_MAX_IDS` (5,000 distinct target records per source row)
1045
+ #: and the `effect: "capped"` report `relation_cells` emits when any row reaches it.
1046
  #:
1047
+ #: ⭐ AND THE COLUMN IS DECLARED: `module_link_fields("customer_data")` above now returns
1048
+ #: `products_ordered`, `customer_data -> ut_odoo_order_lines -> product_data`, which is D-492's
1049
+ #: first half closed with a resolving column rather than with a blank one.
 
 
 
 
 
 
 
 
 
 
 
1050
  #:
1051
+ #: ⛔⛔ WHAT DID **NOT** EXPIRE, AND IS KEPT BELOW RATHER THAN SWEPT UP WITH IT. Two of the old
1052
+ #: blocker's clauses were never about the engine, so landing the engine work changed nothing about
1053
+ #: them, and retiring a refusal whose condition survives is worse than leaving it standing:
1054
+ #: * THE INVOICE ROUTE. Still refused, still for its own reason, and it now has its own dict
1055
+ #: (`_INVOICE_PRODUCT_LINK_BLOCKER` below) so it cannot be read as a leftover of this one.
1056
+ #: * "CUSTOMERS WHO ORDERED" ON `product_data`. ⚠ ITS REASON CHANGED AND SO THE SENTENCE HAD TO
1057
+ #: BE REWRITTEN RATHER THAN DELETED. It is no longer UNRESOLVABLE: the mechanism is symmetric
1058
+ #: and the reverse route (`product_data.product_id -> ut_odoo_order_lines.product_id ->
1059
+ #: ut_odoo_order_lines.partner_id -> customer_data.pid`) is walkable by the same `through` arm
1060
+ #: the moment somebody declares it. It is simply NOT DECLARED — W53-T40's `done-when` names
1061
+ #: one direction, so one direction is what shipped and the other is a declaration nobody has
1062
+ #: asked for yet, not a missing primitive. `module_link_fields` still returns `[]` for
1063
+ #: `product_data` and its guard is the first line of that function.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1064
  #:
1065
+ #: ⛔ THE MEASUREMENTS SURVIVE THEIR BLOCKER and are kept because standing rule 8 wants the number
1066
+ #: rather than the adjective: the bridge holds 256,593 in-scope rows of which 256,502 carry a
1067
+ #: `product_id` (measured 2026-08-29; the machine-readable form is `_ORDER_LINE_GRAIN` below), and
1068
+ #: `product.product` still declares NO commercial relation to `res.partner` — `message_partner_ids`
1069
+ #: is the `mail.thread` FOLLOWERS many2many and `seller_ids` is an unstored one2many to
1070
+ #: `product.supplierinfo`, i.e. VENDORS. Neither answers "who ordered this", which is why
1071
+ #: `sale.order.line` is the only route and why it is two hops.
1072
+
1073
+ #: ⛔⛔ W53-T40 — THE **INVOICE** TO PRODUCT ROUTE IS STILL REFUSED, AND THIS IS THE SURVIVING HALF
1074
+ #: OF `_PRODUCT_LINK_BLOCKER` RESTATED TO WHAT IS ACTUALLY TRUE TODAY. Its cause is DATA, never the
1075
+ #: engine: the engine now walks two hops and would walk these too, which is precisely why the
1076
+ #: refusal has to be written down instead of assumed. A route that has become MECHANICALLY possible
1077
+ #: while remaining EVIDENTIALLY wrong is the one a future lane is most likely to build by accident.
 
 
 
 
1078
  #:
1079
+ #: ⚠ ASCII ONLY IN THESE VALUES. They travel into `plan()`'s `limits` report and can reach a
1080
+ #: client, where standing rule 2 forbids an em dash or an en dash.
1081
+ _INVOICE_PRODUCT_LINK_BLOCKER = {
1082
+ "subject": "ut_odoo_invoices: Products invoiced",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1083
  "effect": "unresolvable",
1084
+ "cause": "there are two candidate routes from an invoice to a product and BOTH are refused, "
1085
+ "for reasons that have nothing to do with the relation engine (which resolves two "
1086
+ "hops since W53-T40). ROUTE 1, through ut_odoo_order_lines, is THREE hops rather "
1087
+ "than two: sale.order.line hangs off sale.order and not off account.move, so the "
1088
+ "first hop is invoice_fields' order_link, which matches origin_order (Odoo's "
1089
+ "invoice_origin, a NAME) to order_no. MEASURED 2026-08-29: invoice_origin is filled "
1090
+ "on 10,706 of 31,418 posted customer invoices (34.1%), of which 10,683 match a "
1091
+ "sale_order.name, and _sync_state shows the account_move.cols.invoice_origin "
1092
+ "backfill still in phase running at 35,000 of 236,811 rows since 2026-08-15. A "
1093
+ "depth-3 path whose first hop is free text populated on a third of the population "
1094
+ "returns a confidently wrong number instead of an error. ROUTE 2 is the honest two "
1095
+ "hops and is blocked on a COLUMN: account_move_line carries move_id, product_id AND "
1096
+ "sale_line_id, so invoice -> ut_odoo_gl_lines -> product_data is a real two-hop "
1097
+ "traversal (measured 2026-08-29: 477,852 of 511,167 posted customer invoice lines "
1098
+ "carry a product_id, across 30,164 of 31,418 invoices), but gl_line_fields does not "
1099
+ "expose product_id, so the bridge grain has no column for the second hop to read",
1100
+ "recommendation": "take ROUTE 2 and never ROUTE 1. Expose product_id on gl_line_fields and "
1101
+ "on the ut_odoo_gl_lines mirror projection in routes_odoo_tables, then "
1102
+ "declare a link on ut_odoo_invoices with from=odoo_id, "
1103
+ "through=ut_odoo_gl_lines, throughOn=move_id (that grain already carries "
1104
+ "the account.move id under exactly that key), throughTo=product_id, "
1105
+ "table=product_data and on=product_id. The engine needs no further change: "
1106
+ "core.user_tables._clean_link accepts the route and "
1107
+ "automation_engine.relation_cells walks it. Until that column exists, keep "
1108
+ "refusing: a link declared over invoice_origin would populate and would be "
1109
+ "wrong on two thirds of the rows",
1110
+ # ⭐ THE BLOCKING SYMBOL AS DATA rather than prose, so `verify_odoo_relational.py` can read its
1111
+ # source and go RED the day the blocking property stops holding. ⛔ IT IS ONE SYMBOL NOW, NOT
1112
+ # THREE: the three the old blocker named were engine symbols and all three have changed. What
1113
+ # is left is a missing COLUMN on one field builder, which is a claim about this very file.
1114
+ "blocked_by": ("aios-web/api/odoo_relational.py::gl_line_fields",),
1115
+ "rows_exist_at": "aios-web/api/routes_odoo_tables.py::GRID_SOURCES['ut_odoo_gl_lines'] -> "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1116
  "routes_tables._read_through_rows (the same reader is registered as "
1117
  "core.perm_scope._MIRROR_READER by routes_tables._register_mirror)",
1118
  }
 
1151
  #: the label "DBA" would put a SECOND definition of one fact under one name, which is the
1152
  #: defect `module_link_fields`' own "NO ROLLUPS" note refuses for `ar_outstanding` and which
1153
  #: this module refuses everywhere else.
1154
+ #: ⚠ ASCII ONLY IN THESE VALUES, like `_INVOICE_PRODUCT_LINK_BLOCKER` above: they travel into `plan()`'s
1155
  #: `limits` report and can reach a client, where standing rule 2 forbids an em dash or an en dash.
1156
  _DBA_NAME_BLOCKER = {
1157
  "subject": "ut_odoo_invoices: the DBA or trade name",
 
1869
  return models, errors
1870
 
1871
 
1872
+ #: ⭐⭐ W53-T38 / C2 — THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD.
1873
+ #:
1874
+ #: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py`
1875
+ #: (W53-T36). Odoo's equivalent could not be transcribed there for one reason: **`core` never
1876
+ #: imports up**, so a spec that must name `JOIN_KEY`, `PRODUCT_JOIN_KEY`, `TABLES` and the field
1877
+ #: builders has to be DECLARED HERE and REGISTERED into that module. `register()` exists for that.
1878
+ #:
1879
+ #: ⛔⛔ **THIS DECLARATION IS SEVEN KEYS ABOUT A TABLE AND IT IS NOT A LINK FIELD.** It sits BESIDE
1880
+ #: `module_link_fields` and does not touch it. `module_link_fields` is reached BY STRING through
1881
+ #: `getattr(_rel, "module_link_fields", None)` from `automation_engine._module_link_fields`, so
1882
+ #: renaming it, moving it or folding it into anything raises NO ImportError and silently kills
1883
+ #: every pre-set relation column on `customer_data`. Nothing below is emitted as a field, appears
1884
+ #: in a `*_fields()` builder, or reaches `_link_bags()` in the gate. An edge here is a DECLARATION
1885
+ #: the relation reader consults; a link bag is a COLUMN the automation engine resolves. They are
1886
+ #: different objects with different consumers, and this file keeps them apart on purpose.
1887
+ #:
1888
+ #: ⛔ **R12 — DEPTH 2, EVERY HOP NAMED, AND DECLARING AN EDGE HERE CREATES NO ROLLUP.** Aggregation
1889
+ #: stays at depth 1. `ORDER_LINES_KEY -> PRODUCTS_KEY` is declared below, and W53-T40 has since
1890
+ #: built the LINK FIELD half of the same relation (`module_link_fields("customer_data")`'s
1891
+ #: `products_ordered`, a two-hop TRAVERSAL). ⚠ THE TWO REMAIN DIFFERENT OBJECTS AND THE FACT THAT
1892
+ #: BOTH NOW EXIST IS EXACTLY WHY THIS SENTENCE STAYS: an edge here is a DECLARATION the relation
1893
+ #: reader consults, a link bag is a COLUMN the automation engine resolves, and neither creates a
1894
+ #: rollup. Aggregation is still depth 1. This note used to read *"`_PRODUCT_LINK_BLOCKER` further
1895
+ #: up this file is STILL unresolvable ... W53-T40 is the ticket that does"*; that ticket landed on
1896
+ #: 2026-09-05 and the blocker is retired, so the sentence was rewritten rather than left standing.
1897
+ #: ⛔ **AND THE INVOICE -> LINE -> PRODUCT ROUTE IS DELIBERATELY ABSENT.** Its first hop is
1898
+ #: `invoice_origin`, free text filled on 34.1% of posted invoices (measured 2026-08-29, recorded at
1899
+ #: `_INVOICE_PRODUCT_LINK_BLOCKER` above, which is the surviving half of the retired blocker). A
1900
+ #: depth-3 path over a weak hop returns a confidently wrong number instead of an error, so no
1901
+ #: `invoice_origin` edge is declared here at any time.
1902
+ #:
1903
+ #: ⛔ **R9 — `native` IS NEVER EDITABLE AND `label` IS ONLY A DEFAULT.** The labels below are our
1904
+ #: SHIPPED defaults; a tenant's rename lives in `platform/core/schema_overlay.py`, per tenant, and a
1905
+ #: connector re-sync must never write it. Nothing here is a place to store an override.
1906
+
1907
+ #: `native`, DERIVED rather than re-typed. `ODOO_TABLE_MODELS` above already declares the Odoo model
1908
+ #: behind eight of the ten keys and is the map `authoritative_schema_snapshot` is built around; a
1909
+ #: second literal map beside it would be a second source for one fact. It is missing only the two
1910
+ #: keys W33-T44 retired from `TABLES`, so exactly those two are supplied here.
1911
+ #: ⭐ `PRODUCTS_KEY` IS `product.product`, NOT `product.template`, and the code is what settles it:
1912
+ #: `read_products` reads `FROM product_product` and keys every row on `PRODUCT_JOIN_KEY`, whose own
1913
+ #: field description reads "The `product.product` id. Also this row's id". A template is the family;
1914
+ #: a variant is the thing an order line actually names.
1915
+ _RETIRED_NATIVE = {
1916
+ CUSTOMERS_KEY: "res.partner",
1917
+ PRODUCTS_KEY: "product.product",
1918
+ }
1919
+
1920
+ #: The shipped default label for the two retired keys. The other eight come from `TABLES`' own third
1921
+ #: element and are transcribed into `ODOO_SPEC` below, where the gate holds the two spellings equal.
1922
+ _RETIRED_LABEL = {
1923
+ CUSTOMERS_KEY: "Odoo customers",
1924
+ PRODUCTS_KEY: "Odoo products",
1925
+ }
1926
+
1927
+ #: The identity column of a grid AS THE WIRE SPELLS IT. `routes_tables` stamps `pid` onto every row
1928
+ #: it serves (`r["pid"] = int(rid)`), and `core.relations.IDENTITY_COL` is this same string with the
1929
+ #: same meaning. It is taken from `CUSTOMER_JOIN_FROM` rather than re-typed, because that constant
1930
+ #: already IS this value under the name the customer leg reads it by.
1931
+ _ROW_ID_COL = CUSTOMER_JOIN_FROM
1932
+
1933
+ #: Every edge below is `many_to_one` for one uniform reason: each is a CHILD row naming its PARENT.
1934
+ #: The reverse direction is NEVER declared here. `core.relations.reverse_links` scans for tables
1935
+ #: pointing at a target and its docstring says the rule outright: "Nothing declares a reverse link;
1936
+ #: this scan IS the declaration". Declaring an edge from both ends is two sources for one fact.
1937
+ _M2O = "many_to_one"
1938
+
1939
+
1940
+ def _native_model(key):
1941
+ """The Odoo model behind one `ut_odoo_*` key. `ODOO_TABLE_MODELS` first, the two retired keys
1942
+ second, and a KeyError rather than a shrug for anything else."""
1943
+ return ODOO_TABLE_MODELS.get(key) or _RETIRED_NATIVE[key]
1944
+
1945
+
1946
+ #: ⭐⭐ THE TEN TABLES. **`links` NAMES THE CHILD'S COLUMN, THE TARGET KEY, THE TARGET'S COLUMN AND
1947
+ #: THE CARDINALITY**, in that order, matching `ConnectorTableSpec.links`.
1948
+ #:
1949
+ #: ⚠ THESE ARE PLAIN DICTS, NOT `ConnectorTableSpec` INSTANCES, AND THAT IS FORCED. `core` is not
1950
+ #: importable at the moment this module is imported (`_ut` and `_registry` above are lazy for that
1951
+ #: exact reason, and `import core.connector_spec` raises `ModuleNotFoundError` on a bare
1952
+ #: `import odoo_relational` from `aios-web/api`). The dataclass is constructed inside
1953
+ #: `register_connector_spec()` below, where the import has already succeeded.
1954
+ #:
1955
+ #: ⚠ `to_col` IS `pid` WHEREVER THE TARGET IS MATCHED ON ITS ROW IDENTITY. The one exception is
1956
+ #: `ACCOUNT_JOIN_KEY`, which is an ordinary column on both sides: a GL line carries the account CODE
1957
+ #: and `ut_odoo_accounts` is keyed by that code, never by a partner id.
1958
+ #: ⚠ `AGENTS_KEY` and `VENDORS_KEY` are ALSO reachable on their own `agent_id` / `vendor_id`
1959
+ #: columns, which is how the existing link FIELDS in `customer_fields` and `bill_fields` spell the
1960
+ #: same join (`{"on": AGENT_JOIN_KEY}` / `{"on": VENDOR_JOIN_KEY}`). Both resolve to the identical
1961
+ #: `res.partner` id (`read_agents` and `read_vendors` write the row id into both), so the spec uses
1962
+ #: the one column every grid carries rather than a per-table spelling.
1963
+ ODOO_SPEC = (
1964
+ {"key": INVOICES_KEY, "source": "account_move", "label": "Odoo invoices",
1965
+ "pinned": "invoice_no", "identity": (_ROW_ID_COL, "odoo_id"),
1966
+ "links": ((JOIN_KEY, CUSTOMERS_KEY, _ROW_ID_COL, _M2O),)},
1967
+
1968
+ # ⚠ RETIRED FROM `TABLES` BY W33-T44, DECLARED HERE ANYWAY, AND THAT IS THE POINT OF A SPEC.
1969
+ # `RETIRED_KEYS` pops this key and `PRODUCTS_KEY` from a tenant's document on every sync, but
1970
+ # the key constants, the field builders and the readers in `_READERS` all still exist, the
1971
+ # compiled twins `customer_data` / `product_data` present the same subjects, and the done-when
1972
+ # asks for ten. A spec DESCRIBES a table's shape; it does not assert the table is materialised.
1973
+ {"key": CUSTOMERS_KEY, "source": "res_partner", "label": _RETIRED_LABEL[CUSTOMERS_KEY],
1974
+ "pinned": "customer", "identity": (_ROW_ID_COL, JOIN_KEY),
1975
+ # ⚠ `AGENT_JOIN_KEY`, NEVER `JOIN_KEY`. An agent IS a `res.partner`, so both ids live in one
1976
+ # namespace and joining agents through `JOIN_KEY` would link every customer to itself and look
1977
+ # entirely plausible doing it. The same warning stands on `AGENT_JOIN_KEY`'s own declaration.
1978
+ "links": ((AGENT_JOIN_KEY, AGENTS_KEY, _ROW_ID_COL, _M2O),)},
1979
+
1980
+ {"key": ORDERS_KEY, "source": "sale_order", "label": "Odoo orders",
1981
+ "pinned": "order_no", "identity": (_ROW_ID_COL, "odoo_id"),
1982
+ "links": ((JOIN_KEY, CUSTOMERS_KEY, _ROW_ID_COL, _M2O),)},
1983
+
1984
+ # ⚠ RETIRED FROM `TABLES` like `CUSTOMERS_KEY` above, and declared for the same reason.
1985
+ {"key": PRODUCTS_KEY, "source": "product_product", "label": _RETIRED_LABEL[PRODUCTS_KEY],
1986
+ "pinned": "product", "identity": (_ROW_ID_COL, PRODUCT_JOIN_KEY),
1987
+ # the catalogue's HEAD: order lines point at it, it points at nothing.
1988
+ "links": ()},
1989
+
1990
+ {"key": AGENTS_KEY, "source": "res_partner", "label": "Odoo agents",
1991
+ "pinned": "agent", "identity": (_ROW_ID_COL, "odoo_id"),
1992
+ "links": ()},
1993
+
1994
+ {"key": ACCOUNTS_KEY, "source": "account_account", "label": "Odoo GL accounts",
1995
+ "pinned": "account_code", "identity": (_ROW_ID_COL, "odoo_id"),
1996
+ "links": ()},
1997
+
1998
+ {"key": BILLS_KEY, "source": "account_move", "label": "Odoo vendor bills",
1999
+ "pinned": "bill_no", "identity": (_ROW_ID_COL, "odoo_id"),
2000
+ # ⚠ `VENDORS_KEY`, NOT `CUSTOMERS_KEY`, even though both tables are `res.partner`. MEASURED and
2001
+ # recorded on `vendor_fields`: 393 vendors, of which 9 also appear in the customer population,
2002
+ # so pointing bills at the customers table would dangle 384 of 393 links as a mostly empty
2003
+ # column rather than as an error.
2004
+ "links": ((VENDOR_JOIN_KEY, VENDORS_KEY, _ROW_ID_COL, _M2O),)},
2005
+
2006
+ {"key": VENDORS_KEY, "source": "res_partner", "label": "Odoo vendors",
2007
+ "pinned": "vendor", "identity": (_ROW_ID_COL, "odoo_id"),
2008
+ "links": ()},
2009
+
2010
+ # ⭐⭐ THE BRIDGE GRAIN, AND ITS THREE EDGES ARE WHAT MAKE THE DONE-WHEN'S CHAIN EXPRESSIBLE:
2011
+ # customers <- orders <- order_lines -> products. Two of the three legs are REVERSE readings of
2012
+ # a child naming its parent, which is why the chain needs no fourth declaration and no path
2013
+ # search. ⚠ This grain stores no rows here (`READ_THROUGH_KEYS`); it is served from the mirror
2014
+ # by `routes_odoo_tables.GRID_SOURCES`, whose `cols` map binds exactly `order_id`, `partner_id`
2015
+ # and `product_id` to `sol.order_id`, `sol.order_partner_id` and `sol.product_id`.
2016
+ {"key": ORDER_LINES_KEY, "source": "sale_order_line", "label": "Odoo order lines",
2017
+ "pinned": "order_no", "identity": (_ROW_ID_COL, "odoo_id"),
2018
+ "links": ((JOIN_KEY, CUSTOMERS_KEY, _ROW_ID_COL, _M2O),
2019
+ ("order_id", ORDERS_KEY, _ROW_ID_COL, _M2O),
2020
+ (PRODUCT_JOIN_KEY, PRODUCTS_KEY, _ROW_ID_COL, _M2O))},
2021
+
2022
+ # ⚠ `move_id` REACHES MORE DOCUMENTS THAN `ut_odoo_invoices` HOLDS, and saying so is cheaper
2023
+ # than discovering it: the GL line grain is deliberately UNSCOPED (a ledger whose draft and
2024
+ # cancelled entries are invisible cannot be reconciled) while the invoices table is posted
2025
+ # CUSTOMER documents only. So this edge resolves for the customer-document lines and dangles for
2026
+ # the rest, which is the ordinary shape of a `many_to_one` into a scoped parent and is why the
2027
+ # cardinality is stated rather than assumed.
2028
+ {"key": GL_LINES_KEY, "source": "account_move_line", "label": "Odoo GL lines",
2029
+ "pinned": "entry", "identity": (_ROW_ID_COL, "odoo_id"),
2030
+ "links": ((JOIN_KEY, CUSTOMERS_KEY, _ROW_ID_COL, _M2O),
2031
+ ("move_id", INVOICES_KEY, _ROW_ID_COL, _M2O),
2032
+ (ACCOUNT_JOIN_KEY, ACCOUNTS_KEY, ACCOUNT_JOIN_KEY, _M2O))},
2033
+ )
2034
+
2035
+
2036
+ #: ⛔⛔ **THE REGISTRATION IS AN IMPORT-ORDER DEPENDENCY AND THIS IS THE SIGN THAT SAYS SO.**
2037
+ #: `platform/core/connector_spec.py` CANNOT import this file (`core` never imports up), so Odoo's
2038
+ #: spec reaches that registry by exactly one route: this module being imported. Therefore
2039
+ #: **`connector_spec.edges_for("odoo")` RETURNS `[]` IN ANY PROCESS THAT HAS NOT IMPORTED
2040
+ #: `odoo_relational`**, and an empty answer there is an import that never happened, not a connector
2041
+ #: with no edges. A reader who hits that emptiness should find this paragraph beside the call rather
2042
+ #: than have to derive it. Amazon and Meta have no such dependency: their rows are literals inside
2043
+ #: `connector_spec` itself.
2044
+ #: ⛔ AND IT IS RECORDED RATHER THAN ASSUMED. `core` is genuinely absent from `sys.path` on a bare
2045
+ #: `import odoo_relational` from `aios-web/api`, and raising there would take the whole route layer
2046
+ #: down over a declaration nothing on the request path reads. So the failure is CAPTURED in
2047
+ #: `SPEC_REGISTRATION` and `verify_odoo_relational`'s connector-spec section asserts it is
2048
+ #: `registered`. A caller that puts `platform/` on the path later may call
2049
+ #: `register_connector_spec()` again; it is idempotent, because `register()` REPLACES a connector.
2050
+ SPEC_REGISTRATION = {"connector": "odoo", "registered": False, "error": ""}
2051
+
2052
+
2053
+ def register_connector_spec():
2054
+ """Register `ODOO_SPEC` into `core.connector_spec` under the connector key `odoo`.
2055
+
2056
+ Returns True when it landed. Records the reason in `SPEC_REGISTRATION` when it did not, and
2057
+ never raises: see the banner above for why a hard failure here is the wrong trade.
2058
+ """
2059
+ try:
2060
+ import core.connector_spec as connector_spec
2061
+ except Exception as exc: # noqa: BLE001
2062
+ # ⚠ ASCII ONLY, like `_INVOICE_PRODUCT_LINK_BLOCKER`'s values: this string is short enough to be
2063
+ # quoted into a report, and standing rule 2 forbids an em dash or an en dash in copy that
2064
+ # can reach a screen.
2065
+ SPEC_REGISTRATION.update(
2066
+ registered=False,
2067
+ error="core.connector_spec is not importable from here: %s: %s"
2068
+ % (type(exc).__name__, str(exc)[:120]))
2069
+ return False
2070
+ connector_spec.register(
2071
+ SPEC_REGISTRATION["connector"],
2072
+ [connector_spec.ConnectorTableSpec(**dict(row, native=_native_model(row["key"])))
2073
+ for row in ODOO_SPEC])
2074
+ SPEC_REGISTRATION.update(registered=True, error="")
2075
+ return True
2076
+
2077
+
2078
+ register_connector_spec()
2079
+
2080
+
2081
  #: ⭐⭐ W49-T25 / C6 — THE COMPILED REGISTRY GRIDS, AND THIS MAP IS WHERE THE WHOLE TICKET LIVES.
2082
  #:
2083
  #: `TABLES` above declares the eight mirror grids owned by THIS file. The products and customers
 
2817
 
2818
 
2819
  def is_royal(tenant):
2820
+ """ENTITLEMENT by slug, kept verbatim for the five callers outside this module.
2821
+
2822
+ ⚠ IT IS NO LONGER THE SPAWN'S ADMISSION TEST — `available()` below is (W53-T39 / R3).
2823
+ It survives because `main.py`, `routes_odoo_tables`, `routes_grid` and `routes_tables` still
2824
+ gate their ROUTES on it, and because `is_royal("")` is deliberately True with
2825
+ `verify_automation`'s W35-T35 leg pinning that as a fixture contract. Deleting it here would
2826
+ be a silent regression in a gate this module does not run.
2827
+ """
2828
  return str(tenant or "").strip().lower() in RI_SLUGS
2829
 
2830
 
2831
+ def available(rt=None, tenant_key=None):
2832
+ """⭐⭐ R3 — DOES THIS TENANT HAVE ODOO CONFIGURED WITH LIVE CREDENTIALS? Never a slug list.
2833
+
2834
+ R3, verbatim: *"The connector table spawn gates on does this tenant have this connector
2835
+ configured with live credentials, never on a tenant-slug allow-list. Applies to every
2836
+ connector."* So this is the Odoo sibling of `amazon_relational.available` /
2837
+ `meta_relational.available`, and the three connectors now answer the same question the same
2838
+ way.
2839
+
2840
+ ⛔ THE RESOLUTION IS NOT RE-DERIVED HERE, AND THAT IS THE POINT. It is
2841
+ `TenantRuntime.odoo_flag_key()`, whose docstring already carries R3's three rules: first
2842
+ unlocked keychain `odoo` entry (ANY tenant), else tenant #0's compiled env source, else
2843
+ nothing. A second copy of those rules in this file is exactly the drift `odoo_flag_key` was
2844
+ written to end — a spawn admitted against one resolution and a pause flag written against
2845
+ another disagree while both report success.
2846
+
2847
+ ⚠ `odoo_flag_key()` rather than `odoo_source()`: the identity is cheap (a truthy key means a
2848
+ source WOULD serve) where the connector is a whole client build.
2849
+
2850
+ ⚠ READ THROUGH `rt`, NEVER THROUGH A MODULE-LEVEL `os.environ`, so a fixture runtime can
2851
+ answer. A runtime that cannot answer the question answers NO (fail closed): the harm this
2852
+ guards is a spawn, and a spawn makes wrong numbers durable.
2853
+
2854
+ ⛔ ADDING A SECOND ODOO TENANT NEEDS NO EDIT HERE. Anyone with a keychain `odoo` entry is
2855
+ admitted, whatever their slug.
2856
+ """
2857
+ try:
2858
+ if rt is not None:
2859
+ return bool(rt.odoo_flag_key())
2860
+ except Exception: # noqa: BLE001
2861
+ return False # unreadable = fail closed
2862
+ if not tenant_key:
2863
+ return False
2864
+ # A caller holding only a slug (a script, a probe) resolves its own runtime. Never reached
2865
+ # from `refresh`, which is always handed one.
2866
+ try:
2867
+ from harness import runtime as _runtime
2868
+ return bool(_runtime.get_runtime(str(tenant_key)).odoo_flag_key())
2869
+ except Exception: # noqa: BLE001
2870
+ return False
2871
+
2872
+
2873
  def refresh(rt, tenant, username="automation", cur=None, today=None):
2874
  """THE entry point — the store-resync path and the route both call this.
2875
 
 
2877
  still carries a `refreshed` stamp, so a stale worklist is at least LEGIBLE rather than
2878
  silently authoritative.
2879
  """
2880
+ # ⭐⭐ W53-T39 / R3 — THE ADMISSION IS A CREDENTIALS TEST, NOT A TENANT NAME.
2881
+ #
2882
+ # ⛔ THE OLD GATE'S REASON IS KEPT AND ONLY ITS MECHANISM IS REPLACED. It read
2883
+ # `is_royal(tenant)` against a hardcoded `RI_SLUGS`, and the reason it gave was REAL: a tenant
2884
+ # with no Odoo mirror behind these tables "would get empty locked databases" in their product.
2885
+ # That harm is unchanged, so the refusal is unchanged; what changes is WHAT MAKES IT TRUE. A
2886
+ # slug list is an allow-list that a second Odoo tenant can only join by a code edit, which is
2887
+ # precisely what R3 forbids. Credentials answer the same question and answer it for everybody.
2888
+ #
2889
+ # ⚠ THE FROZEN CLAUSE IS NOT A LOOPHOLE, IT IS R10 SURVIVING. `disconnect` REMOVES the
2890
+ # credential, so a disconnected workspace has none by construction — and the guard below
2891
+ # answers a freeze with a REPORT rather than an exception, deliberately, because the resync
2892
+ # loop calls this every cycle and an exception is not a status. Refusing here would hand that
2893
+ # loop a raise for the one state it is meant to report. So a frozen workspace is admitted this
2894
+ # far and stopped by its own guard, three lines down, with its own words.
2895
+ if not available(rt) and not (rt is not None and frozen(rt)):
2896
+ raise Refused("no Odoo credential is configured for this workspace, so there is nothing "
2897
+ "behind these tables and the spawn would create empty locked databases. "
2898
+ "Add an Odoo credential in the Connectors panel, then run the sync again.")
2899
+ # ⭐⭐ W31-T45 / D-169 — THE CREDENTIAL GATE ABOVE AND THE FILE GATE HERE ANSWER DIFFERENT
2900
+ # QUESTIONS, and this is the one place in the codebase where that is easy to miss. The gate
2901
+ # above asks "does this tenant have Odoo configured"; it says nothing about WHICH DuckDB file
2902
+ # this process has open. A worker pinned to another tenant's store (AIOS_DUCKDB_PATH, or a
2903
+ # `use_path` in a provisioning script) carries tenant #0's own Odoo credential, passes the
2904
+ # gate above, and then WRITES tenant #0's locked databases from another customer's rows — a
2905
+ # spawn, not a read, so the wrong numbers become durable. Entitlement is not residency, and
2906
+ # ⚠ W53-T39 did not weaken this by one line: the gate above changed its QUESTION, not its
2907
+ # blindness. Credentials say no more about residency than a slug did.
2908
  # ⚠ It runs when `cur` is LENT too, not only when we open one: the resync loop and the boot
2909
  # rebuild both hand a cursor in, and a lent cursor is exactly the case where nobody re-checks.
2910
  if rt is not None:
api/routes_connectors.py CHANGED
@@ -33,11 +33,17 @@ from deps import Session, err, require_session
33
  #: of it (a gate, a future module page) must not have to import FastAPI to ask what category a
34
  #: connector is in.
35
  from core import connector_directory
 
 
 
 
 
 
36
  #: ⛔ W32-T10 — IMPORTED, NEVER RE-DERIVED. "Does the environment serve THIS tenant's Odoo?" is
37
  #: one question, and this module used to answer it with an unguarded `os.environ.get("ODOO_URL")`
38
  #: while `routes_keychain` answered it correctly. Importing the correct one is the fix; writing a
39
  #: second correct one here would leave the same two-copies shape that produced the defect.
40
- from routes_keychain import TENANT_WIDE_TYPES, env_odoo_available
41
  #: ⛔⛔ W49-T16 / C3 — THE DEPENDENTS ROUTER IS MOUNTED FROM HERE, NOT FROM `main.py`. In a
42
  #: worktree-parallel wave `main.py` lives in exactly ONE lane's fence, so a router built in any
43
  #: other lane has nowhere to be mounted from (five consecutive waves lost an `include_router`
@@ -302,6 +308,124 @@ def _table_connection_key(table_key, definition):
302
  return ""
303
 
304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  def relationship_graphs(rows, user, rt, uname, is_admin=False):
306
  """Actual, permitted tables and same-connection declared links for directory rows.
307
 
@@ -377,6 +501,13 @@ def relationship_graphs(rows, user, rt, uname, is_admin=False):
377
  "visible": visible,
378
  }
379
 
 
 
 
 
 
 
 
380
  for connection_key, entries in tables_by_connection.items():
381
  if not entries:
382
  continue
@@ -410,6 +541,30 @@ def relationship_graphs(rows, user, rt, uname, is_admin=False):
410
  "to": {"table": target_table, "field": target_field},
411
  "label": str(field.get("label") or source_field).strip() or source_field,
412
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  graphs[connection_key] = {
414
  "connectionKey": connection_key,
415
  "status": "ready",
@@ -713,6 +868,28 @@ def directory(rt, uname, is_admin=False, incomplete=None):
713
  "the connector directory's category taxonomy could not be composed",
714
  "every connector above is still listed and still correct; the category filter and "
715
  "the wider catalogue are missing from this list only")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716
  return rows
717
 
718
 
@@ -731,6 +908,17 @@ def _oauth_row(slug, meta, row_st):
731
  else "available" if row_st.get("configured")
732
  else "unconfigured"),
733
  "connectedAs": row_st.get("email") or "",
 
 
 
 
 
 
 
 
 
 
 
734
  "startUrl": f"/api/v1/oauth/{slug}/start",
735
  "manage": "oauth",
736
  "needs": "" if row_st.get("configured") else "the owner registers the client",
@@ -878,6 +1066,19 @@ def connectors_directory(session: Session = Depends(require_session)):
878
  served = connector_directory.to_client_rows(rows)
879
  return {"connectors": served,
880
  "incomplete": incomplete,
 
 
 
 
 
 
 
 
 
 
 
 
 
881
  "categories": connector_directory.chip_counts(served),
882
  # ⛔⛔ `planned` COUNTS THE ROADMAP AGAIN, AND FOR ONE WAVE IT COUNTED 120. W49-T18
883
  # gave every Monid listing the `planned` state because that state renders faded, so
@@ -1208,7 +1409,201 @@ def _odoo_catalog_by_model(rt):
1208
  return out
1209
 
1210
 
1211
- def _detail_databases(rt, is_admin, connector_key):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1212
  """C4's `databases` half: what this connector materialises, and the fields behind each one.
1213
 
1214
  ⛔ ODOO IS THE ONLY INTROSPECTABLE CONNECTOR TODAY and every other card answers `[]`. That is
@@ -1231,11 +1626,24 @@ def _detail_databases(rt, is_admin, connector_key):
1231
  per-database control that is not per-database, and the reader would discover it by watching
1232
  the other database change. So the row carries the sibling it shares with, by KEY, and the tab
1233
  says so above the toggles.
 
 
 
 
 
 
 
 
 
 
 
 
1234
  """
1235
  if not connector_directory.is_introspectable(connector_key):
1236
  return []
 
1237
  if str(connector_key) == "amazon_sp":
1238
- return _amazon_databases(rt, is_admin)
1239
  try:
1240
  import odoo_relational
1241
  choices = odoo_relational.grid_choices(rt)
@@ -1261,17 +1669,24 @@ def _detail_databases(rt, is_admin, connector_key):
1261
  key = str(choice.get("key") or "")
1262
  model = str(models.get(key) or "")
1263
  fields, excluded = catalog.get(model, ([], []))
 
 
 
 
 
1264
  out.append({"key": key,
1265
- "label": str(choice.get("label") or key),
 
 
1266
  "enabled": bool(choice.get("enabled")),
1267
  "fields": [dict(field) for field in fields],
1268
  "excluded": [dict(item) for item in excluded],
1269
  "sharesFieldsWith": [other for other in shared.get(model, ())
1270
  if other != key]})
1271
- return out
1272
 
1273
 
1274
- def _amazon_databases(rt, is_admin):
1275
  """⭐⭐ W52 · R6 — THE SEVEN AMAZON DATABASES, DISCLOSED WITH WHERE EACH COLUMN CAME FROM.
1276
 
1277
  Fills the SAME `ConnectorDatabase` shape Odoo does, so the Databases tab needs no client
@@ -1331,8 +1746,17 @@ def _amazon_databases(rt, is_admin):
1331
  "reason": (amazon_schema.PROVENANCE_COPY["measured_at_sync"]
1332
  + f" The report is {rep}." if rep
1333
  else amazon_schema.PROVENANCE_COPY["measured_at_sync"])})
 
 
 
 
 
 
1334
  out.append({"key": key,
1335
- "label": str(LABELS_AMAZON.get(key) or key),
 
 
 
1336
  "enabled": True,
1337
  "fields": fields,
1338
  "excluded": excluded,
@@ -1502,7 +1926,9 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
1502
  graph = relationship_graphs(rows, user, rt, uname, bool(is_admin)).get(key) or _graph_refusal(
1503
  key, "No actual relationship graph was returned for this connection. A provider template "
1504
  "is not shown.")
1505
- databases = _detail_databases(rt, bool(is_admin), key)
 
 
1506
  return {"overview": _detail_overview(row, databases, graph),
1507
  "keychain": _detail_keychain(rt, uname, bool(is_admin), row),
1508
  "databases": databases,
@@ -1537,6 +1963,112 @@ def connectors_detail(connector_key: str, session: Session = Depends(require_ses
1537
  return detail
1538
 
1539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1540
  # ⛔⛔ W49-T16 — THE MOUNT. `dependents_router` DECLARES NO PREFIX OF ITS OWN, so including it in
1541
  # this router (which carries `prefix="/api/v1"`) yields exactly `/api/v1/dependents`. Declaring
1542
  # the prefix on both would serve `/api/v1/api/v1/dependents` — the mirror image of the wave-23
 
33
  #: of it (a gate, a future module page) must not have to import FastAPI to ask what category a
34
  #: connector is in.
35
  from core import connector_directory
36
+ #: ⭐ W53-T27 / R9 / C2 — the label RESOLVER, imported rather than re-written. "Shipped default,
37
+ #: per-tenant override, absent means inherit" is one idea and `core/schema_overlay.py` already
38
+ #: owns it for fields; `merge_database_labels` is that idea for a database's own name. This module
39
+ #: holds the tenant's store handle and does the reading; nothing about what a blank override MEANS
40
+ #: is decided here.
41
+ from core import schema_overlay
42
  #: ⛔ W32-T10 — IMPORTED, NEVER RE-DERIVED. "Does the environment serve THIS tenant's Odoo?" is
43
  #: one question, and this module used to answer it with an unguarded `os.environ.get("ODOO_URL")`
44
  #: while `routes_keychain` answered it correctly. Importing the correct one is the fix; writing a
45
  #: second correct one here would leave the same two-copies shape that produced the defect.
46
+ from routes_keychain import TENANT_WIDE_TYPES, allowed_scopes, env_odoo_available
47
  #: ⛔⛔ W49-T16 / C3 — THE DEPENDENTS ROUTER IS MOUNTED FROM HERE, NOT FROM `main.py`. In a
48
  #: worktree-parallel wave `main.py` lives in exactly ONE lane's fence, so a router built in any
49
  #: other lane has nowhere to be mounted from (five consecutive waves lost an `include_router`
 
308
  return ""
309
 
310
 
311
+ def _module_connection_key(subject):
312
+ """Which connected card a REGISTRY MODULE's `subject` belongs to, or `""`.
313
+
314
+ ⭐⭐ W53-T30 — DERIVED FROM `CONNECTED_PREFIXES`, NEVER A SECOND HAND-TYPED PAIR LIST. A
315
+ module's subject is namespaced by the system the records come from (`odoo:res.partner`,
316
+ `odoo:product.product` in `core/registry.py`), and the connector families this file already
317
+ knows carry that same namespace inside their table prefix (`odoo` inside `ut_odoo_`). So the
318
+ two are matched rather than mapped: a connector added to `CONNECTED_PREFIXES` in the change
319
+ that spawns its tables gets this for free, and a module whose namespace names no connected
320
+ family here simply does not appear on anybody's graph.
321
+
322
+ ⛔ THE SUBJECT, NOT THE `source` STRING. `source` is display copy ("Odoo") and a rename of it
323
+ is a copy edit; `subject` is the identity `core.registry` already refuses to let two rows
324
+ claim at once, which is what makes it safe to key a graph off.
325
+ """
326
+ namespace = str(subject or "").split(":", 1)[0].strip()
327
+ if not namespace:
328
+ return ""
329
+ for connection_key, prefix in CONNECTED_PREFIXES.items():
330
+ parts = str(prefix or "").strip("_").split("_")
331
+ if len(parts) > 1 and namespace == "_".join(parts[1:]):
332
+ return connection_key
333
+ return ""
334
+
335
+
336
+ def _module_graph_entries(rt, user, lent, connected):
337
+ """The REGISTRY MODULES this reader may see on a connected card's graph, per connection.
338
+
339
+ Returns `{connection key: {module key: {"dto", "visible"}}}` in exactly the shape the `ut_`
340
+ loop below builds, so the edge pass treats both kinds of node identically.
341
+
342
+ ⭐⭐ W53-T30 — THE WHOLE TICKET. `relationship_graphs` walks `user_tables.all_defs`, and
343
+ `customer_data` / `product_data` are COMPILED REGISTRY ROWS rather than stored definitions, so
344
+ that loop could never reach them however permissive it became. They were absent from the Odoo
345
+ diagram for that reason, not for a permission one. ⛔ The retired `ut_odoo_customers` /
346
+ `ut_odoo_products` keys are NOT the subject and must not be revived: W33-T44 / A2 retired
347
+ them, `odoo_relational.RETIRED_KEYS` pops them out of every tenant's document on rebuild, and
348
+ their subjects are claimed by these two registry rows, which is now the only claim on each.
349
+
350
+ ⛔⛔ THREE PREDICATES, THE SAME THREE `routes_tables._module_link_targets` USES ON THESE EXACT
351
+ TWO KEYS, and none of them is `is_admin`. A blanket administrator check here would silently
352
+ drop two nodes from a member's diagram for no stated reason, while every other node on the
353
+ same picture is walled per table:
354
+ 1. `perms.tenant_has_module` — is this database part of THIS tenant's world at all? Every
355
+ provisioned tenant but #0 carries a restricted `modules:` list, so without it another
356
+ company's admin is shown a database their workspace does not have.
357
+ 2. `perm_scope.nav_may_open` — ADMISSION, the predicate `deps.py`'s module gate itself asks.
358
+ `may_read` alone would draw a node whose door then 403s.
359
+ 3. `perm_scope.may_read` — the READ wall, the same one the `ut_` loop applies per table.
360
+
361
+ ⛔ `user_tables.may_open` IS NOT IN THAT LIST AND ITS ABSENCE IS DELIBERATE: it answers about
362
+ a STORED definition's creator and share grants, and a registry module has no such row, so it
363
+ refuses every reader including the tenant's owner.
364
+
365
+ �� THE FIELDS ARE `automation_engine._module_table`'s, WHICH IS THE ONE COMPOSER OF A MODULE'S
366
+ FIELD CONTRACT (`aios_grid` plus `odoo_relational.module_link_fields`). Restating either half
367
+ here is how this diagram would start disagreeing with the engine that resolves the very links
368
+ it draws. `want_rows=False`, so no pool is built and no store is written.
369
+
370
+ ⚠ AND THE FIELD LIST IS THE VIEWER'S: `visible_fields` strips the hidden closure, so a column
371
+ an administrator hid from this account is neither drawn on the card nor usable as an edge
372
+ endpoint. Fail-closed everywhere: a wall that cannot be answered drops the node.
373
+ """
374
+ try:
375
+ import automation_engine # noqa: PLC0415 - lazy, as elsewhere
376
+ import core.perm_scope as perm_scope
377
+ import core.perms as perms
378
+ import core.registry as registry
379
+ import core.user_tables as user_tables
380
+ except Exception: # noqa: BLE001
381
+ return {}
382
+ out = {}
383
+ memo = {}
384
+ for module_key in getattr(user_tables, "LINKABLE_MODULE_KEYS", ()):
385
+ key = str(module_key or "")
386
+ row = registry.BY_KEY.get(key) or {}
387
+ connection_key = _module_connection_key(row.get("subject"))
388
+ if not key or connection_key not in connected:
389
+ continue
390
+ try:
391
+ if not perms.tenant_has_module(rt, key):
392
+ continue
393
+ if not perm_scope.nav_may_open(user, key, st=lent):
394
+ continue
395
+ if not perm_scope.may_read(user, key, st=lent):
396
+ continue
397
+ # ⛔ `_module_table`, THE ENGINE'S OWN COMPOSER (`# noqa: SLF001` for the same reason
398
+ # `_database_name_overrides` calls `routes_nav._read_nav_meta`: one reader for one
399
+ # fact beats a correct-looking second copy).
400
+ table, _limit = automation_engine._module_table(rt, key, memo) # noqa: SLF001
401
+ declared = [dict(field) for field in ((table or {}).get("fields") or ())
402
+ if isinstance(field, dict)]
403
+ if not declared:
404
+ continue
405
+ visible = perm_scope.visible_fields(declared, user, key, st=lent)
406
+ except Exception: # noqa: BLE001
407
+ continue
408
+ fields = []
409
+ for field in visible:
410
+ field_key = str(field.get("key") or "").strip()
411
+ if field_key:
412
+ fields.append({"key": field_key,
413
+ "label": str(field.get("label") or field_key).strip() or field_key})
414
+ if not fields:
415
+ continue
416
+ # ⚠ THE REGISTRY'S OWN LABEL, READ RATHER THAN RETYPED. "Odoo customers" and "Odoo
417
+ # products" are `core/registry.py`'s `label` values (renamed there once already, W33-T42),
418
+ # and a literal copy here is a second authority that goes stale the day the row is
419
+ # renamed. There is no tenant override to merge in: `routes_nav` refuses a name for any
420
+ # key that does not start with `ut_`, so a registry module cannot be renamed at all.
421
+ label = str(row.get("label") or key).strip() or key
422
+ out.setdefault(connection_key, {})[key] = {
423
+ "dto": {"key": key, "label": label, "fields": fields},
424
+ "visible": visible,
425
+ }
426
+ return out
427
+
428
+
429
  def relationship_graphs(rows, user, rt, uname, is_admin=False):
430
  """Actual, permitted tables and same-connection declared links for directory rows.
431
 
 
501
  "visible": visible,
502
  }
503
 
504
+ # ⭐⭐ W53-T30 — AND THE REGISTRY MODULES THIS CONNECTION STANDS BEHIND. They are not stored
505
+ # definitions, so the loop above cannot reach them; they are permitted by their own three
506
+ # predicates and then join the SAME edge pass, which is what makes an already-declared link
507
+ # between a `ut_` table and a module resolvable at both ends for the first time.
508
+ for connection_key, entries in _module_graph_entries(rt, user, lent, connected).items():
509
+ tables_by_connection.setdefault(connection_key, {}).update(entries)
510
+
511
  for connection_key, entries in tables_by_connection.items():
512
  if not entries:
513
  continue
 
541
  "to": {"table": target_table, "field": target_field},
542
  "label": str(field.get("label") or source_field).strip() or source_field,
543
  })
544
+ # ⭐ W53-T30 / C2 — THE SPEC'S OWN DECLARED RELATIONS, held to the same two proofs as the
545
+ # field bags above: both endpoints must be nodes on THIS graph and both named columns must
546
+ # be visible to THIS reader. `{}` until lane D's `core.connector_spec` lands, and the
547
+ # `seen` signature is shared so a relation declared in both places is drawn once.
548
+ label_of = {(table_key, str(field.get("key") or "")): str(field.get("label") or "")
549
+ for table_key, entry in entries.items()
550
+ for field in entry["dto"]["fields"]}
551
+ for source_table, declared in _connector_spec_links(connection_key).items():
552
+ if source_table not in table_keys:
553
+ continue
554
+ for source_field, target_table, target_field in declared:
555
+ if (source_field not in visible_keys.get(source_table, set())
556
+ or target_table not in table_keys
557
+ or target_field not in visible_keys.get(target_table, set())):
558
+ continue
559
+ signature = (source_table, source_field, target_table, target_field)
560
+ if signature in seen:
561
+ continue
562
+ seen.add(signature)
563
+ relationships.append({
564
+ "from": {"table": source_table, "field": source_field},
565
+ "to": {"table": target_table, "field": target_field},
566
+ "label": label_of.get((source_table, source_field)) or source_field,
567
+ })
568
  graphs[connection_key] = {
569
  "connectionKey": connection_key,
570
  "status": "ready",
 
868
  "the connector directory's category taxonomy could not be composed",
869
  "every connector above is still listed and still correct; the category filter and "
870
  "the wider catalogue are missing from this list only")
871
+
872
+ # ⭐⭐ W53-T29 / OWNER RULING R6 — EVERY ROW DECLARES WHICH SCOPES IT MAY EVER CARRY.
873
+ #
874
+ # R6: *"Each catalogue source declares which scopes it allows (Odoo company-only; Gmail
875
+ # both)."* The Company / Mine toggle needs that per SOURCE, not per stored connection: a card
876
+ # may only ever appear under Company if `business` is in this list, and under Mine only if
877
+ # `personal` is — so Odoo cannot land under Mine however its `scope` was written, and a
878
+ # personal-only source cannot land under Company.
879
+ #
880
+ # ⛔ ONE PASS OVER THE COMPOSED SET, NOT A LINE IN EACH CONTRIBUTOR. Six functions above append
881
+ # rows and a seventh extends the list with a vendor catalogue; a declaration repeated in each
882
+ # is a declaration the eighth composer forgets, and the client would then treat the missing
883
+ # key as "unrestricted" with nothing going red. Stamped here, a new contributor gets the right
884
+ # answer for free.
885
+ # ⛔ AND THE ANSWER IS `routes_keychain.allowed_scopes`, IMPORTED. This module already imports
886
+ # `TENANT_WIDE_TYPES` rather than keeping a copy (see the import note at the top of the file);
887
+ # the eligibility rule built ON that tuple is fetched the same way for the same reason.
888
+ # ⚠ A ROW WITH NO KEYCHAIN TYPE (an OAuth slot, the Scraper, a catalogue listing) answers with
889
+ # both words, which is the honest default: nothing about it forbids either scope, and the one
890
+ # thing the toggle must never do is hide a connection the reader actually holds.
891
+ for row in rows:
892
+ row["allowedScopes"] = list(allowed_scopes(_entry_type_for(row.get("key"))))
893
  return rows
894
 
895
 
 
908
  else "available" if row_st.get("configured")
909
  else "unconfigured"),
910
  "connectedAs": row_st.get("email") or "",
911
+ # ⭐⭐ W53-T29 / R6 — A PER-USER SLOT IS PERSONAL, AND THE CARD NOW SAYS SO.
912
+ # `_oauth_slot_entries` below already stamps `"scope": "personal"` on these very
913
+ # credentials ("a per-user slot is personal by construction, in the vocabulary
914
+ # `routes_keychain`"), and the ROW carried no scope at all — so a connected Google card
915
+ # read as business-wide on the page while its own Keychain tab called it personal, and the
916
+ # Company / Mine split would have filed this reader's own sign-in under Company. One fact,
917
+ # said the same way in both places.
918
+ # ⚠ NO CARD MOVES TODAY: `oauth_connect.offered()` filters every provider out of the
919
+ # directory (D-45, the CASA verification nobody has bought), so this is the answer waiting
920
+ # for the day one of them is offered again rather than a change to what renders now.
921
+ "scope": "personal",
922
  "startUrl": f"/api/v1/oauth/{slug}/start",
923
  "manage": "oauth",
924
  "needs": "" if row_st.get("configured") else "the owner registers the client",
 
1066
  served = connector_directory.to_client_rows(rows)
1067
  return {"connectors": served,
1068
  "incomplete": incomplete,
1069
+ # ⭐⭐ W53-T29 / OWNER RULING R6 — MAY THIS READER SEE THE COMPANY SIDE AT ALL.
1070
+ #
1071
+ # R6: *"A non-admin does not see the Company side at all; the toggle itself is hidden
1072
+ # for them."* That is a PERMISSION, so it is the server's answer and not something the
1073
+ # page infers from whether some row happened to carry `manage: "keychain"`.
1074
+ # ⛔ THE WORD IS `routes_keychain`'s OWN. `GET /admin/keychain` has answered
1075
+ # `"canBusiness": bool(session.admin)` since W32-T11, for exactly this purpose ("the
1076
+ # vocabulary and the permission, so the client renders a picker it can honour"), and
1077
+ # the same fact under a second name would be two vocabularies for one boolean.
1078
+ # ⚠ CARRIED HERE RATHER THAN FETCHED FROM THAT ROUTE. The keychain door lists every
1079
+ # visible ENTRY, so a page that wanted one boolean would pull the workspace's whole
1080
+ # credential list on every visit; this route already holds the session that decides it.
1081
+ "canBusiness": bool(session.admin),
1082
  "categories": connector_directory.chip_counts(served),
1083
  # ⛔⛔ `planned` COUNTS THE ROADMAP AGAIN, AND FOR ONE WAVE IT COUNTED 120. W49-T18
1084
  # gave every Monid listing the `planned` state because that state renders faded, so
 
1409
  return out
1410
 
1411
 
1412
+ def _spec_field(item, name):
1413
+ """One attribute off a C2 table spec, whether lane D ships dataclasses or dicts."""
1414
+ if isinstance(item, dict):
1415
+ return item.get(name)
1416
+ return getattr(item, name, None)
1417
+
1418
+
1419
+ def _connector_spec_items(connector_key):
1420
+ """C2's raw table specs for one connector, as a sequence of items, or `()`.
1421
+
1422
+ ⭐⭐ W53-T30 — EXTRACTED FROM `_connector_spec_tables` (W53-T27) SO THERE IS STILL EXACTLY ONE
1423
+ IMPORT PATH TO LANE D'S MODULE. Two consumers now read the spec: the Databases tab wants
1424
+ `native` and `label`, the relationship graph wants `links`. A second `from core import
1425
+ connector_spec` with its own lookup order is how the two would start disagreeing about which
1426
+ attribute of D's module is the spec, and only one of them would be exercised by any given
1427
+ tenant. The lookup order, the failure posture and the reasons for both are unchanged and are
1428
+ documented on `_connector_spec_tables` below.
1429
+ """
1430
+ try:
1431
+ from core import connector_spec # noqa: PLC0415 - lane D's module (C2)
1432
+ except Exception: # noqa: BLE001
1433
+ return ()
1434
+ key = str(connector_key or "")
1435
+ found = None
1436
+ for name in ("tables_for", "for_connector", "tables", "spec", "spec_for"):
1437
+ fn = getattr(connector_spec, name, None)
1438
+ if not callable(fn):
1439
+ continue
1440
+ try:
1441
+ got = fn(key)
1442
+ except Exception: # noqa: BLE001
1443
+ continue
1444
+ if got:
1445
+ found = got
1446
+ break
1447
+ if not found:
1448
+ for name in ("SPECS", "TABLES", "CONNECTOR_TABLES"):
1449
+ blob = getattr(connector_spec, name, None)
1450
+ if isinstance(blob, dict):
1451
+ found = blob.get(key) or list(blob.values())
1452
+ elif isinstance(blob, (list, tuple)):
1453
+ found = list(blob)
1454
+ if found:
1455
+ break
1456
+ return list(found.values()) if isinstance(found, dict) else list(found or ())
1457
+
1458
+
1459
+ def _connector_spec_links(connector_key):
1460
+ """C2's DECLARED relations for one connector: `{table key: [(from, target, to, label)]}`.
1461
+
1462
+ ⭐⭐ W53-T30 / C2 — THE GRAPH'S SECOND SOURCE OF EDGES, and the contract's own words for it:
1463
+ each spec row carries `links`, a list of `(from_col, target_key, to_col, cardinality)`. Today
1464
+ every edge on this graph is read off a stored FIELD bag, which can only ever describe a
1465
+ relation somebody wrote a column for; a spec-declared relation between two tables that carry
1466
+ no link column has nowhere else to come from.
1467
+
1468
+ ⛔ AN EDGE FROM HERE IS HELD TO THE SAME TWO PROOFS AS ONE FROM A FIELD BAG, in the caller:
1469
+ both endpoints must be permitted NODES on this graph and both named columns must be VISIBLE
1470
+ to this reader. A spec is a declaration about the shipped schema, never a permission decision
1471
+ about a person, and an edge drawn on the strength of the declaration alone would name a column
1472
+ an administrator hid from the account looking at it.
1473
+
1474
+ ⛔ AND IT IS NOT AN OUTAGE WHEN LANE D'S MODULE IS ABSENT: `{}` means "no spec-declared
1475
+ relations", the field bags still answer, and the graph is exactly what it is today.
1476
+
1477
+ ⚠ `cardinality` IS NOT A LABEL and is not read as one. The wire's `label` is what the reader
1478
+ sees on the line, and "one to many" is a fact about the join rather than a name for it, so the
1479
+ caller labels a spec edge with the SOURCE COLUMN's own label instead.
1480
+ """
1481
+ out = {}
1482
+ for item in _connector_spec_items(connector_key):
1483
+ table_key = str(_spec_field(item, "key") or "")
1484
+ links = _spec_field(item, "links")
1485
+ if not table_key or not isinstance(links, (list, tuple)):
1486
+ continue
1487
+ edges = []
1488
+ for link in links:
1489
+ if not isinstance(link, (list, tuple)) or len(link) < 3:
1490
+ continue
1491
+ from_col = str(link[0] or "").strip()
1492
+ target_key = str(link[1] or "").strip()
1493
+ to_col = str(link[2] or "").strip()
1494
+ if from_col and target_key and to_col:
1495
+ edges.append((from_col, target_key, to_col))
1496
+ if edges:
1497
+ out[table_key] = edges
1498
+ return out
1499
+
1500
+
1501
+ def _connector_spec_tables(connector_key):
1502
+ """C2's spec for one connector as `{table key: {"native", "label"}}`, or `{}`.
1503
+
1504
+ ⛔⛔ `core.connector_spec` IS LANE D'S MODULE AND IT IS NOT IN THIS TREE YET. C2 splits the
1505
+ work: lane D declares the spec (`key`, `native`, `source`, `label`, `pinned`, `identity`,
1506
+ `links`) and this lane CONSUMES it through `GET /connectors/{key}/detail`. So the import is
1507
+ defensive and the fallback is the in-tree source each value already has — Odoo's native model
1508
+ from `odoo_relational.ODOO_TABLE_MODELS`, its default label from `grid_choices`, Amazon's
1509
+ report type from `connectors_amazon.REPORT_TYPES` and its label from `LABELS_AMAZON`. When D's
1510
+ module lands, the spec WINS with no edit here.
1511
+
1512
+ ⚠ D'S EXACT API IS NOT FROZEN, so the lookups tried are written down rather than guessed at by
1513
+ the next reader: the callables `tables_for(key)`, `for_connector(key)`, `tables(key)`,
1514
+ `spec(key)`, `spec_for(key)`, then the module attributes `SPECS`, `TABLES`,
1515
+ `CONNECTOR_TABLES` (a dict keyed by connector, a dict keyed by table, or a flat sequence).
1516
+ Whatever answers first is normalised by TABLE KEY, and only the keys this connector already
1517
+ declares are ever consulted — so a spec carrying other connectors' tables is harmless.
1518
+ ⚠ W53-T30 — THAT LOOKUP NOW LIVES IN `_connector_spec_items` ABOVE, unchanged, because the
1519
+ relationship graph reads the same spec for its `links`. One import path, two readings.
1520
+
1521
+ ⛔ A SPEC THAT CANNOT BE READ IS NOT AN OUTAGE. Every failure returns `{}` and the row keeps
1522
+ the in-tree value it has today: C2 is a better source for these two strings, never the only
1523
+ one, and a Databases tab that 500s because a sibling lane's module changed shape would be a
1524
+ disclosure screen taken down by a naming question.
1525
+ """
1526
+ out = {}
1527
+ for item in _connector_spec_items(connector_key):
1528
+ table_key = str(_spec_field(item, "key") or "")
1529
+ if not table_key:
1530
+ continue
1531
+ out[table_key] = {"native": str(_spec_field(item, "native") or ""),
1532
+ "label": str(_spec_field(item, "label") or "")}
1533
+ return out
1534
+
1535
+
1536
+ def _database_name_overrides(rt):
1537
+ """This tenant's per-database name overrides: `{table key: {"name": ...}}`, or `{}`.
1538
+
1539
+ ⛔⛔ `nav_meta` IS THE STORE, AND IT IS READ THROUGH THE NAVIGATION RAIL'S OWN READER. R9,
1540
+ verbatim: *"the rename database under the Navigation rail also works, it should then sync to
1541
+ the navigation in the connector too."* That rename has written `nav_meta` since wave 19
1542
+ (`routes_nav.save_nav_meta`), and `routes_tables.ut_label` already resolves a served name as
1543
+ nav_meta's name, then the definition's label, then the key. Calling `routes_nav._read_nav_meta`
1544
+ rather than re-deriving the document shape here is what makes the rail and this tab provably
1545
+ ONE fact instead of two answers to one question.
1546
+
1547
+ ⛔ AND IT IS WHY NOTHING HERE WRITES A TABLE DEFINITION'S LABEL. `user_tables.set_label` is
1548
+ rewritten by a connector re-sync (`odoo_relational.apply_plan` rebuilds definitions), so an
1549
+ override stored there would be silently clobbered on the next sync, which is precisely the
1550
+ R9 violation this ticket exists to prevent.
1551
+
1552
+ ⚠ ONE READ FOR THE WHOLE LIST, never one per row: `store.get` deep copies the tenant document
1553
+ on every call, and this list is eight rows on Odoo and seven on Amazon.
1554
+ ⚠ A store blip is "no overrides", never a failed page. The default name is still true.
1555
+ """
1556
+ try:
1557
+ import routes_nav # noqa: PLC0415 - lazy, avoids a cycle
1558
+ meta = routes_nav._read_nav_meta(rt) or {} # noqa: SLF001 - the ONE reader (R9)
1559
+ except Exception: # noqa: BLE001
1560
+ return {}
1561
+ return {str(k): v for k, v in meta.items() if isinstance(v, dict)}
1562
+
1563
+
1564
+ def _rename_rights(rt, uname, is_admin, keys):
1565
+ """`{table key: bool}` — which of these databases THIS reader may rename (R9's write wall).
1566
+
1567
+ ⛔ THE SAME PREDICATE `routes_nav.save_nav_meta` APPLIES TO A `ut_` KEY, not a second one:
1568
+ `user_tables.may_open`, i.e. the table's creator, a tenant admin, or a share grant. Two ideas
1569
+ of who may rename a database would show one person a control that the other door refuses.
1570
+
1571
+ ⛔ A DATABASE THIS CONNECTION HAS NOT CREATED YET IS NOT RENAMEABLE, and that is not a
1572
+ technicality: `nav_meta` is keyed by TABLE key, so a name stored for a table nobody can open
1573
+ would sit in the tenant's document naming nothing, and the rail would never show it.
1574
+
1575
+ ⚠ IT IS SERVED PER ROW because the answer IS per row, and because a control the server will
1576
+ refuse is R7's banned shape. One `lend_defs` read answers the whole list; that projection
1577
+ carries definitions without rows (~0.1% of the document's bytes).
1578
+ """
1579
+ try:
1580
+ import core.user_tables as user_tables # noqa: PLC0415 - lazy, as elsewhere
1581
+ definitions = user_tables.lend_defs(rt)
1582
+ return {key: bool(str(key).startswith("ut_")
1583
+ and user_tables.get(key, st=definitions)
1584
+ and user_tables.may_open(key, uname, bool(is_admin), st=definitions))
1585
+ for key in keys}
1586
+ except Exception: # noqa: BLE001
1587
+ # Fail closed. A wall that could not be read is not a wall that admitted you.
1588
+ return {key: False for key in keys}
1589
+
1590
+
1591
+ def _named_databases(rt, is_admin, uname, rows):
1592
+ """The LAST step of every databases list, Odoo's and Amazon's alike: the three names.
1593
+
1594
+ One place, deliberately. Each half of `_detail_databases` builds its own `native` and its own
1595
+ shipped default from its own source, and then BOTH come through here — so "what is this
1596
+ database called for this tenant" is answered once, by `schema_overlay.merge_database_labels`,
1597
+ and a third connector cannot arrive with a fourth opinion about a blank override.
1598
+ """
1599
+ named = schema_overlay.merge_database_labels(rows, _database_name_overrides(rt))
1600
+ rights = _rename_rights(rt, uname, is_admin, [str(row.get("key") or "") for row in named])
1601
+ for row in named:
1602
+ row["canRename"] = bool(rights.get(str(row.get("key") or "")))
1603
+ return named
1604
+
1605
+
1606
+ def _detail_databases(rt, is_admin, connector_key, uname=""):
1607
  """C4's `databases` half: what this connector materialises, and the fields behind each one.
1608
 
1609
  ⛔ ODOO IS THE ONLY INTROSPECTABLE CONNECTOR TODAY and every other card answers `[]`. That is
 
1626
  per-database control that is not per-database, and the reader would discover it by watching
1627
  the other database change. So the row carries the sibling it shares with, by KEY, and the tab
1628
  says so above the toggles.
1629
+
1630
+ ⭐⭐ W53-T27 / R9 / C2 — THREE NAMES PER ROW, AND THEY ARE THREE DIFFERENT FACTS. `native` is
1631
+ the VENDOR's own identifier (`res.partner`, or Amazon's report type) and is never editable by
1632
+ anybody; `defaultLabel` is OUR shipped default; `override` is this tenant's own rename, held
1633
+ in the `nav_meta` bucket the navigation rail already writes. `label` stays the EFFECTIVE name
1634
+ because every existing reader of it — this tab's heading, `_detail_overview`'s `creates` list
1635
+ — already means "what this database is called today", and serving the un-overridden default
1636
+ there would be the drift R9 exists to close.
1637
+
1638
+ ⛔ ALL THREE SURVIVE FOR A NON-ADMIN, like `key` and `enabled` above them and for the same
1639
+ reason: what a database is CALLED is a fact about the reader's own workspace. Only the WRITE
1640
+ is walled, per row, by `canRename`.
1641
  """
1642
  if not connector_directory.is_introspectable(connector_key):
1643
  return []
1644
+ spec = _connector_spec_tables(connector_key)
1645
  if str(connector_key) == "amazon_sp":
1646
+ return _named_databases(rt, is_admin, uname, _amazon_databases(rt, is_admin, spec))
1647
  try:
1648
  import odoo_relational
1649
  choices = odoo_relational.grid_choices(rt)
 
1669
  key = str(choice.get("key") or "")
1670
  model = str(models.get(key) or "")
1671
  fields, excluded = catalog.get(model, ([], []))
1672
+ # ⚠ THE SPEC WINS WHERE IT SPEAKS, AND THE MIRROR STILL GROUPS. `native` is a DISPLAY fact
1673
+ # (what Odoo calls this table); `shared` above is keyed by the model the ENABLEMENT flag
1674
+ # uses, so it stays derived from `ODOO_TABLE_MODELS` whatever C2 says a row is called.
1675
+ # Conflating the two would let a spec edit silently change which switches move together.
1676
+ declared = spec.get(key) or {}
1677
  out.append({"key": key,
1678
+ "label": str(declared.get("label") or choice.get("label") or key),
1679
+ "defaultLabel": str(declared.get("label") or choice.get("label") or key),
1680
+ "native": str(declared.get("native") or model),
1681
  "enabled": bool(choice.get("enabled")),
1682
  "fields": [dict(field) for field in fields],
1683
  "excluded": [dict(item) for item in excluded],
1684
  "sharesFieldsWith": [other for other in shared.get(model, ())
1685
  if other != key]})
1686
+ return _named_databases(rt, is_admin, uname, out)
1687
 
1688
 
1689
+ def _amazon_databases(rt, is_admin, spec=None):
1690
  """⭐⭐ W52 · R6 — THE SEVEN AMAZON DATABASES, DISCLOSED WITH WHERE EACH COLUMN CAME FROM.
1691
 
1692
  Fills the SAME `ConnectorDatabase` shape Odoo does, so the Databases tab needs no client
 
1746
  "reason": (amazon_schema.PROVENANCE_COPY["measured_at_sync"]
1747
  + f" The report is {rep}." if rep
1748
  else amazon_schema.PROVENANCE_COPY["measured_at_sync"])})
1749
+ # ⭐⭐ W53-T27 / C2 — THE SAME THREE FACTS AS THE ODOO ROWS, one source swapped. Amazon
1750
+ # has no per-table model name; the identifier AMAZON itself uses for what fills a table is
1751
+ # the REPORT TYPE (`rep`, already computed above for `sharesFieldsWith`). That is exactly
1752
+ # what `native` carries: the vendor's own name for the thing, never one we invented. It is
1753
+ # empty for a table whose report type is unknown, and the tab says so rather than guessing.
1754
+ declared = (spec or {}).get(key) or {}
1755
  out.append({"key": key,
1756
+ "label": str(declared.get("label") or LABELS_AMAZON.get(key) or key),
1757
+ "defaultLabel": str(declared.get("label")
1758
+ or LABELS_AMAZON.get(key) or key),
1759
+ "native": str(declared.get("native") or rep),
1760
  "enabled": True,
1761
  "fields": fields,
1762
  "excluded": excluded,
 
1926
  graph = relationship_graphs(rows, user, rt, uname, bool(is_admin)).get(key) or _graph_refusal(
1927
  key, "No actual relationship graph was returned for this connection. A provider template "
1928
  "is not shown.")
1929
+ # ⚠ `uname` REACHES THE DATABASES HALF NOW (W53-T27): `canRename` is `may_open`, which is a
1930
+ # question about a PERSON and a table, not about an administrator flag alone.
1931
+ databases = _detail_databases(rt, bool(is_admin), key, uname=str(uname or ""))
1932
  return {"overview": _detail_overview(row, databases, graph),
1933
  "keychain": _detail_keychain(rt, uname, bool(is_admin), row),
1934
  "databases": databases,
 
1963
  return detail
1964
 
1965
 
1966
+ # ⚠ FIVE SEGMENTS, so it can collide with nothing already declared here: the literal Odoo routes
1967
+ # are four (`/connectors/odoo/schema/{field_key}`) and `/detail` is three.
1968
+ @router.patch("/connectors/{connector_key}/databases/{database_key}/name")
1969
+ def connector_database_name(connector_key: str, database_key: str,
1970
+ body: dict = Body(default=None),
1971
+ session: Session = Depends(require_session)):
1972
+ """W53-T27 / R9 — set or CLEAR this tenant's own name for one of a connector's databases.
1973
+
1974
+ ⛔⛔ IT WRITES THE BUCKET THE NAVIGATION RAIL WRITES, `nav_meta`, IN THE SAME SHAPE AND WITH
1975
+ THE SAME PER-KEY MERGE. That is the whole ruling: *"the rename database under the Navigation
1976
+ rail also works, it should then sync to the navigation in the connector too."* A rename made
1977
+ here is the one the rail shows, and a rename made on the rail is the one this connector's
1978
+ Databases tab shows, because there is one document and one reader of it
1979
+ ([[one-question-two-normalizers]]). The key names, the length cap and the merge semantics are
1980
+ IMPORTED from `routes_nav` rather than copied, so the two doors cannot drift apart.
1981
+
1982
+ ⛔ SO WHY A SECOND DOOR AT ALL? `POST /nav/meta` cannot CLEAR a name: an empty or null `name`
1983
+ 400s there ("a database needs a name"), so "clearing the override falls back to our shipped
1984
+ default" has nowhere to happen today. This route is that door. `name: null` and `name: ""`
1985
+ both clear; any other string sets. The day `/nav/meta` grows the same clearing capability this
1986
+ becomes a thin alias of it and should be folded in.
1987
+
1988
+ ⛔ AND IT NEVER TOUCHES A TABLE DEFINITION. `user_tables.set_label` would be rewritten by the
1989
+ next connector re-sync (`odoo_relational.apply_plan` rebuilds definitions), so an override
1990
+ stored there would vanish on a sync nobody connected to a rename. R9 forbids exactly that, and
1991
+ the store choice is what makes it impossible rather than merely unlikely.
1992
+
1993
+ THE WALLS, in order, and each one names what it refused:
1994
+ · the database must be one THIS connector declares (404) - the door is scoped to the card
1995
+ the reader opened it from, so it cannot be used to rename an unrelated table;
1996
+ · the key must be a `ut_` key (400 `name_not_allowed`, the same refusal `/nav/meta` gives) -
1997
+ a built-in module's label is a compiled registry literal;
1998
+ · the table must EXIST in this workspace (409) - a name for a table nobody can open would
1999
+ sit in the document naming nothing;
2000
+ · `may_open` - the creator, an admin, or a share grant, the same predicate `/nav/meta` uses
2001
+ and the same one `canRename` reports, so the control and the door always agree.
2002
+ """
2003
+ import routes_nav # noqa: PLC0415 - the ONE nav owner
2004
+ rt = session.runtime
2005
+ key = str(database_key or "").strip()
2006
+ rows = _detail_databases(rt, bool(session.admin), str(connector_key or ""),
2007
+ uname=session.uname)
2008
+ row = next((candidate for candidate in rows
2009
+ if str(candidate.get("key") or "") == key), None)
2010
+ if row is None:
2011
+ raise err(404, "unknown_database",
2012
+ "this connection does not create a database with that name")
2013
+ if not key.startswith("ut_"):
2014
+ raise err(400, "name_not_allowed",
2015
+ "only a database this connection created can be renamed. This one's name comes "
2016
+ "from the module registry")
2017
+ import core.user_tables as user_tables # noqa: PLC0415 - lazy, as elsewhere
2018
+ definitions = user_tables.lend_defs(rt)
2019
+ if not user_tables.get(key, st=definitions):
2020
+ raise err(409, "database_not_created",
2021
+ "this connection has not created that database in this workspace yet, so there "
2022
+ "is nothing to rename")
2023
+ if not user_tables.may_open(key, session.uname, session.admin, st=definitions):
2024
+ raise err(403, "forbidden", "that database belongs to another user")
2025
+
2026
+ body = body if isinstance(body, dict) else {}
2027
+ if "name" not in body:
2028
+ raise err(400, "bad_request",
2029
+ "no name was sent. Send a name to set one, or null to go back to the default")
2030
+ # The same normalisation `/nav/meta` applies: whitespace collapsed, capped at its own limit.
2031
+ # A blank result CLEARS, which is the half that route refuses and this one exists for.
2032
+ name = " ".join(str(body.get("name") or "").split())[:routes_nav._MAX_NAV_NAME]
2033
+
2034
+ if not rt.available():
2035
+ raise err(503, "store_unavailable",
2036
+ "the tenant store is unavailable. Nothing was saved.")
2037
+
2038
+ def _up(data):
2039
+ # `routes_nav.save_nav_meta._up`, clause for clause: an entry left empty is REMOVED rather
2040
+ # than stored as `{}`, and an icon set from the rail survives a rename made here.
2041
+ data = data if isinstance(data, dict) else {}
2042
+ entry = dict(data.get(key) or {}) if isinstance(data.get(key), dict) else {}
2043
+ if name:
2044
+ entry["name"] = name
2045
+ else:
2046
+ entry.pop("name", None)
2047
+ if entry:
2048
+ data[key] = entry
2049
+ else:
2050
+ data.pop(key, None)
2051
+ return data
2052
+
2053
+ try:
2054
+ rt.update(routes_nav._NAV_META_KEY, _up) # noqa: SLF001 - the nav's own key
2055
+ except Exception: # noqa: BLE001
2056
+ raise err(503, "store_unavailable",
2057
+ "the change was not saved: the store refused the write.")
2058
+
2059
+ # Read BACK through the same resolver the tab reads, so the answer cannot be the echo of a
2060
+ # write that landed somewhere else.
2061
+ default_label = str(row.get("defaultLabel") or "")
2062
+ override = schema_overlay.override_name(_database_name_overrides(rt).get(key))
2063
+ return {"key": key,
2064
+ # ⛔ SERVED, NEVER ACCEPTED. `native` is the vendor's identifier; this door reads
2065
+ # `name` and nothing else off the body (C2: `native` is never editable).
2066
+ "native": str(row.get("native") or ""),
2067
+ "defaultLabel": default_label,
2068
+ "override": override,
2069
+ "label": schema_overlay.database_label(default_label, override)}
2070
+
2071
+
2072
  # ⛔⛔ W49-T16 — THE MOUNT. `dependents_router` DECLARES NO PREFIX OF ITS OWN, so including it in
2073
  # this router (which carries `prefix="/api/v1"`) yields exactly `/api/v1/dependents`. Declaring
2074
  # the prefix on both would serve `/api/v1/api/v1/dependents` — the mirror image of the wave-23
api/routes_grid.py CHANGED
@@ -2721,21 +2721,225 @@ def related_entries(session: Session, table: str):
2721
  return [e for e in entries if _may_open(session, e["target"])]
2722
 
2723
 
2724
- @router.get("/grid/{table}/related")
2725
- def grid_related(table: str, session: Session = Depends(require_session)):
2726
- """C6 — every database related to `table`, one entry per edge, under the caller's scope.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2727
 
2728
- `{ok, table, related: [{key, label, via, target, served, where?}]}`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2729
 
2730
  ⭐ ONE ENTRY PER EDGE, NOT PER TARGET. R2: *"two links between the same pair give two tabs
2731
  subtitled by the field"* — so `key` is the EDGE's identity and `via.key` repeats it, because
2732
- `via` is the whole of what the pinned read is handed back and it has to identify an edge on its
2733
- own. Two bridges off `customer_data` really do share `{direction: "bridge", on: "partner_id"}`.
2734
 
2735
- ⭐ `served` IS PART OF THE ANSWER, AND R6'S SECOND SENTENCE IS WHY. A declared edge whose
2736
- target is served from its stored copy cannot be pinned yet (that door takes no predicate), and
2737
- the caller is told which ones those are rather than discovering it as an empty tab. Open
2738
- invoices is the one such edge today.
2739
 
2740
  ⛔ THE CALLER'S OWN ACCESS IS CHECKED FIRST. Listing what `table` is related to tells you what
2741
  `table` is, so the listing is behind the same gate the grid is.
@@ -2747,4 +2951,44 @@ def grid_related(table: str, session: Session = Depends(require_session)):
2747
  raise err(403, "not_permitted",
2748
  f"your account may not open '{table}', so it cannot be told what that database "
2749
  f"is related to. Ask an administrator for access to it")
2750
- return {"ok": True, "table": table, "related": related_entries(session, table)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2721
  return [e for e in entries if _may_open(session, e["target"])]
2722
 
2723
 
2724
+ def _ensure_odoo_spec():
2725
+ """Make sure Odoo's connector spec is registered in `core.connector_spec` before it is READ.
2726
+
2727
+ ⛔⛔ AN EMPTY `edges_for("odoo")` IS AN IMPORT THAT NEVER HAPPENED, NOT A CONNECTOR WITH NO
2728
+ EDGES, AND THIS FUNCTION EXISTS BECAUSE THAT FAILURE IS SILENT. `platform/core/connector_spec.py`
2729
+ cannot import `odoo_relational` (`core` never imports up), so Odoo's rows reach that registry by
2730
+ exactly one route: `odoo_relational` being imported IN A PROCESS WHERE `core` IS ON THE PATH.
2731
+ MEASURED: a bare `import odoo_relational` from `aios-web/api` leaves `SPEC_REGISTRATION` at
2732
+ `{'registered': False, 'error': "core.connector_spec is not importable from here: ..."}`, and
2733
+ `edges_for("odoo")` then answers `[]` with nothing red anywhere. The relation answer would come
2734
+ back short by every spec edge and look entirely correct doing it.
2735
+
2736
+ ⛔ IT IS DONE HERE, NOT IN `core/relations.py`, for the layering reason above: `core` never
2737
+ imports up, so the module that READS the edges cannot be the module that registers them. This
2738
+ file already imports `odoo_relational` inside `_source_fields`, so the dependency is not new.
2739
+ ⚠ IDEMPOTENT: `connector_spec.register` REPLACES a connector, and `register_connector_spec`
2740
+ never raises. So calling it per request is cheap and the failure is recorded rather than thrown.
2741
+ """
2742
+ try:
2743
+ import odoo_relational
2744
+ return bool(odoo_relational.register_connector_spec())
2745
+ except Exception: # noqa: BLE001
2746
+ return False
2747
+
2748
+
2749
+ def _unwalled_fields(defs: dict, key: str):
2750
+ """`key`'s field list WITHOUT this session's FIELD wall, for the W53-T18 diff pass only.
2751
+
2752
+ ⛔⛔ IT IS NEVER SERVED AND NEVER WIDENS A TAB. Its ONE consumer is the unfiltered half of
2753
+ `relations.diagnose_path` / `wall_refusals`, which chooses a refusal CODE and names a table or
2754
+ a hop. Nothing built from it reaches `related`, and `verify_odoo_relational` proves that by
2755
+ comparing the served list with and without the whole diff rather than by trusting this note.
2756
+
2757
+ ⚠ `all_defs` IS ALREADY UNSCOPED (it is the tenant's definitions, projected free of `rows`),
2758
+ so the raw `fields` on a definition IS the pre-wall list; `_source_fields`' narrowing happens
2759
+ later, in `perm_scope.scoped_fields`. A registry module has no `all_defs` row at all, which is
2760
+ why the pre-set link fields are appended here exactly as `_source_fields` appends them.
2761
+ """
2762
+ # ⚠ `isinstance` RATHER THAN `or {}`, the guard `relations.reverse_links` already carries on the
2763
+ # same input: a definition that is not a dict makes `.get` an AttributeError, and this function
2764
+ # runs inside the LISTING, so the crash would land on a door that is otherwise answering fine.
2765
+ defn = defs.get(key)
2766
+ fields = list((defn.get("fields") or ()) if isinstance(defn, dict) else ())
2767
+ if key in _PRESET_LINK_MODULES:
2768
+ try:
2769
+ import odoo_relational
2770
+ fields = fields + list(odoo_relational.module_link_fields(key) or ())
2771
+ except Exception: # noqa: BLE001
2772
+ pass
2773
+ return fields
2774
+
2775
+
2776
+ def _relation_context(session: Session, table: str):
2777
+ """`defs` plus the three callbacks `relations` needs, memoised for the life of ONE request.
2778
+
2779
+ ⚠ BOTH WALLS ARE MEMOISED. `_may_open` runs `session.require` plus `perm_scope.scoped_fields`
2780
+ and `_source_fields` runs the second of those again; a depth-2 enumeration asks about the same
2781
+ dozen tables repeatedly, so without the memo one listing pays for the same permission answer
2782
+ many times over. W53-T18 added a SECOND enumeration over the same tables, which is exactly why
2783
+ the memo now lives out here instead of inside the builder: the diff pass costs no extra
2784
+ permission call at all.
2785
+
2786
+ ⛔⛔ `open_fields_for` IS A **UNION**, NOT A REPLACEMENT, AND THAT IS LOAD-BEARING. The diff in
2787
+ `relations.diagnose_path` calls a path that is present unfiltered and absent filtered a WALL
2788
+ removal; if the unfiltered field list could ever be NARROWER than the walled one, a path the
2789
+ wall really did remove would be absent from both and get reported as an edge that never
2790
+ existed. Taking the union makes the unfiltered enumeration a superset by construction, so the
2791
+ diff is monotone and the only thing it can be wrong about is saying "unknown" too rarely.
2792
+ """
2793
+ import core.user_tables as user_tables
2794
+
2795
+ try:
2796
+ defs = dict(user_tables.all_defs(st=session.runtime) or {})
2797
+ except Exception: # noqa: BLE001
2798
+ defs = {}
2799
+
2800
+ open_memo, field_memo, wide_memo = {}, {}, {}
2801
+
2802
+ def may_open(key):
2803
+ if key not in open_memo:
2804
+ open_memo[key] = _may_open(session, key)
2805
+ return open_memo[key]
2806
 
2807
+ def fields_for(key):
2808
+ if key not in field_memo:
2809
+ field_memo[key] = _source_fields(session, key)
2810
+ return field_memo[key]
2811
+
2812
+ def open_fields_for(key):
2813
+ if key not in wide_memo:
2814
+ walled = list(fields_for(key) or ())
2815
+ seen = {str(f.get("key")) for f in walled if isinstance(f, dict)}
2816
+ extra = [f for f in _unwalled_fields(defs, key)
2817
+ if isinstance(f, dict) and str(f.get("key")) not in seen]
2818
+ wide_memo[key] = walled + extra
2819
+ return wide_memo[key]
2820
+
2821
+ return {"defs": defs, "may_open": may_open, "fields_for": fields_for,
2822
+ "open_fields_for": open_fields_for}
2823
+
2824
+
2825
+ def related_path_entries(session: Session, table: str, depth: int, ctx: dict = None):
2826
+ """C3's `/related` list for `table` at `depth`, narrowed to what this session may open.
2827
+
2828
+ ⭐ THE WALL IS APPLIED TO EVERY TABLE ON A PATH, INTERMEDIATE INCLUDED, and it is applied by
2829
+ `relations.related_paths` calling back into `_may_open` rather than by filtering the finished
2830
+ list: a two-hop path through a table this reader cannot open must never be enumerated, because
2831
+ the enumeration itself tells them what that table is related to.
2832
+
2833
+ ⛔ THIS IS THE **SERVED** ANSWER AND W53-T18 DID NOT TOUCH IT. The diff pass that names the
2834
+ refusals is `related_refusals` below; it reads this list and never feeds it.
2835
+ """
2836
+ import core.relations as relations
2837
+
2838
+ _ensure_odoo_spec()
2839
+ table = str(table or "")
2840
+ ctx = ctx or _relation_context(session, table)
2841
+ return relations.related_paths(table, fields=ctx["fields_for"](table), defs=ctx["defs"],
2842
+ depth=depth, may_open=ctx["may_open"],
2843
+ fields_for=ctx["fields_for"])
2844
+
2845
+
2846
+ def related_refusals(session: Session, table: str, depth: int, entries: list, ctx: dict = None):
2847
+ """W53-T18 / R13 / C3 — WHAT THE WALL REMOVED from `entries`, by name. The SIBLING of `related`.
2848
+
2849
+ `[{code, message, path, table?, hop?}]`, where `code` is one of `relations.REFUSAL_CODES`.
2850
+
2851
+ ⛔⛔ *"AN EMPTY LIST IS NEVER AN ACCEPTABLE ANSWER TO A PERMISSION-FILTERED TRAVERSAL."* An
2852
+ HTTP error covers the request that PINNED one path; the LISTING answers 200 with a shorter
2853
+ array, and a shorter array is exactly the silent empty PostgREST hands out under RLS and Odoo
2854
+ hands out for a forbidden One2many. So a path the wall removed is REPORTED here rather than
2855
+ omitted, and a table with nothing on the other side says `no_related_rows` out loud.
2856
+ ⛔ AND A 403 FOR THE WHOLE STRIP WOULD BE EQUALLY WRONG: the other tabs are legitimately
2857
+ visible, and refusing them all in order to explain one is a wall with a bug in it.
2858
+
2859
+ ⛔ IT CANNOT WIDEN `related`. The unfiltered enumeration lives entirely inside
2860
+ `relations.wall_refusals`, which is handed the SERVED list and only ever reports paths that are
2861
+ NOT in it. Nothing here is added to, or removed from, what the caller is served.
2862
+ """
2863
+ import core.relations as relations
2864
+
2865
+ table = str(table or "")
2866
+ ctx = ctx or _relation_context(session, table)
2867
+ return relations.wall_refusals(
2868
+ table, fields=ctx["fields_for"](table), defs=ctx["defs"], depth=depth,
2869
+ may_open=ctx["may_open"], fields_for=ctx["fields_for"], entries=entries,
2870
+ open_fields=ctx["open_fields_for"](table), open_fields_for=ctx["open_fields_for"])
2871
+
2872
+
2873
+ #: ⭐ THE HTTP STATUS EACH R13 CODE EARNS ON A **PIN**. The two permission answers are 403, the
2874
+ #: same status the top-of-route `_may_open` gate on `table` itself already uses; a path that never
2875
+ #: existed stays the 400 this route already answered with, unchanged; and "every hop was open and
2876
+ #: there is nothing there" is a 404, because it is neither a bad request nor a refusal.
2877
+ #: ⚠ `no_related_rows` cannot be reached from THIS route's pin branch (a path that resolves is
2878
+ #: served, so the diff never reports it) and is mapped anyway, because `diagnose_path` is the one
2879
+ #: diagnosis and the row door will raise the same bag from another ticket's fence.
2880
+ _REFUSAL_STATUS = {"forbidden_table": 403, "hop_filtered": 403,
2881
+ "no_related_rows": 404, "unknown_via": 400}
2882
+
2883
+
2884
+ def _refusal_error(diag: dict):
2885
+ """`err(...)` for a `diagnose_path` bag, carrying its named table, hop and candidates.
2886
+
2887
+ ⛔ THE X2 SHAPE IS UNCHANGED: `{"error": {"code", "message"}}`, with the extra keys added as
2888
+ SIBLINGS inside `error`. C3 asks for *"the ENUMERATED candidates with their join columns and
2889
+ the exact retry strings, not prose"*, and a client cannot draw a retry button out of an English
2890
+ clause, so the structure rides beside the sentence rather than inside it.
2891
+ """
2892
+ exc = err(_REFUSAL_STATUS.get(str(diag.get("code")), 400), str(diag.get("code")),
2893
+ str(diag.get("message") or ""))
2894
+ for key in ("table", "hop", "path", "candidates"):
2895
+ if diag.get(key) not in (None, ""):
2896
+ exc.detail["error"][key] = diag[key]
2897
+ return exc
2898
+
2899
+
2900
+ @router.get("/grid/{table}/related")
2901
+ def grid_related(table: str,
2902
+ depth: int = Query(default=2),
2903
+ via: list[str] = Query(default=None),
2904
+ session: Session = Depends(require_session)):
2905
+ """C6 + C3 — every database reachable from `table` in at most `depth` NAMED hops.
2906
+
2907
+ `{ok, table, depth, related: [{key, label, via, target, served, where?, cardinality, path,
2908
+ hops}], refusals: [{code, message, path, table?, hop?}]}`.
2909
+
2910
+ ⭐⭐ R12: *"the server enumerates what is reachable within two hops and offers it; the client
2911
+ pins one by naming each edge. Never a path search."* So `depth` is 1 or 2 and nothing else, the
2912
+ answer is an ENUMERATION rather than a route this server chose, and `path` is what the client
2913
+ sends back to pin one. ⛔ `depth`'s default of 2 mirrors `relations.MAX_DEPTH`;
2914
+ `verify_odoo_relational` asserts the two agree rather than letting two literals drift.
2915
+
2916
+ ⛔ A BAD `depth` IS A NAMED 400, NEVER A 500 AND NEVER A SILENT CLAMP. Clamping 3 to 2 would
2917
+ answer a different question than the one asked and call it success, which is the whole failure
2918
+ mode R12's refusal exists to prevent.
2919
+
2920
+ ⭐ `via` IS AN ARRAY OF EDGE KEYS, one per hop, resolved by `relations.pick_path` against THIS
2921
+ enumeration, so an edge this account cannot be offered is an edge it cannot pin. A SINGLE
2922
+ `?via=<key>` arrives as a one-element list and is therefore a one-hop path, which is C3's
2923
+ back-compat leg with no second matching rule behind it.
2924
+
2925
+ ⭐⭐ W53-T18 / R13 — `refusals` IS A SIBLING OF `related`, AND `related` DID NOT CHANGE. R13:
2926
+ *"a permission-filtered traversal must be distinguishable on the wire from an empty one"*. A
2927
+ shorter `related` array is exactly the silent empty PostgREST hands out under RLS, so every
2928
+ path the wall removed is NAMED here instead: `forbidden_table` naming the closed table (which
2929
+ may be the INTERMEDIATE of a two-hop path), `hop_filtered` naming the hop the field wall took,
2930
+ and `no_related_rows` said out loud when the answer is genuinely nothing. ⛔ THE LIST IS NOT
2931
+ THE ANSWER TO A PIN: a `via` that cannot resolve fails the REQUEST with the same codes through
2932
+ `_refusal_error`, and a pin that resolves reports `refusals: []`.
2933
 
2934
  ⭐ ONE ENTRY PER EDGE, NOT PER TARGET. R2: *"two links between the same pair give two tabs
2935
  subtitled by the field"* — so `key` is the EDGE's identity and `via.key` repeats it, because
2936
+ `via` is the whole of what a resolver is handed back and it has to identify an edge on its own.
2937
+ Two bridges off `customer_data` really do share `{direction: "bridge", on: "partner_id"}`.
2938
 
2939
+ ⭐ `served` IS PART OF THE ANSWER, AND R6'S SECOND SENTENCE IS WHY. A declared edge whose target
2940
+ is served from its stored copy cannot be pinned yet (that door takes no predicate), and the
2941
+ caller is told which ones those are rather than discovering it as an empty tab. Open invoices is
2942
+ the one such edge today, and a two-hop entry is `served` only when BOTH its hops are.
2943
 
2944
  ⛔ THE CALLER'S OWN ACCESS IS CHECKED FIRST. Listing what `table` is related to tells you what
2945
  `table` is, so the listing is behind the same gate the grid is.
 
2951
  raise err(403, "not_permitted",
2952
  f"your account may not open '{table}', so it cannot be told what that database "
2953
  f"is related to. Ask an administrator for access to it")
2954
+ import core.relations as relations
2955
+
2956
+ try:
2957
+ depth = int(depth)
2958
+ except (TypeError, ValueError):
2959
+ depth = -1
2960
+ if depth not in (1, relations.MAX_DEPTH):
2961
+ raise err(400, "bad_depth",
2962
+ f"a relation listing is offered at depth 1 (edges of '{table}' itself) or depth "
2963
+ f"{relations.MAX_DEPTH} (those plus everything one further named hop away), and "
2964
+ f"this request asked for {depth}. Ask for 1 or {relations.MAX_DEPTH}")
2965
+
2966
+ ctx = _relation_context(session, table)
2967
+ entries = related_path_entries(session, table, depth, ctx)
2968
+ if via:
2969
+ wanted = [str(v) for v in via if str(v or "").strip()]
2970
+ if len(wanted) > relations.MAX_DEPTH:
2971
+ raise err(400, "over_depth", relations.over_depth_refusal(table, wanted))
2972
+ hit = relations.pick_path(entries, wanted)
2973
+ if hit is None:
2974
+ # ⭐⭐ W53-T18 / R13 / C3 — THE ONE GENERIC `unknown_via` IS NOW ONE OF FOUR NAMED
2975
+ # ANSWERS, CHOSEN BY A DIFF. `relations.diagnose_path` enumerates the reachable set
2976
+ # TWICE, once with this session's wall and once without it, and compares: a path the
2977
+ # wall removed answers `forbidden_table` NAMING the closed table or `hop_filtered`
2978
+ # NAMING the hop, while a path absent from both really is an edge that does not exist
2979
+ # and keeps the `unknown_via` code this route already used, now carrying the
2980
+ # enumerated candidates with their join columns and the exact retry strings.
2981
+ # ⛔ THE UNFILTERED PASS CHOOSES THE CODE AND NAMES THE TABLE. IT SERVES NOTHING:
2982
+ # `entries` above is the walled enumeration and is what a resolvable `via` returns.
2983
+ raise _refusal_error(relations.diagnose_path(
2984
+ table, wanted, fields=ctx["fields_for"](table), defs=ctx["defs"],
2985
+ may_open=ctx["may_open"], fields_for=ctx["fields_for"], depth=depth,
2986
+ entries=entries, open_fields=ctx["open_fields_for"](table),
2987
+ open_fields_for=ctx["open_fields_for"]))
2988
+ # ⚠ A RESOLVED PIN REPORTS NO REFUSALS. The caller named one path and got it; the other
2989
+ # tabs the wall removed are the LISTING's answer, not this one, and repeating them here
2990
+ # would attach an unasked-for permission report to every successful read.
2991
+ return {"ok": True, "table": table, "depth": depth, "related": [hit], "refusals": []}
2992
+ return {"ok": True, "table": table, "depth": depth, "related": entries,
2993
+ "refusals": related_refusals(session, table, depth, entries, ctx)}
2994
+
api/routes_keychain.py CHANGED
@@ -121,6 +121,28 @@ SCOPE_KEY = "keychain_scopes"
121
  TENANT_WIDE_TYPES = ("odoo", "meta_ads", "amazon_sp")
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def clean_scope(raw, default=DEFAULT_SCOPE):
125
  """A scope word from the wire, or None when the caller said something we do not speak.
126
 
 
121
  TENANT_WIDE_TYPES = ("odoo", "meta_ads", "amazon_sp")
122
 
123
 
124
+ #: ⭐⭐ W53-T29 / OWNER RULING R6 — WHICH SCOPES ONE SOURCE MAY EVER CARRY, SAID AS DATA.
125
+ #:
126
+ #: R6: *"Each catalogue source declares which scopes it allows (Odoo company-only; Gmail both)."*
127
+ #: ⛔ IT IS DERIVED FROM `TENANT_WIDE_TYPES`, NEVER A SECOND LIST BESIDE IT. That tuple is already
128
+ #: the authored answer to "may this source be personal" — `add_key` and `update_key` REFUSE on it
129
+ #: three lines apart — so a hand-written `{"odoo": ["business"], ...}` map here would be the
130
+ #: [[one-question-two-normalizers]] shape the day one of the two changes and the other does not.
131
+ #: The function exists so the CLIENT can be told the fact rather than re-deriving it from a
132
+ #: `tenantWideTypes` list it would have to reason about itself.
133
+ def allowed_scopes(entry_type):
134
+ """The scopes `entry_type` may legally be stored under, as a subset of `SCOPES`.
135
+
136
+ ⚠ ELIGIBILITY, NOT PERMISSION. This is the SOURCE's own rule and it does not know who is
137
+ asking: whether THIS reader may create a business-wide connection is `session.admin`, decided
138
+ at the door in `add_key`. A card needs both answers and they are different questions, which is
139
+ why `routes_connectors._detail_connect` narrows this one by the admin flag rather than
140
+ replacing it.
141
+ """
142
+ word = str(entry_type or "").strip().lower()
143
+ return ("business",) if word in TENANT_WIDE_TYPES else SCOPES
144
+
145
+
146
  def clean_scope(raw, default=DEFAULT_SCOPE):
147
  """A scope word from the wire, or None when the caller said something we do not speak.
148
 
api/routes_odoo_tables.py CHANGED
@@ -507,11 +507,19 @@ def _resync_state(cur):
507
  # reader goes red; a bucket with no binding is REPORTED, never silently served from the copy as
508
  # though it were read-through ([[one-evaluator-per-question]], [[gate-answers-the-wrong-question]]).
509
  #
510
- # ⚠ ONE BUCKET IS BOUND HERE (orders). The other seven still serve from the materialised copy and
511
- # say so on the wire (`readThrough: false`), because R6's second sentence — *"if there is lag or
512
- # it can't be done, you need to explicitly tell me why and recommend a fix"* — makes an unconverted
513
- # grid something to REPORT, not something to leave looking converted. Adding one is a spec row plus
514
- # a green oracle check.
 
 
 
 
 
 
 
 
515
 
516
  #: `ut_*` key -> how to read that grid straight out of the mirror.
517
  #:
@@ -589,9 +597,12 @@ def _odoo_sources():
589
  # ⭐ R6 / W30-T29 — TELL THE STORE LAYER WHICH DATABASES ARE CONNECTED, so `MAX_ROWS` stops
590
  # being a fact about them. `core` never imports up, so the declaration goes this way round.
591
  # ⚠ ALL EIGHT, not just the read-through-bound ones — every row in these tables comes from
592
- # Odoo, which is what R6 is about; being served from the stored copy today is our conversion
593
- # state, not a property of the data. `_sources`' own `register_connected` covers only the keys
594
- # a provider RETURNS, so this call is not redundant with it and must not be folded into it.
 
 
 
595
  _ut().register_connected(*[key for _b, key, _l, _f in rel.TABLES])
596
  GRID_SOURCES = {} # the LOCAL registry this builder fills and returns
597
  _s, _i, _n = ((lambda v: str(v or "")), (lambda v: int(v or 0)),
@@ -734,6 +745,186 @@ def _odoo_sources():
734
  "THEN '1' ELSE '' END", _s),
735
  },
736
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
737
  return GRID_SOURCES
738
 
739
 
@@ -918,11 +1109,45 @@ def _degrade(expr, have_by_alias, default_alias=""):
918
 
919
 
920
  def _source_for(cur, table_key):
921
- """The resolved spec for one connected grid, or None when this grid is not read-through yet."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
922
  spec = _sources().get(str(table_key or ""))
923
  if not spec:
924
  return None
925
  from harness import datastore
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
926
  # ⚠ `tables` maps the SQL alias a projection uses to the mirror table behind it. A single-table
927
  # spec declares none and its columns are bare, so it degrades against `table` as before.
928
  aliases = dict(spec.get("tables") or {})
@@ -1423,6 +1648,279 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1423
  return sql, params, notes
1424
 
1425
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1426
  def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=None,
1427
  search=None, tree=_TREE_UNSET, related=None):
1428
  """EVERYTHING THAT DECIDES **WHICH ROWS** A CONNECTED GRID MAY ANSWER OVER, compiled once.
@@ -1516,9 +2014,17 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
1516
 
1517
  spec = _source_for(cur, table_key)
1518
  if spec is None:
 
 
 
 
 
 
 
1519
  raise err(409, "not_read_through",
1520
- "this connected database is still served from its stored copy; it has no "
1521
- "read-through binding on this deployment yet")
 
1522
 
1523
  cols = _filter_columns(spec, fields)
1524
 
@@ -1636,8 +2142,20 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
1636
  "recommendation": "ask an administrator to set the restriction on a whole number, "
1637
  "or on a column that is not an amount"})
1638
 
 
 
 
 
 
 
 
 
1639
  # ── the predicate, pushed down ────────────────────────────────────────────────────────────
1640
- named = _leaf_cols(tree)
 
 
 
 
1641
  missing = sorted(named - set(cols))
1642
  if missing:
1643
  limits.append({
@@ -1687,9 +2205,12 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
1687
 
1688
  where, params = base_where, list(wall_params)
1689
  try:
 
 
 
1690
  pred = _fs().compile_filter_tree(
1691
  tree, conj=(filterConj if filterConj in ("and", "or") else "and"), columns=cols,
1692
- today=_today())
1693
  except ValueError as e:
1694
  # ⛔ A REFUSAL IS AN ANSWER, NOT A CRASH — and it must not become "no filter". Ranking ops
1695
  # ("top 10") have no SQL form in this compiler; saying so beats returning every row.
 
507
  # reader goes red; a bucket with no binding is REPORTED, never silently served from the copy as
508
  # though it were read-through ([[one-evaluator-per-question]], [[gate-answers-the-wrong-question]]).
509
  #
510
+ # ⭐⭐ W53-T19 / RULING R5 — EVERY ODOO BUCKET IS BOUND HERE NOW, AND THAT IS THE WHOLE TICKET.
511
+ # R5: *"Every `ut_odoo_*` table becomes read-through bound. The stored-copy refusal is deleted,
512
+ # not hidden."* Before this the registry held four of the ten declared keys
513
+ # (orders, order lines, GL lines, accounts) and the other four DECLARED grains — invoices, agents,
514
+ # vendors, bills — answered `409 not_read_through` on the rows door, which is what every Linked
515
+ # database tab onto them showed a person. They are bound below, off the SAME SQL their readers in
516
+ # `odoo_relational` already run, so the differential oracle has something to hold them to.
517
+ #
518
+ # ⛔ BINDING IS NOT UN-MATERIALISING, and conflating the two would delete rows six link rollups
519
+ # still fold. `_unmaterialisable` is the separate, gated decision about who may STOP STORING rows,
520
+ # and none of the four newly bound grains becomes eligible by being bound: each is small enough to
521
+ # live in the document and each is folded by a link declared on another table. What changes is
522
+ # that the WINDOW door can now answer them, which is what a relation pin needs.
523
 
524
  #: `ut_*` key -> how to read that grid straight out of the mirror.
525
  #:
 
597
  # ⭐ R6 / W30-T29 — TELL THE STORE LAYER WHICH DATABASES ARE CONNECTED, so `MAX_ROWS` stops
598
  # being a fact about them. `core` never imports up, so the declaration goes this way round.
599
  # ⚠ ALL EIGHT, not just the read-through-bound ones — every row in these tables comes from
600
+ # Odoo, which is what R6 is about; where its rows are SERVED FROM is our conversion state, not
601
+ # a property of the data. `_sources`' own `register_connected` covers only the keys a provider
602
+ # RETURNS, so this call is not redundant with it and must not be folded into it.
603
+ # ⚠ W53-T19: the two sets now coincide (every `TABLES` key is bound below), and the call still
604
+ # stands rather than being deleted as redundant — a grain declared but not yet bound is the
605
+ # normal state of the next connector, and this is the line that keeps it uncapped meanwhile.
606
  _ut().register_connected(*[key for _b, key, _l, _f in rel.TABLES])
607
  GRID_SOURCES = {} # the LOCAL registry this builder fills and returns
608
  _s, _i, _n = ((lambda v: str(v or "")), (lambda v: int(v or 0)),
 
745
  "THEN '1' ELSE '' END", _s),
746
  },
747
  }
748
+
749
+ # ═════════════════════════════════════════════════════════════════════════════════════════
750
+ # ⭐⭐ W53-T19 / RULING R5 — THE LAST FOUR DECLARED GRAINS: invoices, agents, vendors, bills.
751
+ #
752
+ # Each one is the SQL its reader in `odoo_relational` already runs, restated as a window. That
753
+ # is a second statement of one question and it is gated rather than trusted: `verify_scopes`'s
754
+ # `section_unmaterialise` holds every binding against its own `*_fields()` declaration in BOTH
755
+ # directions (a `cols` key with no declaration is a silent no-cell, because `rows_from_pool`
756
+ # projects strictly; a declaration with no `cols` key is an INACTIVE filter leaf, which
757
+ # WIDENS), and `section_read_through` is the differential oracle shape for the row values.
758
+ #
759
+ # ⛔⛔ NOT ONE `read_*` STATEMENT WAS TOUCHED TO MAKE THESE FIT, AND THAT IS A HARD RULE HERE.
760
+ # `verify_odoo_relational.FixtureCursor` DISPATCHES ON THE SELECT-CLAUSE HEAD, because
761
+ # `read_bills` reads `account_move` with a different projection and the opposite move types
762
+ # from `read_invoices`; aliasing either projection once already made the fixture recognise
763
+ # nothing and return a CONFIDENT EMPTY on every box with no mirror, six legs red. The specs
764
+ # below are new SQL beside those readers, never a rewrite of them.
765
+ #
766
+ # ⛔ THE PREDICATES ARE **IMPORTED**, NEVER RETYPED. `_POSTED_DOCS` and `_VENDOR_DOCS` are the
767
+ # only statement of which `account.move` documents belong to which grain, and a fifth copy of
768
+ # `move_type IN (...)` is how a grid and its reader start describing different populations.
769
+ # ⚠ They open with the bare column `state`, and they are left UNQUALIFIED on purpose: the one
770
+ # joined spec here (invoices) joins only a derived commission aggregate, which carries no
771
+ # `state`, `move_type` or `payment_state` column, so SQL resolution is unambiguous. Prefixing
772
+ # `am.` would qualify only the FIRST term of a two-term predicate, which is worse than not
773
+ # qualifying at all.
774
+ inv_key, ag_key = rel.INVOICES_KEY, rel.AGENTS_KEY
775
+ ven_key, bill_key = rel.VENDORS_KEY, rel.BILLS_KEY
776
+ _ut().register_connected(inv_key, ag_key, ven_key, bill_key)
777
+
778
+ # `checkbox` cells are the overlay's `'1'` / `''` convention (`odoo_relational._in_scope`), so
779
+ # a boolean column is coerced HERE rather than being CASEd in SQL: read as a bare column it
780
+ # goes through `_degrade`, which answers NULL when the mirror has not backfilled it, and NULL
781
+ # then lands as an honestly unticked cell instead of a Binder error.
782
+ _flag = (lambda v: "1" if v else "")
783
+ # ⛔ BLANK, NOT ZERO, AND `read_invoices` SAYS WHY: an invoice carrying more than one agent has
784
+ # NO single agent id, and `int(None or 0)` would render `0` — a plausible, wrong, clickable
785
+ # foreign key. The reader writes `""` for exactly that row and so does this.
786
+ _i_blank = (lambda v: "" if v in (None, "") else int(v))
787
+ _s_strip = (lambda v: str(v or "").strip())
788
+
789
+ # ── INVOICES ─────────────────────────────────────────────────────────────────────────────
790
+ # `read_invoices`' default projection: every POSTED customer document, the channel TAGGED
791
+ # rather than dropped. The commission aggregate is the reader's own subquery, verbatim, and it
792
+ # is the reason this grain needs `optional`: `account_invoice_line_agent` is an OCA module
793
+ # entity a mirror hydrated from an older seed can lack entirely, and the reader degrades to
794
+ # blank agent columns rather than refusing. So does this.
795
+ _AGENT_FOLD = (
796
+ "(SELECT invoice_id, count(DISTINCT agent_id) AS n_agents, "
797
+ " min(agent_id) AS one_agent, "
798
+ " string_agg(DISTINCT agent_name, ', ' ORDER BY agent_name) AS agent_names "
799
+ " FROM account_invoice_line_agent WHERE invoice_id IS NOT NULL GROUP BY invoice_id) ag")
800
+ GRID_SOURCES[inv_key] = {
801
+ "from_sql": f"(account_move am LEFT JOIN {_AGENT_FOLD} ON ag.invoice_id = am.id)",
802
+ # ⚠ `ag` IS ABSENT FROM THIS MAP ON PURPOSE: it is a derived alias, not a mirror table, so
803
+ # `_degrade` must leave its projections alone rather than look for a `PRAGMA table_info`
804
+ # that does not exist. `_source_for` refuses a spec whose declared tables are missing, and
805
+ # declaring `ag` here would turn a degradable absence into no binding at all.
806
+ "tables": {"am": "account_move"},
807
+ "where": f"{rel._POSTED_DOCS} AND partner_id IS NOT NULL",
808
+ "id": "am.id",
809
+ "needs_excluded": True,
810
+ "cols": {
811
+ "invoice_no": ("am.name", _s),
812
+ "odoo_id": ("am.id", _i),
813
+ "customer": ("am.partner_name", _s),
814
+ rel.JOIN_KEY: ("am.partner_id", _i),
815
+ "invoice_date": ("am.invoice_date", rel._as_date),
816
+ "due_date": ("am.invoice_date_due", rel._as_date),
817
+ # ⚠ THE SIGNED PAIR, exactly as the reader reads them: Odoo's `_signed` fields already
818
+ # carry a refund's direction, so nothing here re-derives a sign.
819
+ "residual": ("am.amount_residual_signed", _n),
820
+ "amount_untaxed": ("am.amount_untaxed_signed", _n),
821
+ "payment_state": ("am.payment_state", _s),
822
+ "move_type": ("am.move_type", _s),
823
+ "origin_order": ("am.invoice_origin", _s_strip),
824
+ "agent": ("ag.agent_names", _s),
825
+ rel.AGENT_JOIN_KEY: ("CASE WHEN ag.n_agents = 1 THEN ag.one_agent END", _i_blank),
826
+ "wholesale_scope": (
827
+ "CASE WHEN am.partner_id IN ({excluded}) THEN '' ELSE '1' END", _s),
828
+ },
829
+ "optional": (
830
+ {"absent": (("account_invoice_line_agent",),),
831
+ "without": {"from_sql": "account_move am",
832
+ "cols": {"agent": ("''", _s),
833
+ rel.AGENT_JOIN_KEY: ("CAST(NULL AS BIGINT)", _i_blank)}}},
834
+ ),
835
+ }
836
+
837
+ # ── AGENTS ───────────────────────────────────────────────────────────────────────────────
838
+ # ⭐ THE POPULATION IS A UNION OF TWO DISAGREEING SOURCES and `agent_fields`' docstring holds
839
+ # the measurement: 16 partners carry commission lines, 17 carry `res_partner.agent`, the union
840
+ # is 19. Either source alone silently drops real agents, so BOTH legs are here and each one is
841
+ # separately optional. The three `optional` entries are the three degraded mirrors, and the
842
+ # combined one is written LAST because entries apply in order and the last merge wins.
843
+ _COMMISSIONED = ("id IN (SELECT agent_id FROM account_invoice_line_agent "
844
+ " WHERE agent_id IS NOT NULL)")
845
+ GRID_SOURCES[ag_key] = {
846
+ "table": "res_partner",
847
+ "where": f"({_COMMISSIONED} OR COALESCE(agent, FALSE))",
848
+ "id": "id",
849
+ "cols": {
850
+ "agent": ("name", _s),
851
+ "odoo_id": ("id", _i),
852
+ rel.AGENT_JOIN_KEY: ("id", _i),
853
+ "flagged": ("agent", _flag),
854
+ "commissioned": (f"CASE WHEN {_COMMISSIONED} THEN '1' ELSE '' END", _s),
855
+ },
856
+ "optional": (
857
+ {"absent": (("account_invoice_line_agent",),),
858
+ "without": {"where": "COALESCE(agent, FALSE)",
859
+ "cols": {"commissioned": ("''", _s)}}},
860
+ {"absent": (("res_partner", "agent"),),
861
+ "without": {"where": _COMMISSIONED, "cols": {"flagged": ("''", _s)}}},
862
+ # ⛔ NEITHER SOURCE ⇒ NO POPULATION, SPELLED `1=0` RATHER THAN LEFT EMPTY. An empty
863
+ # `where` is EVERY partner, which is 3,649 customers wearing the Agents label; the
864
+ # reader answers `[]` on the same mirror and so must this.
865
+ {"absent": (("account_invoice_line_agent",), ("res_partner", "agent")),
866
+ "without": {"where": "1=0",
867
+ "cols": {"flagged": ("''", _s), "commissioned": ("''", _s)}}},
868
+ ),
869
+ }
870
+
871
+ # ── VENDORS ──────────────────────────────────────────────────────────────────────────────
872
+ # ⚠ DERIVED FROM THE BILLS, exactly as `read_vendors` is, and the asymmetry with customers is
873
+ # deliberate there: a partner with no posted bill has no payable history to show. MEASURED in
874
+ # that reader's docstring: 393 vendors, 0 bills with a null partner, nothing dangles.
875
+ # ⚠ ALIASED `p` AND EVERY COLUMN QUALIFIED, matching the reader, because `zip` unqualified is
876
+ # a bare identifier a SQL dialect is free to read as something else.
877
+ GRID_SOURCES[ven_key] = {
878
+ "from_sql": "res_partner p",
879
+ "tables": {"p": "res_partner"},
880
+ "where": (f"p.id IN (SELECT partner_id FROM account_move WHERE {rel._VENDOR_DOCS} "
881
+ " AND partner_id IS NOT NULL)"),
882
+ "id": "p.id",
883
+ "cols": {
884
+ "vendor": ("p.name", _s),
885
+ "odoo_id": ("p.id", _i),
886
+ rel.VENDOR_JOIN_KEY: ("p.id", _i),
887
+ "country": ("p.country_name", _s),
888
+ "email": ("p.email", _s),
889
+ "phone": ("p.phone", _s),
890
+ "mobile": ("p.mobile", _s),
891
+ "website": ("p.website", _s),
892
+ "vat": ("p.vat", _s),
893
+ # ⚠ `vendor_ref` HERE, `ref` IN THE MIRROR, and `vendor_fields` explains the rename:
894
+ # the bills grid already spends `ref` on the vendor's own invoice number.
895
+ "vendor_ref": ("p.ref", _s),
896
+ "street": ("p.street", _s),
897
+ "street2": ("p.street2", _s),
898
+ "city": ("p.city", _s),
899
+ "zip": ("p.zip", _s),
900
+ },
901
+ # `account_move` is a SECONDARY dependency here (it defines the population, it projects
902
+ # nothing), so its absence degrades to an empty grid rather than to no binding. The reader
903
+ # answers `[]` on that mirror for the same reason.
904
+ "optional": ({"absent": (("account_move",),), "without": {"where": "1=0"}},),
905
+ }
906
+
907
+ # ── BILLS ────────────────────────────────────────────────────────────────────────────────
908
+ # ⚠ DOCUMENT GRAIN, and `bill_fields` records why it is the only one that fits: 6,538 bills
909
+ # against 154,917 expense GL lines. This is the payable; the line ledger is `ut_odoo_gl_lines`
910
+ # above, and they are different tables answering different questions.
911
+ GRID_SOURCES[bill_key] = {
912
+ "table": "account_move",
913
+ "where": f"{rel._VENDOR_DOCS} AND partner_id IS NOT NULL",
914
+ "id": "id",
915
+ "cols": {
916
+ "bill_no": ("name", _s),
917
+ "odoo_id": ("id", _i),
918
+ "vendor": ("partner_name", _s),
919
+ rel.VENDOR_JOIN_KEY: ("partner_id", _i),
920
+ "invoice_date": ("invoice_date", rel._as_date),
921
+ "due_date": ("invoice_date_due", rel._as_date),
922
+ "amount_untaxed": ("amount_untaxed_signed", _n),
923
+ "residual": ("amount_residual_signed", _n),
924
+ "payment_state": ("payment_state", _s),
925
+ "move_type": ("move_type", _s),
926
+ },
927
+ }
928
  return GRID_SOURCES
929
 
930
 
 
1109
 
1110
 
1111
  def _source_for(cur, table_key):
1112
+ """The resolved spec for one connected grid, or None when this grid is not read-through yet.
1113
+
1114
+ ⭐⭐ W53-T19 — `optional` RESOLVES A SPEC'S **SECONDARY** MIRROR DEPENDENCIES, and it exists
1115
+ because R5 asks every Odoo grain to be bound while two of them read a table or a column a
1116
+ mirror can honestly lack. `_degrade` already answers the missing-COLUMN case for a BARE
1117
+ projection; it cannot answer a missing TABLE named in the FROM or in the WHERE, and a SELECT
1118
+ naming an absent table is a DuckDB Binder error reaching a user as a bare 500 (D-107's shape).
1119
+
1120
+ An entry is `{"absent": ((table[, column]), ...), "without": {<partial spec>}}`: when EVERY
1121
+ requirement it names is absent from the mirror, its `without` is merged over the spec, with
1122
+ `cols` merged key by key rather than replacing the map. Entries apply IN DECLARATION ORDER, so
1123
+ a combined case (both of `read_agents`' two sources missing) is written last and wins.
1124
+
1125
+ ⛔ DEGRADE, NEVER REFUSE, which is the posture `odoo_relational.columns` already sets for the
1126
+ readers: without its commission table the invoices grid serves blank agent cells, not a 409,
1127
+ and `read_invoices` degrades the same way over the same absence. ⚠ THE **BASE** TABLE IS A
1128
+ DIFFERENT QUESTION and keeps its existing answer: `tables`/`table` must all resolve, and a
1129
+ spec whose base table the mirror lacks is no binding at all (None, and the caller refuses).
1130
+ """
1131
  spec = _sources().get(str(table_key or ""))
1132
  if not spec:
1133
  return None
1134
  from harness import datastore
1135
+ for opt in (spec.get("optional") or ()):
1136
+ wants = tuple(opt.get("absent") or ())
1137
+ if not wants:
1138
+ continue
1139
+ gone = True
1140
+ for need in wants:
1141
+ need = tuple(need)
1142
+ have = datastore.columns_of(str(need[0]), cur=cur)
1143
+ if have and (len(need) < 2 or str(need[1]).lower() in have):
1144
+ gone = False
1145
+ break
1146
+ if not gone:
1147
+ continue
1148
+ without = dict(opt.get("without") or {})
1149
+ merged = {**spec["cols"], **(without.pop("cols", None) or {})}
1150
+ spec = {**spec, **without, "cols": merged}
1151
  # ⚠ `tables` maps the SQL alias a projection uses to the mirror table behind it. A single-table
1152
  # spec declares none and its columns are bare, so it degrades against `table` as before.
1153
  aliases = dict(spec.get("tables") or {})
 
1648
  return sql, params, notes
1649
 
1650
 
1651
+ # ── ⭐⭐ W53-T20 / D-377 — THE VIEW-MEMBERSHIP LEAF, ON A SERVER-WINDOWED GRID ─────────────────
1652
+ #
1653
+ # D-377: *"`Where View is [x]` is unavailable on any server-windowed (read-through Odoo) grid"* —
1654
+ # W37-T26 shipped the leaf for client-windowed grids and the SQL compiler never learned it. T08
1655
+ # makes every Odoo grid server-windowed, so the latent gap became a visible one.
1656
+ #
1657
+ # ⛔⛔ THE FIX IS A REWRITE, NOT A NEW SQL ARM, AND THAT IS THE WHOLE POINT.
1658
+ # `harness/filter_sql.py::_compile_cohort` ALREADY compiles "the row identity is in one of these
1659
+ # hand-supplied pid sets", and it already gets the three hard cases right: an empty set is `1=0`,
1660
+ # an ABSENT set is `1=0` **for `noneOf` too** (answering "everything" to `is none of [a set we
1661
+ # cannot see]` is the widening sin wearing a plausible face), and the membership test is wrapped in
1662
+ # `COALESCE(..., FALSE)` so a NULL row id does not make `NOT (id IN (...))` NULL and drop a row the
1663
+ # client would keep. A `__view__` leaf asks EXACTLY that question about a different kind of set. So
1664
+ # each leaf is rewritten into the `__cohort__` shape with the view's resolved pids supplied through
1665
+ # `cohort_sets=`, and `noneOf` is correct for free because it is the same compiler that already got
1666
+ # it right. `filter_sql.py` is not this lane's fence and does not need to be.
1667
+ #
1668
+ # ⭐ EXACTLY ONE PLACE LEARNS THE LEAF: `_compiled_read`, immediately before the ONE
1669
+ # `compile_filter_tree` call it makes. `/rows` and `/aggregates` are the same door (C1), so both
1670
+ # inherit it, and `totalUnfiltered` keeps counting the population with the reader's conditions
1671
+ # dropped because the rewrite happens to `tree` and never to `base_where`.
1672
+
1673
+ #: The two RESERVED pseudo-columns a filter tree may name. Neither is a column, and `_leaf_cols`
1674
+ #: cannot tell them apart from a real `colId` — it reads the key, not the vocabulary. Subtracting
1675
+ #: them is what keeps a membership leaf out of the `filter_ignored` sentence that explains a column
1676
+ #: with no mirror expression: that sentence would be FALSE here, and it reads as "your condition was
1677
+ #: dropped", which is the one thing a membership leaf must never be.
1678
+ _PSEUDO_COLS = frozenset(("__cohort__", "__view__"))
1679
+
1680
+
1681
+ def _active_cohort_leaves(nodes):
1682
+ """Every ACTIVE `__cohort__` leaf a tree names, at any depth.
1683
+
1684
+ "Active" in `filter_sql.is_rule_active`'s own sense for this leaf: driven by the SET it names,
1685
+ so a leaf with a blank value is half-built and ignored on both engines. Inactive leaves are
1686
+ excluded deliberately — reporting one would refuse a read the client renders happily.
1687
+ """
1688
+ out = []
1689
+ for n in (nodes or []):
1690
+ if not isinstance(n, dict):
1691
+ continue
1692
+ if isinstance(n.get("children"), list):
1693
+ out.extend(_active_cohort_leaves(n.get("children")))
1694
+ elif str(n.get("colId") or "") == "__cohort__" and _fs().parse_cohort_ids(n.get("value")):
1695
+ out.append(n)
1696
+ return out
1697
+
1698
+
1699
+ def _view_store(session, table_key):
1700
+ """The workspace document a saved view of THIS database lives in.
1701
+
1702
+ ⛔ `table_store.find_view`, NOT a second resolver. `done-when` is a row-set EQUALITY between
1703
+ this path and the client-windowed one, so a second implementation is the one thing guaranteed
1704
+ to fail it: the client reads the views `/workspace` served out of this same document.
1705
+ """
1706
+ import core.table_store as table_store
1707
+ return table_store.make(f"{table_key}_table_workspace", st=session.runtime)
1708
+
1709
+
1710
+ def _views_as_cohorts(tree, table_key, session, spec, cols, base_where, wall_params, cur, limits):
1711
+ """Rewrite every `__view__` leaf into the `__cohort__` shape. `(tree, cohort_sets)`.
1712
+
1713
+ `cohort_sets` is **None** when the tree names no view, and that is load-bearing rather than
1714
+ tidy: `_compile_cohort` REFUSES when `cohort_sets` is missing, which is how a genuine cohort
1715
+ leaf keeps answering `400 filter_unsupported` on this door exactly as it does today instead of
1716
+ quietly compiling to "matches nothing".
1717
+
1718
+ HOW A VIEW IS RESOLVED, mirroring `CustomerGrid.tsx::viewSets` step for step, because the
1719
+ acceptance is that both paths answer the same rows:
1720
+
1721
+ * the view is found in this database's workspace and the caller may see it, or it is
1722
+ UNRESOLVABLE;
1723
+ * a view LOCKED to a cohort is unresolvable here (the lock is resolved from this tenant's
1724
+ records, not from the connection) and is reported;
1725
+ * `config.filters` is compiled through the SAME `compile_filter_tree` the reader's own
1726
+ conditions go through, with `member_ids=config.memberPids` — which reproduces the client's
1727
+ `curated.has(pid) || matchFilterTree(...)` union exactly;
1728
+ * no filters and a curated `memberPids` is the client's `else if (curated)` branch: the
1729
+ membership IS the view;
1730
+ * no filters and no members means the view holds every row in scope;
1731
+ * the ids are materialised in ONE `SELECT DISTINCT` under `base_where`, uncapped, the same
1732
+ way `_related_pin` does it, so the wall rides along and standing rule 1 is kept.
1733
+
1734
+ THE THREE ANSWERS, AND EVERY ONE OF THEM IS SPELLED IN THE COHORT VOCABULARY:
1735
+ resolved to ids -> `anyOf`/`noneOf` over a key PRESENT in `cohort_sets`
1736
+ holds every row -> `is` becomes `noneOf` over an EMPTY set (`NOT (1=0)`, true of every row)
1737
+ and `is not` becomes a key that is absent (`1=0`)
1738
+ unresolvable -> a key that is ABSENT, which `_compile_cohort` answers `1=0` for BOTH ops.
1739
+ That is `evalNode`'s `if (!set) return false;` byte for byte, and it is
1740
+ D-377's negative control: `is not [a view we cannot resolve]` must match
1741
+ NOTHING, never everything.
1742
+ """
1743
+ import aios_grid
1744
+
1745
+ if not aios_grid.view_refs_of(tree):
1746
+ return tree, None
1747
+
1748
+ # ⛔ A GENUINE COHORT LEAF STILL REFUSES. Supplying `cohort_sets` for the views would otherwise
1749
+ # make a real `__cohort__` leaf beside them compile to `1=0` in silence, where today it answers
1750
+ # 400 with a cause. Narrowing is the safe direction, but an unanswerable condition that reports
1751
+ # nothing is how a reader ends up trusting an empty table.
1752
+ if _active_cohort_leaves(tree):
1753
+ raise err(400, "filter_unsupported",
1754
+ "a condition on cohort membership cannot be evaluated on this database's live "
1755
+ "connection, because a cohort is resolved from this tenant's own records rather "
1756
+ "than from the connection. Filter on a saved view instead, or open this "
1757
+ "database's stored copy")
1758
+
1759
+ store = _view_store(session, table_key)
1760
+ sets, memo, unresolved = {}, {}, []
1761
+ counter = [0]
1762
+
1763
+ def key_for():
1764
+ counter[0] += 1
1765
+ # ⚠ A SYNTHETIC KEY, NEVER THE VIEW ID. `parse_cohort_ids` splits `value` on commas and
1766
+ # truncates at 120 characters; a view id is free text and may carry either. A key we mint
1767
+ # cannot collide, cannot split, and cannot be mistaken for a cohort the tenant owns.
1768
+ return "__view_%d__" % counter[0]
1769
+
1770
+ def resolve(vid, seen):
1771
+ """`('ids', [...])` / `('all', None)` / `(None, reason)` for one view id."""
1772
+ if vid in memo:
1773
+ return memo[vid]
1774
+ if vid in seen:
1775
+ # `viewSets`' `resolving` guard: a view re-entered while it is being resolved is left
1776
+ # ABSENT, so a stored loop degrades to an explained empty table, not a hung request.
1777
+ return None, "it refers to itself through another saved view"
1778
+ found = store.find_view(vid, prefer_owner=session.uname)
1779
+ if not found:
1780
+ got = (None, "it is no longer there")
1781
+ memo[vid] = got
1782
+ return got
1783
+ owner, view = found
1784
+ if owner != session.uname and not _may_see_view(session, vid, store):
1785
+ got = (None, "your account cannot open it")
1786
+ memo[vid] = got
1787
+ return got
1788
+ cfg = (view.get("config") or {}) if isinstance(view, dict) else {}
1789
+ if str(cfg.get("cohortLock") or "").strip():
1790
+ got = (None, "it is locked to a cohort, and a cohort is resolved from this tenant's "
1791
+ "own records rather than from this database's live connection")
1792
+ memo[vid] = got
1793
+ return got
1794
+ members = []
1795
+ for raw in (cfg.get("memberPids") or ()):
1796
+ try:
1797
+ members.append(int(raw))
1798
+ except (TypeError, ValueError): # noqa: PERF203
1799
+ continue
1800
+ raw_nodes = cfg.get("filters") or []
1801
+ if not isinstance(raw_nodes, list):
1802
+ raw_nodes = []
1803
+ if not raw_nodes:
1804
+ # `filters.length` is the client's own test, and it is the NODE COUNT rather than
1805
+ # "anything active": with no nodes at all the curated set IS the view, and with nodes
1806
+ # that all happen to be half-built the view holds everything. Two different answers
1807
+ # from one list, so the emptiness is checked before the compiler sees it.
1808
+ got = ("ids", members) if members else ("all", None)
1809
+ memo[vid] = got
1810
+ return got
1811
+ nodes = rewrite(raw_nodes, seen + (vid,))
1812
+ unknown = sorted((_leaf_cols(nodes) - _PSEUDO_COLS) - set(cols))
1813
+ if unknown:
1814
+ # ⛔ UNRESOLVABLE, NOT "IGNORE THAT LEAF". `compile_filter_tree` would treat a column it
1815
+ # cannot see as INACTIVE, which WIDENS the view's row set - and `cols` has the field
1816
+ # wall's hidden columns already stripped, so for a scoped reader that widening would be
1817
+ # the permission door leaking through the back. Reported below, never silently applied.
1818
+ got = (None, "it filters on " + ", ".join(unknown)
1819
+ + ", which this database's live connection cannot read for your account")
1820
+ memo[vid] = got
1821
+ return got
1822
+ try:
1823
+ pred = _fs().compile_filter_tree(nodes, conj=("or" if cfg.get("filterConj") == "or"
1824
+ else "and"),
1825
+ columns=cols, member_ids=(members or None),
1826
+ id_sql=spec["id"], today=_today(), cohort_sets=sets)
1827
+ except ValueError as exc:
1828
+ got = (None, "it uses a condition this database's live connection cannot evaluate ("
1829
+ + str(exc) + ")")
1830
+ memo[vid] = got
1831
+ return got
1832
+ if pred is None:
1833
+ # Every condition in it is half-built, so it matches every row - which is what
1834
+ # `matchFilterTree` answers for an inactive tree, and the `member_ids` union rides
1835
+ # inside that same `if (filters.length)` on both engines.
1836
+ got = ("all", None)
1837
+ memo[vid] = got
1838
+ return got
1839
+ if pred.uses_aggregate:
1840
+ got = (None, "it filters on an aggregate column, which this database's live connection "
1841
+ "cannot evaluate one row at a time")
1842
+ memo[vid] = got
1843
+ return got
1844
+ frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"]
1845
+ where = f"({base_where}) AND ({pred.sql})" if base_where else pred.sql
1846
+ ids = [int(r[0]) for r in cur.execute(
1847
+ f'SELECT DISTINCT {spec["id"]} FROM {frm_body} WHERE {where}',
1848
+ list(wall_params) + list(pred.params)).fetchall() if r and r[0] is not None]
1849
+ got = ("ids", ids)
1850
+ memo[vid] = got
1851
+ return got
1852
+
1853
+ def rewrite(nodes, seen):
1854
+ out = []
1855
+ for n in (nodes or []):
1856
+ if not isinstance(n, dict):
1857
+ out.append(n)
1858
+ continue
1859
+ if isinstance(n.get("children"), list):
1860
+ out.append(dict(n, children=rewrite(n.get("children"), seen)))
1861
+ continue
1862
+ if str(n.get("colId") or "") != aios_grid.VIEW_FIELD:
1863
+ out.append(n)
1864
+ continue
1865
+ vid = str(n.get("value") or "").strip()[:aios_grid.MAX_VIEW_ID]
1866
+ if not vid:
1867
+ # Half-built, and half-built is IGNORED on both engines. Left as it stands: its
1868
+ # `colId` is not a column, so `is_rule_active` already answers False for it.
1869
+ out.append(n)
1870
+ continue
1871
+ # `normalizeViewOp`: anything that is not `notInView` reads as `inView`, so a leaf
1872
+ # carrying a corrupted op asks the narrower question rather than the wider one.
1873
+ not_in = str(n.get("op") or "") == "notInView"
1874
+ key = key_for()
1875
+ kind, got = resolve(vid, seen)
1876
+ if kind == "ids":
1877
+ sets[key] = got
1878
+ op = "noneOf" if not_in else "anyOf"
1879
+ if len(got) >= _PIN_REPORT_AT:
1880
+ limits.append({
1881
+ "subject": "view", "effect": "slow",
1882
+ "cause": f"the saved view this condition names holds {len(got):,} rows, "
1883
+ f"and each page of this database names every one of them in the "
1884
+ f"query that narrows it",
1885
+ "recommendation": "add a condition beside the view to ask a smaller "
1886
+ "question, or open the saved view itself"})
1887
+ elif kind == "all":
1888
+ if not_in:
1889
+ op = "anyOf" # key absent -> 1=0
1890
+ else:
1891
+ sets[key] = []
1892
+ op = "noneOf" # NOT (1=0) -> true of every row
1893
+ else:
1894
+ op = "anyOf" # key absent -> 1=0 for `is` AND for `is not`
1895
+ unresolved.append((vid, got))
1896
+ out.append({"colId": "__cohort__", "op": op, "value": key})
1897
+ return out
1898
+
1899
+ tree = rewrite(tree, ())
1900
+ if unresolved:
1901
+ limits.append({
1902
+ "subject": ", ".join(vid for vid, _why in unresolved),
1903
+ "effect": "filter_unresolved",
1904
+ "cause": "this condition asks whether a row is in a saved view that could not be "
1905
+ "resolved on this database's live connection ("
1906
+ + "; ".join(f"{vid}: {why}" for vid, why in unresolved)
1907
+ + "), so it matches no rows at all, for `is not` as well as for `is`",
1908
+ "recommendation": "pick a saved view you can open on this database, or remove the "
1909
+ "condition"})
1910
+ return tree, sets
1911
+
1912
+
1913
+ def _may_see_view(session, vid, store):
1914
+ """May this caller open that saved view? The same predicate the view rail asks.
1915
+
1916
+ ⛔ NOT SKIPPED FOR BEING INCONVENIENT. A view a caller cannot see resolves to nothing on the
1917
+ client (it is not in the payload at all), so resolving it here would make this door answer a
1918
+ question the other door cannot, out of a row set somebody else curated.
1919
+ """
1920
+ import core.shares as shares
1921
+ return shares.may_see("view", vid, session.uname, is_admin=session.admin, st=store.st)
1922
+
1923
+
1924
  def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=None,
1925
  search=None, tree=_TREE_UNSET, related=None):
1926
  """EVERYTHING THAT DECIDES **WHICH ROWS** A CONNECTED GRID MAY ANSWER OVER, compiled once.
 
2014
 
2015
  spec = _source_for(cur, table_key)
2016
  if spec is None:
2017
+ # ⭐⭐ W53-T19 / R5 — THE SENTENCE IS REWRITTEN AND THE REFUSAL IS NOT. R5 retires the
2018
+ # phrase, not the guard: `verify_scopes` drives `_source_for` to None as a negative control
2019
+ # and requires a 409 here rather than a grid quietly served from somewhere else, and every
2020
+ # Odoo grain is bound today only on a mirror that carries the tables they read. The cause
2021
+ # is now named as what it is, an absent binding, in the same words
2022
+ # `relations.unserved_target_refusal` uses for the same absence.
2023
+ # ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
2024
  raise err(409, "not_read_through",
2025
+ "this connected database has no read-through binding on this deployment, so "
2026
+ "its rows cannot be read a window at a time here. Open it from the Data "
2027
+ "section, or ask for a read-through binding to be added for it")
2028
 
2029
  cols = _filter_columns(spec, fields)
2030
 
 
2142
  "recommendation": "ask an administrator to set the restriction on a whole number, "
2143
  "or on a column that is not an amount"})
2144
 
2145
+ # ── W53-T20 / D-377 — the view-membership leaf, rewritten into the cohort shape ───────────
2146
+ # ⭐ HERE, AND NOWHERE ELSE. After the wall and the pin (so a view resolves inside the scope
2147
+ # the reader is held to, exactly as `viewSets` resolves inside the rows the client holds) and
2148
+ # before `_leaf_cols` below, so the leaf never reaches the sentence that explains a column with
2149
+ # no mirror expression. One place learns it; `/rows` and `/aggregates` share this compiler.
2150
+ tree, cohort_sets = _views_as_cohorts(tree, table_key, session, spec, cols,
2151
+ base_where, wall_params, cur, limits)
2152
+
2153
  # ── the predicate, pushed down ────────────────────────────────────────────────────────────
2154
+ # ⛔ `_PSEUDO_COLS` is subtracted BEFORE the missing-column test. `__cohort__` and `__view__`
2155
+ # are not columns and never will be in `cols`, so leaving them in would report every membership
2156
+ # condition as a column the mirror cannot read - a false sentence, and one that reads as "your
2157
+ # filter was dropped" beside a filter that was in fact applied.
2158
+ named = _leaf_cols(tree) - _PSEUDO_COLS
2159
  missing = sorted(named - set(cols))
2160
  if missing:
2161
  limits.append({
 
2205
 
2206
  where, params = base_where, list(wall_params)
2207
  try:
2208
+ # ⭐ `cohort_sets` IS PASSED ONLY WHEN A VIEW LEAF WAS REWRITTEN (it is None otherwise), and
2209
+ # that is what keeps a genuine cohort leaf REFUSING here rather than compiling to `1=0` in
2210
+ # silence. `id_sql` rides along because `_compile_cohort` raises without it.
2211
  pred = _fs().compile_filter_tree(
2212
  tree, conj=(filterConj if filterConj in ("and", "or") else "and"), columns=cols,
2213
+ id_sql=spec["id"], today=_today(), cohort_sets=cohort_sets)
2214
  except ValueError as e:
2215
  # ⛔ A REFUSAL IS AN ANSWER, NOT A CRASH — and it must not become "no filter". Ranking ops
2216
  # ("top 10") have no SQL form in this compiler; saying so beats returning every row.
api/routes_sheet.py CHANGED
@@ -35,6 +35,8 @@ while its surface is a 404.
35
  (standing rule 2), and each names both the cause and the subject.
36
  """
37
 
 
 
38
  import os
39
  import tempfile
40
  import threading
@@ -88,11 +90,15 @@ def _mirror(session: Session):
88
  `RuntimeError` means the mirror is completing its first sync, so it is a 503 the caller may
89
  retry. `DatastoreMismatch` SUBCLASSES `RuntimeError`, so the guard must run ABOVE the try, and
90
  collapsing them would turn the loudest refusal in the system into a spinner.
 
 
 
 
91
  """
92
  import routes_odoo_tables as rot
93
  import odoo_relational as rel
94
 
95
- def _for(table_key):
96
  fields = None
97
  for _bucket, key, _label, mk_fields in rel.TABLES:
98
  if key == table_key:
@@ -107,16 +113,7 @@ def _mirror(session: Session):
107
  # ⚠ `TABLES` ITSELF IS UNTOUCHED — it has other consumers (`declared_schema_fields`,
108
  # `_odoo_sources`' `register_connected`) that must keep seeing exactly eight rows.
109
  is_registry_grid = fields is None and table_key in rel._REGISTRY_GRID_FIELDS
110
- if is_registry_grid:
111
- import core.perm_scope as perm_scope
112
- try:
113
- fields = perm_scope.scoped_fields(session.user, table_key, st=session.runtime)
114
- except Exception: # noqa: BLE001
115
- # ⚠ THE FIELD LIST DEGRADES TO THE STATIC CONTRACT, NEVER TO A REFUSAL HERE — the
116
- # membership question (is this a connected database at all) is answered, and a
117
- # field-list hiccup belongs to the read below, which DOES refuse loudly.
118
- fields = rel._REGISTRY_GRID_FIELDS[table_key]()
119
- if fields is None:
120
  raise err(404, "not_connected", f"{table_key} is not a connected Odoo database.")
121
  try:
122
  cur, mismatch = rot._mirror_cur(session)
@@ -125,33 +122,328 @@ def _mirror(session: Session):
125
  if mismatch:
126
  raise err(409, "cross_tenant_store", mismatch)
127
  if is_registry_grid:
128
- # ⛔ NEITHER GRID IS READ-THROUGH (`rot._source_for` answers None for both, always —
129
- # their rows are the store's own, not a mirror derivation), so this branch never asks
130
- # that question. `perm_scope.scoped_table` is the SAME wall every other reader of
131
- # these two grids goes through (row scope + field grants); nothing here widens it.
132
- try:
133
- rows = perm_scope.scoped_table(session.user, table_key, st=session.runtime)
134
- except perm_scope.Denied:
135
- raise err(403, "database_unreadable", f"You cannot read {table_key}.")
136
- except perm_scope.UnknownTable:
137
- raise err(404, "not_connected", f"{table_key} is not a connected Odoo database.")
138
- except perm_scope.Unresolvable as exc:
139
- raise err(409, "not_read_through", str(exc))
140
- spec = rel.registry_grid_spec(cur, table_key, fields, rows)
141
- return cur, spec, rot._filter_columns(spec, fields)
 
 
 
142
  spec = rot._source_for(cur, table_key)
143
  if spec is None:
144
  raise err(409, "not_read_through",
145
- f"{table_key} is still served from its stored copy, so a cell cannot read "
146
- "through to it on this deployment yet.")
147
- return cur, spec, rot._filter_columns(spec, fields)
 
 
 
 
 
148
 
149
  return _for
150
 
151
 
152
- def _view_filter(session: Session, database: str, view_id: str, view_name: str = ""):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  """`(nodes, conj)` for a saved view's filter, or a `view_missing` refusal that NAMES it.
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  ⛔⛔ `prefer_owner=session.uname` IS LOAD-BEARING AND OMITTING IT IS A SILENT CROSS-USER READ.
156
  The system view id `all-customers` is pinned on every database, and every user who has ever
157
  touched that view's config holds their OWN record under the same id, so a bare first-hit scan
@@ -163,10 +455,42 @@ def _view_filter(session: Session, database: str, view_id: str, view_name: str =
163
  ⚠ The refusal names the view, which is why `clean_binding` keeps `view_name` on the binding:
164
  once the record is deleted there is nothing left to look a name up from.
165
  """
166
- from core import table_store
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  # ⚠ `TableStore(table_key, st=...)`, in that order. `st` is the STORE HANDLE, and passing the
168
  # session's runtime is what makes the lookup read THIS tenant's bucket rather than tenant #0's.
169
- store = table_store.TableStore(database, st=session.runtime)
 
170
  # ⭐⭐ `include_trashed=True` IS R11, AND IT IS ONE KEYWORD BECAUSE THE DEFAULT MUST NOT MOVE
171
  # (wave 51, W51-T26). A deleted view is MOVED into `<owner>.trash`, so the bare scan answered
172
  # None and this door refused a cell whose view somebody deleted an hour ago and can still
@@ -177,11 +501,34 @@ def _view_filter(session: Session, database: str, view_id: str, view_name: str =
177
  # permission-adjacent (shares, starred, publish, forms); widening there would open doors no
178
  # ticket asked about, with every gate green.
179
  found = store.find_view(view_id, prefer_owner=session.uname, include_trashed=True)
180
- if not found:
 
 
 
 
 
 
 
181
  raise err(409, "view_missing", f"View {view_name or view_id} no longer exists.")
182
- _owner, view = found
183
  import routes_odoo_tables as rot
184
- return rot._fe().tree_parts((view or {}).get("filters"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
 
187
  #: ⛔ THE TWO CAP CODES ANSWER 413, NOT 400 (contract C3). A 400 says the request was malformed and
@@ -413,6 +760,10 @@ def _reresolved_for_reader(session: Session, book):
413
  fresh = _copy.deepcopy(book)
414
  stamp = _now_iso()
415
  seen_db = {}
 
 
 
 
416
  touched = 0
417
  store = _store(session)
418
  wid = book.get("id") or ""
@@ -460,7 +811,7 @@ def _reresolved_for_reader(session: Session, book):
460
  continue
461
 
462
  try:
463
- out = _resolve_binding(session, binding)
464
  except HTTPException as exc:
465
  detail = getattr(exc, "detail", None) or {}
466
  info = detail.get("error") if isinstance(detail, dict) else None
@@ -1120,8 +1471,11 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1120
  forty cells to one database asks once; a reader who has lost access to that database gets a
1121
  refusal on every one of its cells rather than a stale number quietly repainting.
1122
 
1123
- ⚠ Each distinct `view_id` is resolved ONCE. `table_store.find_view` runs a legacy migration on
1124
- every call, so resolving per cell would make a forty-cell refresh do forty migrations.
 
 
 
1125
 
1126
  ⛔⛔ C5 — THIS IS A WRITE DOOR, BECAUSE IT ENDS IN `put_workbook`, AND A VIEWER IS REFUSED
1127
  HERE FOR A REASON THAT IS NOT ABOUT PERMISSION TO SEE. A viewer whose refresh were allowed
@@ -1143,6 +1497,12 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1143
 
1144
  stamp = _now_iso()
1145
  seen_db = {}
 
 
 
 
 
 
1146
  for tab in book.get("sheets") or ():
1147
  for addr, cell in (tab.get("cells") or {}).items():
1148
  if not isinstance(cell, dict) or cell.get("kind") != "bound":
@@ -1163,7 +1523,7 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
1163
  "message": f"You cannot read {db}."}
1164
  continue
1165
  try:
1166
- out = _resolve_binding(session, binding)
1167
  except HTTPException as exc:
1168
  detail = getattr(exc, "detail", None) or {}
1169
  info = detail.get("error") if isinstance(detail, dict) else None
@@ -1338,7 +1698,7 @@ def _formula_message(code, subject=""):
1338
  }.get(code, "This formula could not be calculated.")
1339
 
1340
 
1341
- def _resolve_binding(session: Session, raw_binding, *, today=None):
1342
  """Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
1343
 
1344
  The order below is the contract, not a preference:
@@ -1346,6 +1706,12 @@ def _resolve_binding(session: Session, raw_binding, *, today=None):
1346
  2. the mirror cursor, whose two failures mean opposite things;
1347
  3. the ROW wall, fail-closed, refusing 409 when it names a column the mirror cannot answer;
1348
  4. the binding's own scope, whose unanswerable columns are REPORTED rather than dropped.
 
 
 
 
 
 
1349
  """
1350
  from modules import sheet as sheet_mod
1351
  import core.perm_scope as perm_scope
@@ -1355,8 +1721,25 @@ def _resolve_binding(session: Session, raw_binding, *, today=None):
1355
  except sheet_mod.SheetRefusal as exc:
1356
  raise err(400, exc.code, exc.message)
1357
 
 
 
 
 
 
 
1358
  database = _require_database(session, binding["database"])
1359
- cur, spec, cols = _mirror(session)(database)
 
 
 
 
 
 
 
 
 
 
 
1360
 
1361
  # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
1362
  wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
@@ -1379,7 +1762,7 @@ def _resolve_binding(session: Session, raw_binding, *, today=None):
1379
  scope = binding["scope"]
1380
  if scope.get("view_id"):
1381
  scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"],
1382
- scope.get("view_name", ""))
1383
  else:
1384
  scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
1385
 
@@ -1412,6 +1795,21 @@ def _resolve_binding(session: Session, raw_binding, *, today=None):
1412
 
1413
  row = cur.execute(sql, params).fetchone()
1414
  value = row[0] if row else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1415
  return {"value": value, "limits": limits, "database": database, "binding": binding}
1416
 
1417
 
@@ -1478,7 +1876,12 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s
1478
  raise err(400, exc.code, exc.message)
1479
 
1480
  database = _require_database(session, binding["database"])
1481
- cur, spec, cols = _mirror(session)(database)
 
 
 
 
 
1482
 
1483
  wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
1484
  if perm_scope.row_scope_applies(session.user, database) else None)
@@ -1508,3 +1911,152 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s
1508
  else:
1509
  out["filter"] = scope.get("filter")
1510
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  (standing rule 2), and each names both the cause and the subject.
36
  """
37
 
38
+ import hashlib
39
+ import json
40
  import os
41
  import tempfile
42
  import threading
 
90
  `RuntimeError` means the mirror is completing its first sync, so it is a 503 the caller may
91
  retry. `DatastoreMismatch` SUBCLASSES `RuntimeError`, so the guard must run ABOVE the try, and
92
  collapsing them would turn the loudest refusal in the system into a spinner.
93
+
94
+ ⭐⭐ W53-T13 — `_for` TAKES A `metric_window` NOW, AND EVERY EXISTING CALL SITE IS UNCHANGED.
95
+ It is keyword-only with a None default, so `_mirror(session)(database)` still means "leave
96
+ every Metric column at its own declared window". See `_registry_mirror` for what a window does.
97
  """
98
  import routes_odoo_tables as rot
99
  import odoo_relational as rel
100
 
101
+ def _for(table_key, *, metric_window=None):
102
  fields = None
103
  for _bucket, key, _label, mk_fields in rel.TABLES:
104
  if key == table_key:
 
113
  # ⚠ `TABLES` ITSELF IS UNTOUCHED — it has other consumers (`declared_schema_fields`,
114
  # `_odoo_sources`' `register_connected`) that must keep seeing exactly eight rows.
115
  is_registry_grid = fields is None and table_key in rel._REGISTRY_GRID_FIELDS
116
+ if fields is None and not is_registry_grid:
 
 
 
 
 
 
 
 
 
117
  raise err(404, "not_connected", f"{table_key} is not a connected Odoo database.")
118
  try:
119
  cur, mismatch = rot._mirror_cur(session)
 
122
  if mismatch:
123
  raise err(409, "cross_tenant_store", mismatch)
124
  if is_registry_grid:
125
+ # ⛔⛔ ONE ASSEMBLY PER REQUEST PER (DATABASE, WINDOW), NOT ONE PER CELL. `refresh_sheet`
126
+ # resolves a binding CELL BY CELL, and this branch now costs a full `/workspace`
127
+ # assembly rather than a `scoped_table` read: measured on the running app, 40 to 70
128
+ # seconds each. Forty cells on one database would rebuild that forty times and time the
129
+ # door out, which is a worse failure than the one this ticket fixes because it takes the
130
+ # whole workbook with it. `_view_filter`'s own `memo` argument exists for exactly this
131
+ # shape; the cache hangs off the SESSION because that object is built fresh by
132
+ # `require_session` on every request and dies with it, so nothing can outlive its own
133
+ # cursor or leak across users. The temp table it names lives in that same cursor.
134
+ memo = getattr(session, "_sheet_mirrors", None)
135
+ if memo is None:
136
+ memo = {}
137
+ session._sheet_mirrors = memo
138
+ slot = (table_key, json.dumps(metric_window, sort_keys=True, default=str))
139
+ if slot not in memo:
140
+ memo[slot] = _registry_mirror(session, cur, table_key, metric_window)
141
+ return memo[slot]
142
  spec = rot._source_for(cur, table_key)
143
  if spec is None:
144
  raise err(409, "not_read_through",
145
+ f"{table_key} has no read-through binding on this deployment, so a cell cannot "
146
+ "read through to it yet.")
147
+ # ⚠ THE FIELD LIST RIDES ON THE SPEC (W53-T13). `_resolve_binding` has to ask whether the
148
+ # bound column can be TOTALLED at all, and that question needs the field's own `type` and
149
+ # `rollup` bag, which `_filter_columns` reduces away. Copying rather than mutating is
150
+ # `_source_for`'s own idiom (it returns `{**spec, "cols": resolved}`) and matters for the
151
+ # same reason: the spec dict handed back by `_source_for` is not this call's to keep.
152
+ return cur, {**spec, "fields": fields}, rot._filter_columns(spec, fields)
153
 
154
  return _for
155
 
156
 
157
+ def _registry_assembly(session: Session, table_key: str):
158
+ """The `g` dict `/workspace` builds for one compiled registry grid, or a NAMED refusal.
159
+
160
+ ⭐⭐ W53-T13 — THIS IS THE FIX, AND IT IS A SECOND CALLER OF AN ESTABLISHED PATH RATHER THAN A
161
+ NEW ONE. `_offered_view` above already reaches for these same two assemblies. Measured on the
162
+ running app as `admin@royal-imports`: `/workspace?scope=customer` serves **47** fields, while
163
+ `perm_scope.scoped_fields` resolves through `routes_grid.py::_customer_rows`, which returns
164
+ `list(aios_grid.FIELDS)` - the **static 37-key contract**. So the Sheet was building its temp
165
+ table out of 37 of the tenant's 47 columns and `aggregate_sql` then refused the other 10 as
166
+ `field_unknown`, Metric and plain `custom_` alike. `count` was the only aggregate that worked
167
+ because it returns `COUNT(*)` before it ever looks at `columns`, which is exactly the owner's
168
+ report: *"It seems only Count works."*
169
+
170
+ ⛔⛔ IT WIDENS NOTHING, AND THAT IS CHECKED RATHER THAN HOPED. `grid_assembly` applies
171
+ `perm_scope.apply_row_scope` (`routes_customers.py:358`) and `perm_scope.hidden_keys`
172
+ (`routes_customers.py:496`), narrowing the field list, the rows AND the overlay dict together;
173
+ `product_assembly` does the same. It is the wall this person's OWN grid goes through, so a
174
+ Sheet cell sourced from it can only ever see what they are already shown.
175
+
176
+ ⚠ `consume_corrections=False` IS NOT OPTIONAL, for `_offered_view`'s reason: those one-shot
177
+ field-name correction acks belong to the `/workspace` refresh that exists to show them to the
178
+ person who made the edit, and a bound cell resolving its scope must not eat them.
179
+
180
+ ⛔ AN UNEXPECTED FAILURE REFUSES LOUDLY AND DOES NOT DEGRADE TO THE STATIC CONTRACT. Falling
181
+ back would answer the cell out of 37 columns while the person is looking at 47, which is the
182
+ defect this function exists to end, and it would do it with a 200.
183
+ """
184
+ import core.perm_scope as perm_scope
185
+ try:
186
+ if table_key == "product_data":
187
+ from routes_products import product_assembly
188
+ return product_assembly(session, scope="product", consume_corrections=False)
189
+ from routes_customers import grid_assembly
190
+ return grid_assembly(session, scope="customer", consume_corrections=False)
191
+ except perm_scope.Denied:
192
+ raise err(403, "database_unreadable", f"You cannot read {table_key}.")
193
+ except HTTPException:
194
+ raise
195
+ except Exception as exc: # noqa: BLE001
196
+ # ⛔ THE SENTENCE A PERSON READS SAYS WHAT HAPPENED; THE LOG SAYS WHY. Without this line
197
+ # the refusal is honest and undiagnosable at the same time: it names the database and the
198
+ # act, and nothing anywhere records which call inside a 300 line assembly failed.
199
+ # `harness.telemetry.error` is the same channel `routes_customers._measure_err` uses.
200
+ try:
201
+ import harness.telemetry as _tel
202
+ _tel.error("api:sheet-registry-assembly", exc)
203
+ except Exception: # noqa: BLE001
204
+ pass
205
+ raise err(503, "store_not_ready",
206
+ f"{table_key} could not be assembled for this cell, so the number is not being "
207
+ "shown rather than shown from an older set of columns. Try again in a moment.")
208
+
209
+
210
+ def _registry_mirror(session: Session, cur, table_key: str, metric_window):
211
+ """`(cursor, spec, columns)` for one compiled registry grid, at the cell's own period.
212
+
213
+ ⭐⭐ R7's SECOND HALF LIVES HERE: *"must also be bounded by date time lookup"*. `g["derived"]`
214
+ resolves each Metric column at ITS OWN declared window (`{kind: "ltm"}` on both of the live
215
+ ones), NOT at the cell's period, so a cell labelled one month would otherwise print a twelve
216
+ month number. When the binding carries a period, every Metric column is re-resolved at THAT
217
+ window through the SAME evaluator the grid renders from (`core/measure_resolve.py::
218
+ column_values` for the customer grain, `routes_products._measure_cells` for the product one),
219
+ so a Sheet cell and the grid cannot disagree about a number.
220
+
221
+ ⛔ A METRIC THAT CANNOT BE RESOLVED AT THE REQUESTED WINDOW GOES BLANK AND IS REPORTED. It
222
+ does NOT fall back to its own window: that would answer a wider question under a narrower
223
+ label, with nothing on screen saying so. The report is a `limits` row (standing rule 1).
224
+
225
+ ⛔ AND A METRIC THIS ACCOUNT MAY NOT SEE IS NEVER RE-RESOLVED. `grid_assembly` skips
226
+ `column_values` entirely when `may_metrics` is off, so a column with no value anywhere in
227
+ `g["derived"]` is one the capability wall has already answered for. Re-resolving it here would
228
+ be a second answer to that question, from the one door that never asked it.
229
+ """
230
+ import aios_grid
231
+ import odoo_relational as rel
232
+ import routes_odoo_tables as rot
233
+ from modules import sheet as sheet_mod
234
+
235
+ g = _registry_assembly(session, table_key)
236
+ fields = list(g.get("fields") or [])
237
+ derived, bounded, limits = _metric_derived(session, table_key, g, metric_window)
238
+ rows = aios_grid.rows_from_pool(g["rows_src"], fields, (g.get("ws") or {}).get("overlays"),
239
+ derived=derived)
240
+ # ⛔ THE TYPES ARE NORMALISED FOR THE MIRROR ONLY. See `modules/sheet.py::mirror_field_type`:
241
+ # `metric`, `rating` and a numeric `rollup` are in neither `_REGISTRY_COL_TYPE` nor
242
+ # `filter_sql.NUMERIC_TYPES`, so without this they land as VARCHAR and compare as strings.
243
+ # ⚠ THE SAME LIST GOES TO BOTH CALLS, deliberately. `registry_grid_spec` picks the SQL type and
244
+ # `_filter_columns` picks the compiler's type; handing them two different lists is how a column
245
+ # ends up stored as one thing and compared as another.
246
+ spec_fields = sheet_mod.mirror_fields(fields)
247
+ spec = rel.registry_grid_spec(cur, table_key, spec_fields, rows)
248
+ # ⛔⛔ THE MATERIALISED TABLE IS GIVEN THE WINDOW'S OWN NAME, AND WITHOUT THIS THE MEMO ABOVE
249
+ # SERVES ONE WINDOW'S ROWS UNDER ANOTHER WINDOW'S ANSWER (found by W53-T14, live).
250
+ # `odoo_relational.registry_grid_spec` names its temp table `_registry_grid_<table_key>` and
251
+ # `CREATE OR REPLACE`s it, so the name carries the DATABASE and not the PERIOD, while
252
+ # `_mirror`'s memo is keyed by `(table_key, window)`. Resolve one customer_data cell at no
253
+ # period and a second at `{month, 2026-08}` inside ONE request and the second build replaces
254
+ # the first one's table underneath the spec the memo is still holding; a third cell reading
255
+ # the first slot then runs its SQL against August's rows.
256
+ # ⚠ MEASURED, and it is silent: `avg` over `measure_sales_the_last_12_months_6hlkf` answered
257
+ # **138.3942281513749** in a batch that had already resolved that month (508,322.0 / 3,673)
258
+ # and **1710.679825755513** on its own, which is the all-time number the preview door and the
259
+ # grid both give. No refusal, no limits row, a plausible number under the wrong label.
260
+ # ⛔ IT IS FIXED HERE RATHER THAN IN `registry_grid_spec` BECAUSE THAT FILE BELONGS TO ANOTHER
261
+ # LANE THIS WAVE. The copy is one `CREATE TABLE AS SELECT` over rows already in memory, next
262
+ # to an assembly that costs 20 to 130 seconds, so it is not a cost worth conditioning on.
263
+ # ⚠ ALWAYS, INCLUDING THE `None` WINDOW: the unqualified name is REPLACED by every later
264
+ # build, so leaving the no-period case pointing at it is exactly the case measured above.
265
+ slot = hashlib.sha1(
266
+ json.dumps(metric_window, sort_keys=True, default=str).encode("utf-8")).hexdigest()[:12]
267
+ at_window = f'{spec["table"]}__at_{slot}'
268
+ cur.execute(f'CREATE OR REPLACE TEMP TABLE "{at_window}" AS '
269
+ f'SELECT * FROM "{spec["table"]}"')
270
+ spec = {**spec, "table": at_window}
271
+ # ⚠ `fields` HERE IS THE ASSEMBLY'S OWN LIST, NOT THE MIRROR-TYPED COPY. `aggregate_refusal`
272
+ # has to name WHY a column cannot be totalled, and the normalised copy has already thrown that
273
+ # away: a `concatenate` rollup reads as plain `text` there, so the sentence would say "it holds
274
+ # text" instead of "it folds its linked records into text rather than into a number".
275
+ spec = {**spec, "fields": fields, "unbounded": limits, "bounded": bounded}
276
+ return cur, spec, rot._filter_columns(spec, spec_fields)
277
+
278
+
279
+ def _metric_derived(session: Session, table_key: str, g, metric_window):
280
+ """`(derived, bounded_keys, unbounded)` for one assembly at the cell's period.
281
+
282
+ `unbounded` is `{field key: limits row}` and is KEYED rather than listed on purpose: a mirror
283
+ is built once for a database and a cell reads one or two of its columns, so reporting every
284
+ Metric column that failed would bury the one the reader is actually looking at under a list
285
+ about columns their cell never touches. `_resolve_binding` picks the rows for the columns the
286
+ binding names.
287
+
288
+ With no period this is `g["derived"]` exactly as the grid uses it, no metric keys claimed as
289
+ bounded, and nothing to report. With one, every Metric column this account can already see is
290
+ recomputed at that window, ONE COLUMN AT A TIME so a failure can be attributed to the column
291
+ it belongs to rather than reported as "something went wrong".
292
+
293
+ ⚠ THE MEMO IS PER CALL. `core/measure_resolve.py`'s memo key carries a POOL STAMP this function
294
+ does not hold, and inventing one would park an answer under a stamp that never invalidates:
295
+ the cell would keep serving a number from before the last sync. A fresh dict costs one query
296
+ per Metric column and cannot go stale.
297
+ """
298
+ import aios_grid
299
+ from modules import sheet as sheet_mod
300
+
301
+ derived = g.get("derived") or {}
302
+ mfields = aios_grid.measure_fields_of(g.get("fields") or [])
303
+ if not metric_window or not mfields:
304
+ return derived, (), {}
305
+
306
+ # Which Metric columns carry a value at all today: the capability wall's own answer, reused.
307
+ seen = set()
308
+ for cells in derived.values():
309
+ seen.update(cells or ())
310
+ live = [f for f in mfields if f.get("key") in seen]
311
+
312
+ out = {pid: dict(cells or {}) for pid, cells in derived.items()}
313
+ for f in mfields: # every Metric column starts blank at a new window
314
+ for cells in out.values():
315
+ cells.pop(f.get("key"), None)
316
+
317
+ bounded, unbounded = [], {}
318
+ for f in live:
319
+ key = f.get("key")
320
+ label = str(f.get("label") or key)
321
+ rewritten = dict(f, measure=dict(f.get("measure") or {}, window=metric_window))
322
+ try:
323
+ cells = _measure_cells_at(session, table_key, g, rewritten)
324
+ except Exception: # noqa: BLE001
325
+ cells = {}
326
+ got = False
327
+ for pid, values in (cells or {}).items():
328
+ if key in values:
329
+ out.setdefault(pid, {})[key] = values[key]
330
+ got = True
331
+ if got:
332
+ bounded.append(key)
333
+ else:
334
+ unbounded[key] = sheet_mod.metric_window_limit(
335
+ label,
336
+ "this column's metric could not be measured over the period this cell names, so "
337
+ "it was left blank rather than answered over its own wider window")
338
+ for f in mfields:
339
+ if f.get("key") not in seen:
340
+ # ⚠ THE CAUSE NAMES BOTH POSSIBILITIES because this door cannot tell them apart, and
341
+ # a sentence that picks one would be confidently wrong half the time. A column with no
342
+ # value anywhere in `derived` is either one the metrics capability withholds from this
343
+ # account or one whose own declared window already failed to resolve.
344
+ unbounded[f.get("key")] = sheet_mod.metric_window_limit(
345
+ str(f.get("label") or f.get("key")),
346
+ "this column has no value on this database for this account, either because the "
347
+ "metric behind it is not shared with you or because it could not be measured at "
348
+ "all, so there was nothing to bound to the period")
349
+ return out, tuple(bounded), unbounded
350
+
351
+
352
+ def _measure_cells_at(session: Session, table_key: str, g, field):
353
+ """`{pid: {field key: value}}` for ONE rewritten Metric column, through its grain's evaluator.
354
+
355
+ ⛔ TWO GRAINS, TWO EVALUATORS, AND NEITHER IS RE-IMPLEMENTED HERE. `core/measure_resolve.py`
356
+ is CUSTOMER grain (it resolves through `harness/measure_filter.py`, whose entity is the
357
+ partner); the product grain goes through `semantic.entity_measure_values`, which is what
358
+ `routes_products._measure_cells` wraps and which joins by SKU CODE rather than by pid. Calling
359
+ the wrong one would answer a column of blanks on one of the two grids.
360
+ """
361
+ if table_key == "product_data":
362
+ import routes_products as rp
363
+ return rp._measure_cells([field], g.get("rows_src") or [], g.get("team_id"),
364
+ g.get("today"), "sheet-period", {},
365
+ rp.product_measures(session))
366
+ from core import measure_resolve
367
+ return measure_resolve.column_values([field], g.get("team_id"), g.get("pids") or frozenset(),
368
+ g.get("today"), "sheet-period", {})
369
+
370
+
371
+ def _offered_view(session: Session, database: str, view_id: str):
372
+ """The view THIS database's own workspace assembly offers under `view_id`, or None.
373
+
374
+ ⛔⛔ WAVE 53 FOLLOW-UP TO W53-T12 — `find_view` ALONE CANNOT SEE A PINNED VIEW NOBODY HAS
375
+ TOUCHED, AND THE BINDING EDITOR OFFERS EXACTLY THOSE. `all-customers` is pinned PER USER
376
+ (`core/grid_events.py:1652`: `_pinned_per_user = (_kind == 'system' or view_id in
377
+ ('all-customers', _ag_overview_id()))`), so every user of a table gets their own copy of that
378
+ id, but only once they have touched it — an autosave, a column resize. An account that never
379
+ customised it has NO stored record, `find_view` answers None, and this door then refused, by
380
+ name, a view the `/workspace` door had just offered the same session. Measured on the running
381
+ app as `admin@royal-imports`: `/workspace?scope=customer` served exactly one view,
382
+ `all-customers`, and a cell bound to it answered `409 view_missing: View All customers no
383
+ longer exists.` That sentence is the owner's report of D-662's sibling, word for word.
384
+
385
+ ⭐⭐ SO THE FALLBACK BUILDS THE SAME ASSEMBLY THE `/workspace` DOOR BUILDS AND PICKS THE VIEW
386
+ OUT OF IT. The mechanism is copied from `routes_alerts.py::_require_filtered_view`, including
387
+ its `_view_by_id` — IMPORTED rather than re-written, because two hand-rolled "find the view in
388
+ an assembly" walks is exactly the shape that let `g["views"] IS A LIST` raise on every call for
389
+ thirteen waves ([[one-question-two-normalizers]]).
390
+
391
+ ⚠ `consume_corrections=False` IS NOT OPTIONAL (`routes_alerts.py:498`). Those one-shot
392
+ field-name correction acks belong to the `/workspace` refresh that exists to show them to the
393
+ person who made the edit; a bound cell resolving its scope must not eat them.
394
+
395
+ ⚠ `with_rows=False` on the `ut_` leg for the reason W31-T20 built the flag: only `g["views"]`
396
+ is read here, and building the table would make a read-through grain refuse
397
+ `409 window_required` over rows nobody asked for.
398
+
399
+ ⛔ AN UNEXPECTED FAILURE ANSWERS None RATHER THAN ESCAPING. This function only ever runs after
400
+ `find_view` has already missed, so the cell was on its way to a refusal either way; letting a
401
+ raw exception out would turn one cell's bad luck into a 500 for the whole workbook refresh.
402
+ A refusal that already NAMES ITS OWN CAUSE (`HTTPException`) is let through instead, because
403
+ "the store is not ready" is a truer answer than "that view no longer exists".
404
+ """
405
+ key = str(database or "")
406
+ try:
407
+ if key.startswith("ut_"):
408
+ from routes_tables import ut_assembly
409
+ g = ut_assembly(session, key,
410
+ storage_key=f"{session.tenant}:{key}:{session.uname}",
411
+ consume_corrections=False, with_rows=False)
412
+ elif key == "product_data":
413
+ from routes_products import product_assembly
414
+ g = product_assembly(session, scope="product", consume_corrections=False)
415
+ elif key == "customer_data":
416
+ from routes_customers import grid_assembly
417
+ g = grid_assembly(session, scope="customer", consume_corrections=False)
418
+ else:
419
+ return None
420
+ except HTTPException:
421
+ raise
422
+ except Exception: # noqa: BLE001
423
+ return None
424
+ from routes_alerts import _view_by_id
425
+ return _view_by_id(g, view_id)
426
+
427
+
428
+ def _view_filter(session: Session, database: str, view_id: str, view_name: str = "",
429
+ memo=None):
430
  """`(nodes, conj)` for a saved view's filter, or a `view_missing` refusal that NAMES it.
431
 
432
+ ⭐⭐ TWO LOOKUPS, CHEAPEST FIRST, AND THE ORDER IS THE CONTRACT (wave 53, follow-up to
433
+ W53-T12). `find_view` answers from the caller's OWN stored record and is authoritative when it
434
+ hits, trashed record included (R11). Only on a MISS does `_offered_view` rebuild the workspace
435
+ assembly, which is what resolves a pinned view this account has never customised. A miss in
436
+ BOTH still refuses by name: an id nobody can resolve must never quietly mean "every row", which
437
+ would serve a whole database under a scope nobody wrote.
438
+
439
+ ⚠ `memo` is a PER-REQUEST dict, keyed `(database, view_id)`, and it exists because the two
440
+ per-cell loops in this file resolve a binding CELL BY CELL. `refresh_sheet`'s own docstring
441
+ claimed "each distinct `view_id` is resolved ONCE" and the code never did that: `seen_db`
442
+ deduplicates the DATABASE WALL only, and the resolve underneath it ran per cell. That was
443
+ survivable while the whole lookup was one `find_view`; with an assembly behind the fallback,
444
+ forty cells on one view would rebuild it forty times. The memo caches the REFUSAL too, so a
445
+ workbook full of cells on one deleted view costs one lookup rather than forty.
446
+
447
  ⛔⛔ `prefer_owner=session.uname` IS LOAD-BEARING AND OMITTING IT IS A SILENT CROSS-USER READ.
448
  The system view id `all-customers` is pinned on every database, and every user who has ever
449
  touched that view's config holds their OWN record under the same id, so a bare first-hit scan
 
455
  ⚠ The refusal names the view, which is why `clean_binding` keeps `view_name` on the binding:
456
  once the record is deleted there is nothing left to look a name up from.
457
  """
458
+ slot = (str(database or ""), str(view_id or ""))
459
+ if memo is not None and slot in memo:
460
+ cached = memo[slot]
461
+ if isinstance(cached, Exception):
462
+ raise cached
463
+ return cached
464
+ try:
465
+ out = _view_filter_once(session, database, view_id, view_name)
466
+ except HTTPException as exc:
467
+ if memo is not None:
468
+ memo[slot] = exc
469
+ raise
470
+ if memo is not None:
471
+ memo[slot] = out
472
+ return out
473
+
474
+
475
+ def _view_filter_once(session: Session, database: str, view_id: str, view_name: str = ""):
476
+ """`_view_filter` without the memo. Read that docstring first; this is only its body."""
477
+ from core import table_store, view_templates
478
+ # ⛔⛔ THE BUCKET IS `<key>_table_workspace`, AND THIS DOOR WAS ASKING FOR THE BARE KEY (wave
479
+ # 53, follow-up to W53-T12). `view_templates.workspace_key` is the ONE normaliser between a
480
+ # database key and the store bucket its saved views live in — `customer_data` lives in
481
+ # `customer_table_workspace`, `product_data` in `product_table_workspace`, a `ut_` table in
482
+ # `<key>_table_workspace` — and every other reader in the app already goes through it or
483
+ # spells the suffix out (`routes_starred`, `routes_tables`, `routes_shares`, `routes_grid`,
484
+ # `routes_automation`). `TableStore("customer_data")` reads a bucket nothing writes, so this
485
+ # lookup could not hit for ANY database: `prefer_owner` and `include_trashed` below were both
486
+ # unreachable, and R11's promise that a trashed view keeps a cell working for 30 days was
487
+ # dead code. Fixing the key is what makes the cheap leg able to answer at all.
488
+ # ⚠ `workspace_key` answers None for a key that is not a table; the bare key is kept in that
489
+ # case so nothing that used to resolve stops resolving.
490
  # ⚠ `TableStore(table_key, st=...)`, in that order. `st` is the STORE HANDLE, and passing the
491
  # session's runtime is what makes the lookup read THIS tenant's bucket rather than tenant #0's.
492
+ store = table_store.TableStore(view_templates.workspace_key(database) or str(database or ""),
493
+ st=session.runtime)
494
  # ⭐⭐ `include_trashed=True` IS R11, AND IT IS ONE KEYWORD BECAUSE THE DEFAULT MUST NOT MOVE
495
  # (wave 51, W51-T26). A deleted view is MOVED into `<owner>.trash`, so the bare scan answered
496
  # None and this door refused a cell whose view somebody deleted an hour ago and can still
 
501
  # permission-adjacent (shares, starred, publish, forms); widening there would open doors no
502
  # ticket asked about, with every gate green.
503
  found = store.find_view(view_id, prefer_owner=session.uname, include_trashed=True)
504
+ view = found[1] if found else None
505
+ if view is None:
506
+ # ⭐⭐ THE SECOND LOOKUP, AND IT RUNS ONLY ON A MISS. See `_offered_view`: a pinned view
507
+ # this account has never touched has no stored record anywhere, so the workspace assembly
508
+ # is the only place it exists. A miss HERE too is a genuinely gone view and still refuses
509
+ # by name.
510
+ view = _offered_view(session, database, view_id)
511
+ if view is None:
512
  raise err(409, "view_missing", f"View {view_name or view_id} no longer exists.")
 
513
  import routes_odoo_tables as rot
514
+ # ⛔⛔ D-662 — THE FILTER TREE LIVES AT `config.filters`, NOT AT THE RECORD'S TOP LEVEL.
515
+ # Reading `view["filters"]` answered None on every stored view, and `tree_parts(None)` is
516
+ # `([], "and")` — a legal EMPTY filter, so EVERY view-scoped cell resolved with no filter at
517
+ # all and reported the whole database, with nothing anywhere going red.
518
+ #
519
+ # ⭐⭐ AND THE READER IS `core.sheets.adopted_scope_filter`, NOT A FOURTH HAND-ROLLED WALK.
520
+ # That function is this repo's canonical answer to "which rows does this view mean": its own
521
+ # docstring names THIS door as the one that got it wrong, and it already carries the three
522
+ # shapes a stored record comes in — `config.filters` as a `{conj, nodes}` tree, `config.filters`
523
+ # as a BARE LIST whose conjunction lives beside it in `config.filterConj` (a bare-list read
524
+ # through `tree_parts` alone would silently answer `and` for an OR view), and a LOCKED view,
525
+ # which is a curated ROW SET and adopts its COHORT leaf rather than the incidental filters its
526
+ # config happens to hold (`DESIGN.md` section 4, the three locks). The cohort leaf does not
527
+ # compile on the Sheet path and refuses by name, which is the honest answer: a locked view's
528
+ # membership is not a predicate, and inventing one here would put a plausible wrong number on
529
+ # a screen. It deep-copies, so nothing here can mutate the stored view.
530
+ from core import sheets as sheets_mod
531
+ return rot._fe().tree_parts(sheets_mod.adopted_scope_filter(view))
532
 
533
 
534
  #: ⛔ THE TWO CAP CODES ANSWER 413, NOT 400 (contract C3). A 400 says the request was malformed and
 
760
  fresh = _copy.deepcopy(book)
761
  stamp = _now_iso()
762
  seen_db = {}
763
+ # ⭐ The same per-request memo as `refresh_sheet`, for the same reason and with the same
764
+ # lifetime: this loop resolves cell by cell too, and a reader's GET must not rebuild one
765
+ # database's workspace assembly once per bound cell.
766
+ view_memo = {}
767
  touched = 0
768
  store = _store(session)
769
  wid = book.get("id") or ""
 
811
  continue
812
 
813
  try:
814
+ out = _resolve_binding(session, binding, view_memo=view_memo)
815
  except HTTPException as exc:
816
  detail = getattr(exc, "detail", None) or {}
817
  info = detail.get("error") if isinstance(detail, dict) else None
 
1471
  forty cells to one database asks once; a reader who has lost access to that database gets a
1472
  refusal on every one of its cells rather than a stale number quietly repainting.
1473
 
1474
+ ⚠ Each distinct `view_id` is resolved ONCE, and as of the wave-53 follow-up to W53-T12 that
1475
+ sentence is finally TRUE OF THE CODE. It was written of `seen_db`, which deduplicates the
1476
+ DATABASE WALL and nothing else: the resolve underneath it ran per cell, so a forty-cell
1477
+ workbook did forty `table_store.find_view` calls and forty legacy migrations with them.
1478
+ `view_memo` below is the dedupe this sentence describes.
1479
 
1480
  ⛔⛔ C5 — THIS IS A WRITE DOOR, BECAUSE IT ENDS IN `put_workbook`, AND A VIEWER IS REFUSED
1481
  HERE FOR A REASON THAT IS NOT ABOUT PERMISSION TO SEE. A viewer whose refresh were allowed
 
1497
 
1498
  stamp = _now_iso()
1499
  seen_db = {}
1500
+ # ⭐ ONE MEMO FOR THE WHOLE REFRESH, keyed `(database, view_id)`. `seen_db` deduplicates the
1501
+ # WALL and never the scope, so forty cells on one saved view used to resolve that view forty
1502
+ # times. See `_view_filter`: the second lookup behind it builds a workspace assembly, which is
1503
+ # work no workbook should pay for per cell. Per REQUEST, never on the runtime: a view's filter
1504
+ # may be edited between two refreshes and a longer lived cache would serve the old rows.
1505
+ view_memo = {}
1506
  for tab in book.get("sheets") or ():
1507
  for addr, cell in (tab.get("cells") or {}).items():
1508
  if not isinstance(cell, dict) or cell.get("kind") != "bound":
 
1523
  "message": f"You cannot read {db}."}
1524
  continue
1525
  try:
1526
+ out = _resolve_binding(session, binding, view_memo=view_memo)
1527
  except HTTPException as exc:
1528
  detail = getattr(exc, "detail", None) or {}
1529
  info = detail.get("error") if isinstance(detail, dict) else None
 
1698
  }.get(code, "This formula could not be calculated.")
1699
 
1700
 
1701
+ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=None):
1702
  """Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
1703
 
1704
  The order below is the contract, not a preference:
 
1706
  2. the mirror cursor, whose two failures mean opposite things;
1707
  3. the ROW wall, fail-closed, refusing 409 when it names a column the mirror cannot answer;
1708
  4. the binding's own scope, whose unanswerable columns are REPORTED rather than dropped.
1709
+
1710
+ ⭐⭐ W53-T13 / R7 — THE PERIOD IS RESOLVED BEFORE THE MIRROR IS OPENED, because it decides what
1711
+ the Metric columns of that mirror MEAN. `modules/sheet.py::period_window` turns the cell's
1712
+ `{unit, start}` into the custom window `harness/windows.py` speaks, and `_registry_mirror`
1713
+ re-resolves every Metric column at it. A period that bounds nothing is reported rather than
1714
+ left silent: see `period_limits`.
1715
  """
1716
  from modules import sheet as sheet_mod
1717
  import core.perm_scope as perm_scope
 
1721
  except sheet_mod.SheetRefusal as exc:
1722
  raise err(400, exc.code, exc.message)
1723
 
1724
+ # ⛔ C2's OTHER AGGREGATE ARM IS ANSWERED HERE, NOT LEFT TO FALL THROUGH TO `aggregate_sql`,
1725
+ # where it died as `field_unknown` with an empty subject. See `metric_key_refusal`.
1726
+ metric_refusal = sheet_mod.metric_key_refusal(binding["aggregate"])
1727
+ if metric_refusal is not None:
1728
+ raise err(400, metric_refusal.code, metric_refusal.message)
1729
+
1730
  database = _require_database(session, binding["database"])
1731
+ window = sheet_mod.period_window(binding.get("period"))
1732
+ cur, spec, cols = _mirror(session)(database, metric_window=window)
1733
+
1734
+ # ⛔ THE COLUMN IS CHECKED BEFORE THE SQL IS BUILT (W53-T13). Now that every tenant column is a
1735
+ # real column of the materialised table, a `sum` over a text column reaches DuckDB as a binder
1736
+ # error and a `sum` over a browser-computed formula column reaches it as a confident 0.
1737
+ bound_field = next((f for f in (spec.get("fields") or [])
1738
+ if isinstance(f, dict)
1739
+ and f.get("key") == (binding["aggregate"].get("field") or None)), None)
1740
+ agg_refusal = sheet_mod.aggregate_refusal(binding["aggregate"], bound_field)
1741
+ if agg_refusal is not None:
1742
+ raise err(409, agg_refusal.code, agg_refusal.message)
1743
 
1744
  # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
1745
  wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
 
1762
  scope = binding["scope"]
1763
  if scope.get("view_id"):
1764
  scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"],
1765
+ scope.get("view_name", ""), memo=view_memo)
1766
  else:
1767
  scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
1768
 
 
1795
 
1796
  row = cur.execute(sql, params).fetchone()
1797
  value = row[0] if row else None
1798
+ # ⭐⭐ EVERY WAY THIS ANSWER CAME OUT WIDER THAN THE BINDING ASKED FOR TRAVELS WITH IT
1799
+ # (standing rule 1's second sentence). Three sources, one list: a filter leaf the compiler
1800
+ # could not push down (`build_aggregate_query`), a Metric column that could not be measured at
1801
+ # the cell's period (`_metric_derived`), and a period that bounds nothing at all because the
1802
+ # bound column is stored per record rather than measured over time (`period_limits`).
1803
+ # ⚠ ONLY THE COLUMNS THIS BINDING DEPENDS ON. See `_metric_derived`: the mirror knows about
1804
+ # every Metric column on the database and a cell reads one or two of them, so the aggregate's
1805
+ # own column plus every column its filter names is the honest set.
1806
+ depends = set(sheet_mod.filter_columns_named(scope_nodes))
1807
+ if binding["aggregate"].get("field"):
1808
+ depends.add(str(binding["aggregate"]["field"]))
1809
+ limits = (list(limits)
1810
+ + [row for key, row in (spec.get("unbounded") or {}).items() if key in depends]
1811
+ + sheet_mod.period_limits(binding.get("period"), binding["aggregate"], bound_field,
1812
+ spec.get("bounded") or (), depends))
1813
  return {"value": value, "limits": limits, "database": database, "binding": binding}
1814
 
1815
 
 
1876
  raise err(400, exc.code, exc.message)
1877
 
1878
  database = _require_database(session, binding["database"])
1879
+ # ⚠ THE SAME PERIOD THE NUMBER WAS COMPUTED AT (W53-T13). The drill probes `COUNT(*)` and never
1880
+ # reads the bound column, but its FILTER may name a Metric column, and a mirror opened at a
1881
+ # different window would answer that condition against different values. The popup would then
1882
+ # list rows the cell's own number never counted.
1883
+ cur, spec, cols = _mirror(session)(
1884
+ database, metric_window=sheet_mod.period_window(binding.get("period")))
1885
 
1886
  wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
1887
  if perm_scope.row_scope_applies(session.user, database) else None)
 
1911
  else:
1912
  out["filter"] = scope.get("filter")
1913
  return out
1914
+
1915
+
1916
+ def _resolve_home_tab(book, tabs, names, ref):
1917
+ """The tab an UNQUALIFIED address in a `resolve-bindings` request belongs to.
1918
+
1919
+ ⚠ `ref` MAY BE A TAB `id` OR ITS NAME, exactly as `GET /sheets/{id}/tabs/{tab}` accepts both,
1920
+ and a ref this workbook does not carry is a NAMED 404 rather than an empty answer. The flat
1921
+ `{addr: value}` body of contract C1 has no room to say "that tab is gone", so the only place
1922
+ that sentence can be told is the status line, and an answer of `{}` would read to the client
1923
+ as "none of those cells are bound" - a different problem with a different fix.
1924
+
1925
+ ⚠ NO `tab` AT ALL MEANS THE FIRST TAB, which is what `_tab_scope_names` already makes an
1926
+ unqualified reference mean everywhere else in this file.
1927
+ """
1928
+ from core import sheets
1929
+ ref = str(ref or "").strip()
1930
+ if not ref:
1931
+ return names[0] if names else ""
1932
+ try:
1933
+ found = sheets.find_tab(book, ref)
1934
+ except sheets.SheetRefusal as exc:
1935
+ raise _refuse(exc)
1936
+ for tab, name in zip(tabs, names):
1937
+ if tab is found:
1938
+ return name
1939
+ return names[0] if names else ""
1940
+
1941
+
1942
+ def _asked_key(asked, home, fr):
1943
+ """One requested address, as the `TAB!ADDR` key the whole-workbook pass already uses.
1944
+
1945
+ ⭐ A QUALIFIED REFERENCE KEEPS ITS OWN TAB and an unqualified one lands on `home`, which is
1946
+ the same rule `_recompute_formulas` gives a formula's own references. `'Sales data'!B4` is the
1947
+ quoted spelling a name with a space wears inside a formula, so the quotes are stripped here
1948
+ rather than making that cell unaddressable through this door.
1949
+ """
1950
+ text = str(asked or "").strip()
1951
+ if "!" not in text:
1952
+ return fr.a1_key(text, home)
1953
+ sheet, _, addr = text.rpartition("!")
1954
+ sheet = sheet.strip()
1955
+ if len(sheet) >= 2 and sheet[0] == "'" and sheet[-1] == "'":
1956
+ sheet = sheet[1:-1].replace("''", "'")
1957
+ return fr.a1_key(addr, sheet or home)
1958
+
1959
+
1960
+ @router.post("/sheets/{workbook_id}/resolve-bindings")
1961
+ def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
1962
+ session: Session = Depends(require_session)):
1963
+ """`{addr: value}` for the NAMED bound cells only (contract C1, ruling R2).
1964
+
1965
+ ⭐⭐ THIS IS THE DOOR THE COMMIT PATH USES, AND ITS WHOLE POINT IS THAT IT IS SMALL.
1966
+ Under R2 a formula evaluates in the browser the instant it is committed, so the only thing the
1967
+ client still needs the server for is the handful of DATABASE-BOUND cells that formula leans
1968
+ on. `POST /sheets/{id}/refresh` keeps recomputing the WHOLE workbook and is untouched: load
1969
+ and import still need it, and lane A still calls it for those two paths. What moved off the
1970
+ commit path is the loop, not the door.
1971
+
1972
+ request: `{"cells": ["B4", "'Sales data'!C9", ...], "tab": "<tab id or name>"}`
1973
+ `tab` is the tab an unqualified address belongs to and defaults to the first tab.
1974
+
1975
+ response: `{"B4": 6283327.0, "Sales data!C9": null}` - the flat map contract C1 names, keyed
1976
+ by THE EXACT STRING THE CALLER ASKED WITH, so a client looks its answer up under the
1977
+ reference it already holds and never has to re-derive this file's key spelling.
1978
+
1979
+ ⛔⛔ A KEY IS ABSENT WHEN NO BOUND CELL LIVES AT THAT ADDRESS, AND THAT IS THE ONE
1980
+ DISTINCTION THE SHAPE CAN CARRY. An address that is empty, holds a typed literal or holds a
1981
+ formula is not this door's business - lane A's evaluator already has those values in hand -
1982
+ so asking for one costs nothing and answers nothing.
1983
+
1984
+ ⛔⛔ AND HERE IS WHAT THE SHAPE CANNOT CARRY, STATED RATHER THAN HIDDEN: a bound cell whose
1985
+ binding was REFUSED just now (a database wall, a row wall, a scope condition this database
1986
+ cannot compile) comes back as `null`, which is the same thing an aggregate over zero matching
1987
+ rows returns. The cause is real and this door knows it; `{addr: value}` has nowhere to put it.
1988
+ `POST /sheets/{id}/refresh` and `GET /sheets/{id}` both still carry the full
1989
+ `{code, message}` refusal on the cell, so nothing is lost from the document - what is lost is
1990
+ the client's ability to paint THIS cell's refusal at commit time. Raised as a dated PRD
1991
+ amendment rather than fixed by widening the shape on one lane's authority, because lane A is
1992
+ the consumer and a second shape agreed by nobody is worse than a known gap.
1993
+
1994
+ ⛔ ONE BAD CELL NEVER FAILS THE BATCH, exactly as in `refresh_sheet`'s bound-cell loop: a
1995
+ refusal is caught per cell and the siblings still answer.
1996
+
1997
+ ⭐⭐ THE BATCH PAYS FOR ITS ASSEMBLY ONCE, WHICH IS MOST OF THE REASON THIS DOOR TAKES A LIST
1998
+ AT ALL. A bound cell on a compiled registry grid (`customer_data`, `product_data`) costs a
1999
+ full workspace assembly - measured at 20 to 130 seconds on this box after W53-T13 - so N cells
2000
+ resolved one request each would cost N of them. Two memos make one request pay once:
2001
+ - `session._sheet_mirrors`, keyed `(table_key, metric_window)` inside `_mirror`, so every
2002
+ cell on one database at one period shares one assembly and one temp table. It hangs off
2003
+ the Session, which `require_session` builds fresh per request and drops with it.
2004
+ - `view_memo`, keyed by `view_id`, so a saved-view scope is looked up once for the batch.
2005
+ ⚠ AND IDENTICAL BINDINGS RESOLVE ONCE. Two cells carrying the same database, aggregate, scope
2006
+ and period cannot disagree inside one request, so the second one reads the first one's answer
2007
+ rather than running the same SQL again. Per REQUEST only, for the same reason `view_memo` is:
2008
+ a saved view's filter may be edited between two calls.
2009
+
2010
+ ⛔ A READ DOOR, LIKE `preview_cell` AND `drill_cell`, NOT A WRITE ONE LIKE `refresh_sheet`.
2011
+ It calls neither `_require_editor` nor `put_workbook`, so C5's hazard - a viewer's narrower
2012
+ numbers being SAVED into the owner's document - cannot arise here: nothing this door computes
2013
+ is ever stored. The per-database wall still runs on every cell, inside `_resolve_binding`.
2014
+
2015
+ ⚠ NO CAP ON HOW MANY CELLS MAY BE ASKED FOR (standing rule 1). The client asks for the cells
2016
+ one commit actually touched; the memos above are what keep a large batch from multiplying
2017
+ database work, and a batch's cost is dominated by the number of distinct (database, period)
2018
+ pairs in it rather than by the number of cells.
2019
+ """
2020
+ from core import sheets
2021
+ import formula_runtime as fr
2022
+
2023
+ try:
2024
+ book = sheets.get_workbook(_store(session), workbook_id)
2025
+ except sheets.SheetRefusal as exc:
2026
+ raise _refuse(exc)
2027
+
2028
+ payload = dict(body or {})
2029
+ tabs = [t for t in (book.get("sheets") or ()) if isinstance(t, dict)]
2030
+ names = _tab_scope_names(tabs)
2031
+ home = _resolve_home_tab(book, tabs, names, payload.get("tab"))
2032
+
2033
+ bound = {}
2034
+ for tab, name in zip(tabs, names):
2035
+ for addr, cell in (tab.get("cells") or {}).items():
2036
+ if isinstance(cell, dict) and cell.get("kind") == "bound":
2037
+ bound[fr.a1_key(addr, name)] = cell
2038
+
2039
+ view_memo = {}
2040
+ by_binding = {}
2041
+ answer = {}
2042
+ for asked in (payload.get("cells") or ()):
2043
+ label = str(asked or "")
2044
+ if not label:
2045
+ continue
2046
+ cell = bound.get(_asked_key(label, home, fr))
2047
+ if cell is None:
2048
+ continue
2049
+ binding = cell.get("binding") or {}
2050
+ slot = json.dumps(binding, sort_keys=True, default=str)
2051
+ if slot not in by_binding:
2052
+ try:
2053
+ by_binding[slot] = _resolve_binding(session, binding,
2054
+ view_memo=view_memo)["value"]
2055
+ except HTTPException:
2056
+ # ⛔ SWALLOWED HERE AND NOWHERE ELSE. See the docstring: the flat body has no
2057
+ # room for a cause, and failing the whole batch on one walled cell would take
2058
+ # every sibling's number down with it. The same refusal still travels in full on
2059
+ # the refresh and read doors, which is where the cell's own sentence comes from.
2060
+ by_binding[slot] = None
2061
+ answer[label] = by_binding[slot]
2062
+ return answer
platform/core/connector_directory.py CHANGED
@@ -307,6 +307,12 @@ MONID_ACTION_STATE = "available"
307
  #: state with the neutral tone by construction (the wave-9 law: no client union over a server
308
  #: vocabulary), so the client renders it without a change. Any gate holding a HAND-TYPED copy of
309
  #: the five-word set has to learn the sixth.
 
 
 
 
 
 
310
  CATALOGUE_STATE = "catalogue"
311
 
312
  #: ⭐⭐ W49-T14 · RULINGS R21 + R24 — WHICH CONNECTORS HAVE A FIELD CATALOGUE, AUTHORED IN CODE.
 
307
  #: state with the neutral tone by construction (the wave-9 law: no client union over a server
308
  #: vocabulary), so the client renders it without a change. Any gate holding a HAND-TYPED copy of
309
  #: the five-word set has to learn the sixth.
310
+ #:
311
+ #: ⚠ W53-T31 (R11) — TELEGRAM IS ONE OF THE 117, AND IT STAYS ONE. `MONID_PROVIDERS` carries
312
+ #: `("Telegram", 7, ...)`: a vendor listing, not a connector we have built or planned. Wave 53
313
+ #: adopted only its CREDENTIAL SHAPE on paper and built no runtime path, so the row keeps this
314
+ #: word and Telegram is deliberately absent from `routes_connectors.PLANNED`. The build plan,
315
+ #: with the two keychain steps it needs first, is `.claude/wiki/research/ideation/telegram-bot.md`.
316
  CATALOGUE_STATE = "catalogue"
317
 
318
  #: ⭐⭐ W49-T14 · RULINGS R21 + R24 — WHICH CONNECTORS HAVE A FIELD CATALOGUE, AUTHORED IN CODE.
platform/core/connector_spec.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """connector_spec.py — ONE shared schema spec for every connector's tables, carrying the vendor's
2
+ own name for each of them.
3
+
4
+ ⭐⭐ **THIS FILE IS THE SINGLE SOURCE OF TRUTH FOR A CONNECTOR'S TABLE SHAPE FROM NOW ON.** The
5
+ shape already existed twice before it had a name: `aios-web/api/amazon_relational.py` and
6
+ `aios-web/api/meta_relational.py` each carry loose `SOURCE` / `LABELS` / `PINNED` / `IDENTITY` /
7
+ `LINKS` module dicts saying the same six things about their tables in two different spellings, and
8
+ `odoo_relational.py` carries a third. Nobody called it a spec, so nothing could read it generically
9
+ and every new consumer (the relation engine, the connector detail door, the Databases tab) had to
10
+ learn each connector's dialect. This module generalises those dicts; it does not invent a new model.
11
+
12
+ ConnectorTableSpec one table: key, native, source, label, pinned, identity, links
13
+ register(connector, ...) add a connector's tables to the registry
14
+ tables_for(connector) that connector's specs, in declaration order
15
+ spec_for(ut_key) one table's spec, or None
16
+ connector_of(ut_key) which connector owns a ut_* key, or None
17
+ all_specs() flat ut_key -> spec across every connector
18
+ connectors() the connector keys, in registration order
19
+ edges_for(key) the relation edges of a CONNECTOR or of ONE table
20
+
21
+ ⭐ **THE FIFTH KEY IS `native`, AND IT IS THE ONE THAT DID NOT EXIST BEFORE.** `SOURCE` is the
22
+ MIRROR table — `amzn_orders`, `meta_campaigns` — which is OUR name for the copy we hold. The
23
+ vendor's own identifier for the same thing (`GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL`,
24
+ `AdAccount`, `res.partner`) lived only in comments, so no screen and no gate could reach it.
25
+
26
+ ⛔⛔ **R9 — `label` IS A DEFAULT, `native` IS NEVER EDITABLE.** The `label` here is our SHIPPED
27
+ default display name and nothing else. A tenant's override lives in `core/schema_overlay.py`, is
28
+ stored per tenant, and **a connector re-sync must never write it**; renaming a database from the
29
+ navigation rail is that same override. Nothing in this module is a place to store an override, and
30
+ a caller that writes one here has put tenant state in shipped code.
31
+
32
+ ⛔ **LAYERING: `core` NEVER IMPORTS UP.** `aios-web/api/*` is above `platform/core/`, so this file
33
+ must not import `amazon_relational`, `meta_relational` or `odoo_relational`, and it does not import
34
+ `harness` either. Every value below is therefore written out LITERALLY, transcribed from the modules
35
+ named beside it.
36
+
37
+ ⭐ **THE TRANSCRIPTION IS HELD TRUE BY A GATE, NOT BY A COMMENT.** `aios-web/api/verify_meta.py`
38
+ (`section_connector_spec`) asserts, per table, that this module's `source` / `label` / `pinned` /
39
+ `identity` / `links` agree exactly with the live `amazon_relational` and `meta_relational` dicts.
40
+ That gate lives up in the api layer precisely because it may import both sides. It is the codebase's
41
+ own idiom: `core/relations.py::compiled_pin_matches_filter_sql` proves two SQL spellings agree by a
42
+ gate rather than by a comment, and `relations.OPEN_INVOICE_WHERE` is held against
43
+ `odoo_relational._AR_WHERE` the same way.
44
+ ⚠ **WHEN W53-T37 LANDS** and `amazon_relational` / `meta_relational` READ their dicts from here,
45
+ those parity checks become tautological and this note should be revisited — but **the checks stay**,
46
+ because a tautology is exactly what catches a hand edit that re-introduces a literal on either side.
47
+
48
+ ⛔ **ODOO IS NOT HERE YET.** W53-T38 writes Odoo's spec in its own file fence. There is deliberately
49
+ no `"odoo"` entry and no stub for one; `edges_for("odoo")` returns `[]` until that ticket lands.
50
+ """
51
+ from dataclasses import dataclass, replace
52
+
53
+ #: ⭐ THE CARDINALITY VOCABULARY, AS A CONSTANT SO EVERY CONSUMER CHECKS MEMBERSHIP RATHER THAN
54
+ #: SPELLING. The relation wire (W53-T17) and the parity gate both read this set; a fifth value
55
+ #: added by hand in a link tuple goes red instead of travelling silently to a screen.
56
+ CARDINALITIES = ("many_to_one", "one_to_many", "one_to_one", "many_to_many")
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class ConnectorTableSpec:
61
+ """One connector table. ⛔ EXACTLY SEVEN FIELDS, IN THIS ORDER — contract C2 says "exactly",
62
+ and `verify_meta.section_connector_spec` reads `dataclasses.fields` to make that word
63
+ mechanical. Grouping by connector is done by the two-level `SPECS` registry below, NOT by an
64
+ eighth field.
65
+ """
66
+ key: str #: our `ut_*` key — the grid a person opens
67
+ native: str #: the vendor's OWN identifier. ⛔ NEVER editable (R9)
68
+ source: str #: the mirror table `harness/*_store.py` writes
69
+ label: str #: our shipped DEFAULT display name. A DEFAULT, never an override (R9)
70
+ pinned: str = None #: the title column, or None when the table has no natural one
71
+ identity: tuple = () #: the id columns, in FALLING preference
72
+ #: ⚠ A TUPLE OF 4-TUPLES `((from_col, target_key, to_col, cardinality), ...)`, AND THE TUPLE IS
73
+ #: DELIBERATE: a `list` default on a frozen dataclass is a mutable shared default and defeats
74
+ #: the freeze. C2's word "LIST" is about `links` being a SEQUENCE per key — several links from
75
+ #: one table, which is Amazon's shape — rather than Meta's single scalar 3-tuple; a tuple
76
+ #: satisfies that. **Do not "fix" this back to a list.** `register()` normalises a caller's
77
+ #: list into a tuple, so passing either is safe and only tuples are ever stored.
78
+ links: tuple = ()
79
+
80
+
81
+ #: ⭐ THE REGISTRY IS TWO-LEVEL: `{connector_key: {ut_key: ConnectorTableSpec}}`. That is what makes
82
+ #: a connector groupable without an eighth dataclass field. Insertion order is declaration order, so
83
+ #: `tables_for` and `edges_for` return a connector's tables in the order its store syncs them.
84
+ SPECS = {}
85
+
86
+
87
+ def _normalise_links(links):
88
+ """A caller's list-of-lists becomes a tuple-of-4-tuples. Explicit, so `links` is ONE type
89
+ everywhere downstream and the gate can assert 4-tuple-ness without a shape apology."""
90
+ return tuple(tuple(entry) for entry in (links or ()))
91
+
92
+
93
+ def register(connector, specs):
94
+ """Add one connector's tables. `specs` may be a mapping of `ut_key -> spec` or any iterable of
95
+ specs; `links` is normalised to tuples on the way in. Re-registering a connector REPLACES it,
96
+ which is what lets a gate's negative control swap the registry and restore it in a `finally`.
97
+ """
98
+ rows = list(specs.values()) if isinstance(specs, dict) else list(specs)
99
+ SPECS[connector] = {s.key: replace(s, links=_normalise_links(s.links)) for s in rows}
100
+ return SPECS[connector]
101
+
102
+
103
+ def connectors():
104
+ """The registered connector keys, in registration order."""
105
+ return tuple(SPECS.keys())
106
+
107
+
108
+ def tables_for(connector):
109
+ """One connector's specs, in declaration order. Unknown connector -> `()`."""
110
+ return tuple(SPECS.get(connector, {}).values())
111
+
112
+
113
+ def all_specs():
114
+ """Flat `ut_key -> spec` across every connector."""
115
+ out = {}
116
+ for tables in SPECS.values():
117
+ out.update(tables)
118
+ return out
119
+
120
+
121
+ def spec_for(ut_key):
122
+ """One table's spec, or None. Never raises."""
123
+ for tables in SPECS.values():
124
+ if ut_key in tables:
125
+ return tables[ut_key]
126
+ return None
127
+
128
+
129
+ def connector_of(ut_key):
130
+ """Which connector owns a `ut_*` key, or None."""
131
+ for connector, tables in SPECS.items():
132
+ if ut_key in tables:
133
+ return connector
134
+ return None
135
+
136
+
137
+ def _label(col):
138
+ """`amazon_order_id` -> `Amazon order id`. ⛔ THE SAME RULE BOTH CONNECTORS ALREADY USE
139
+ (`amazon_relational._label`, `meta_relational._label`), copied because `core` cannot import
140
+ them. The parity gate holds the two spellings together."""
141
+ return col.replace("_", " ").strip().capitalize()
142
+
143
+
144
+ def edges_for(key):
145
+ """The relation edges of a CONNECTOR key (`"amazon"`) or of ONE `ut_*` table key.
146
+
147
+ ⭐ **ONE FUNCTION, TWO NAMESPACES, AND THEY CANNOT COLLIDE:** every table key is `ut_`-prefixed
148
+ and no connector key is, so `edges_for("amazon")` (every edge of the connector, in table
149
+ declaration order) and `edges_for("ut_amzn_order_items")` (just that table's) are never
150
+ ambiguous. W53-T38's `edges_for("odoo")` is the connector form.
151
+
152
+ Each edge is `{"key", "label", "source", "target", "from_col", "to_col", "cardinality"}` where
153
+ `source` is the `ut_*` table the edge starts FROM — needed because the connector form mixes
154
+ tables — and:
155
+ · `key` is `f"{target}_link__{from_col}"`, Amazon's shape. ⛔ THE SOURCE COLUMN IS IN THE
156
+ KEY ON PURPOSE: two links from one table to the same target (orders by id and by sku) would
157
+ otherwise collide on one key and the second would silently overwrite the first. Meta's older
158
+ `f"{target}_link"` cannot express that, which is why Amazon's convention is the shared one.
159
+ · `label` is `f"{target_label} by {_label(from_col)}"`.
160
+
161
+ ⚠ **NEVER RAISES.** An unknown key returns `[]`, and a link whose target is not registered still
162
+ emits its edge, labelled off the raw target key. A lenient reader is what keeps a partially
163
+ ported connector set from blowing up in a caller's hands; the GATE is what asserts that every
164
+ target resolves, and that is the right place for that judgement.
165
+ """
166
+ specs = all_specs()
167
+ if key in SPECS:
168
+ rows = list(SPECS[key].values())
169
+ elif key in specs:
170
+ rows = [specs[key]]
171
+ else:
172
+ return []
173
+ out = []
174
+ for spec in rows:
175
+ for from_col, target, to_col, cardinality in spec.links:
176
+ target_spec = specs.get(target)
177
+ target_label = target_spec.label if target_spec else target
178
+ out.append({
179
+ "key": f"{target}_link__{from_col}",
180
+ "label": f"{target_label} by {_label(from_col)}",
181
+ "source": spec.key,
182
+ "target": target,
183
+ "from_col": from_col,
184
+ "to_col": to_col,
185
+ "cardinality": cardinality,
186
+ })
187
+ return out
188
+
189
+
190
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
191
+ # AMAZON — transcribed from `aios-web/api/amazon_relational.py` + `harness/amazon_client.py`
192
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
193
+ #: ⭐ `native` IS THE SP-API REPORT TYPE, from `harness/amazon_client.py::REPORT_TYPES[t]["report"]`
194
+ #: — the identifier Amazon itself names the data by. ⚠ `orders` and `order_items` share one report
195
+ #: on purpose: the flat-file order report is already one row per order ITEM, so orders is the
196
+ #: deduplicated head and order_items the lines (see `amazon_store.TABLES`). Two of our tables, one
197
+ #: vendor object, which is exactly why `native` and `source` had to be separate keys.
198
+ #: ⚠ `identity` is `amazon_relational.IDENTITY` verbatim: a flat-file report has no `id` column the
199
+ #: way Graph does, so each table names the columns that identify one of its rows, in falling
200
+ #: preference.
201
+ #: ⛔ R12 — AMAZON JOINS ONLY TO AMAZON. Nothing here targets `ut_odoo_*`, `product_data` or the
202
+ #: hand-maintained ASIN mastersheet.
203
+ #: ⚠ EVERY LINK BELOW IS `many_to_one`, and the reason is uniform: each one is a CHILD row naming
204
+ #: its PARENT (a line names its order, a pricing row names its listing). Amazon's `LINKS` carries
205
+ #: 3-tuples today with the cardinality left implicit; this is where it becomes explicit.
206
+ _AMZN = "ut_amzn_"
207
+
208
+ AMAZON_TABLES = (
209
+ ConnectorTableSpec(
210
+ key=_AMZN + "orders",
211
+ native="GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
212
+ source="amzn_orders",
213
+ label="Amazon orders",
214
+ pinned="amazon_order_id",
215
+ identity=("amazon_order_id",),
216
+ links=(
217
+ ("sku", _AMZN + "listings", "seller_sku", "many_to_one"),
218
+ ),
219
+ ),
220
+ ConnectorTableSpec(
221
+ key=_AMZN + "order_items",
222
+ native="GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
223
+ source="amzn_order_items",
224
+ label="Amazon order items",
225
+ pinned="amazon_order_id",
226
+ identity=("order_item_id", "amazon_order_id"),
227
+ links=(
228
+ ("amazon_order_id", _AMZN + "orders", "amazon_order_id", "many_to_one"),
229
+ # ⚠ the order report carries `sku`; listings key on `seller_sku`. Same value, two
230
+ # spellings — the reason a link names BOTH columns rather than one shared name.
231
+ ("sku", _AMZN + "listings", "seller_sku", "many_to_one"),
232
+ ),
233
+ ),
234
+ ConnectorTableSpec(
235
+ key=_AMZN + "listings",
236
+ native="GET_MERCHANT_LISTINGS_ALL_DATA",
237
+ source="amzn_listings",
238
+ label="Amazon listings",
239
+ pinned="seller_sku",
240
+ identity=("seller_sku", "asin1", "asin"),
241
+ links=(), # the product spine's HEAD: everything points at it, it points nowhere
242
+ ),
243
+ ConnectorTableSpec(
244
+ key=_AMZN + "settlements",
245
+ native="GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2",
246
+ source="amzn_settlements",
247
+ label="Amazon settlements",
248
+ pinned="settlement_id",
249
+ identity=("settlement_id",),
250
+ # ⚠ THE MONEY-TO-ORDER BRIDGE — what turns "an order happened" into "this is what we were
251
+ # actually paid for it". The V2 settlement report carries the order id per line.
252
+ links=(
253
+ ("amazon_order_id", _AMZN + "orders", "amazon_order_id", "many_to_one"),
254
+ ("sku", _AMZN + "listings", "seller_sku", "many_to_one"),
255
+ ),
256
+ ),
257
+ ConnectorTableSpec(
258
+ key=_AMZN + "inventory",
259
+ native="GET_LEDGER_SUMMARY_VIEW_DATA",
260
+ source="amzn_inventory",
261
+ label="Amazon inventory",
262
+ pinned="asin",
263
+ identity=("asin", "fnsku", "msku"),
264
+ # ⚠ THE LEDGER KEYS ON `msku`, NOT `sku` — FBA calls the seller's own SKU the MSKU. Same
265
+ # value, a third spelling.
266
+ links=(
267
+ ("msku", _AMZN + "listings", "seller_sku", "many_to_one"),
268
+ ("asin", _AMZN + "listings", "asin1", "many_to_one"),
269
+ ),
270
+ ),
271
+ ConnectorTableSpec(
272
+ key=_AMZN + "pricing",
273
+ native="GET_SALES_AND_TRAFFIC_REPORT",
274
+ source="amzn_pricing",
275
+ label="Amazon pricing and Buy Box",
276
+ pinned="parent_asin",
277
+ identity=("child_asin", "parent_asin"),
278
+ links=(
279
+ ("child_asin", _AMZN + "listings", "asin1", "many_to_one"),
280
+ ("sku", _AMZN + "listings", "seller_sku", "many_to_one"),
281
+ ),
282
+ ),
283
+ ConnectorTableSpec(
284
+ key=_AMZN + "brand_analytics",
285
+ native="GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT",
286
+ source="amzn_brand_analytics",
287
+ label="Amazon brand analytics",
288
+ pinned="search_term",
289
+ identity=("search_term",),
290
+ # ⚠ keyed by SEARCH TERM, not by product, so it joins to nothing by default. Its ASIN
291
+ # columns are the top-clicked ASINs for a term, a different relationship from "this row is
292
+ # about this product", and a link would be misleading.
293
+ links=(),
294
+ ),
295
+ )
296
+
297
+
298
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
299
+ # META ADS — transcribed from `aios-web/api/meta_relational.py`
300
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
301
+ #: ⭐ `native` IS THE GRAPH API NODE NAME — `AdAccount`, `Campaign`, `AdSet`, `Ad`, `AdCreative`,
302
+ #: `AdsInsights`. Meta's own vocabulary for the objects `meta_store` mirrors.
303
+ #: ⛔⛔ **`identity` WAS DECLARED HERE FOR THE FIRST TIME, NOT TRANSCRIBED.** It is honest rather
304
+ #: than invented: `meta_store._read` keys every row on the object's own Graph `id`, so `("id",)` is
305
+ #: what the five object tables are already identified by in practice. `ut_meta_insights` has no
306
+ #: single `id` — the daily insights grain is one row per ad per day — so it takes
307
+ #: `("ad_id", "date_start")`.
308
+ #: ⭐ W53-T37 AMENDMENT, 2026-09-05 — TWO SENTENCES HERE WERE TRUE FOR ONE TICKET AND ARE NOW
309
+ #: FALSE, so they are corrected rather than left to be falsified in one grep.
310
+ #: * *"`meta_relational` has NO `IDENTITY` dict at all"* — it has one now, DERIVED FROM THIS
311
+ #: DECLARATION, so the value is no longer unverifiable against the live module; what is true
312
+ #: instead is that nothing in `meta_relational` READS it yet (`_read` keys rows on the Graph
313
+ #: `id` inline), so it is reachable by name for the caller that will ask.
314
+ #: * *"Meta's `LINKS` is a SCALAR 3-tuple per key today and its generated edge key is
315
+ #: `f"{target}_link"`"* — W53-T37 made it a SEQUENCE keyed by `edges_for`, which is what
316
+ #: retired the collision described below. It is no longer latent, it is fixed.
317
+ #: The sequence-plus-source-column shape is still the reason this file holds links the way it
318
+ #: does: two edges to one target collide on both key and label the moment a scalar spelling
319
+ #: declares them, and Meta was one declaration away from that.
320
+ _META = "ut_meta_"
321
+
322
+ META_TABLES = (
323
+ ConnectorTableSpec(
324
+ key=_META + "ad_accounts",
325
+ native="AdAccount",
326
+ source="meta_ad_accounts",
327
+ label="Meta ad accounts",
328
+ pinned="name",
329
+ identity=("id",),
330
+ links=(), # the hierarchy's HEAD: account -> campaign -> ad set -> ad
331
+ ),
332
+ ConnectorTableSpec(
333
+ key=_META + "campaigns",
334
+ native="Campaign",
335
+ source="meta_campaigns",
336
+ label="Meta campaigns",
337
+ pinned="name",
338
+ identity=("id",),
339
+ links=(
340
+ ("account_id", _META + "ad_accounts", "account_id", "many_to_one"),
341
+ ),
342
+ ),
343
+ ConnectorTableSpec(
344
+ key=_META + "adsets",
345
+ native="AdSet",
346
+ source="meta_adsets",
347
+ label="Meta ad sets",
348
+ pinned="name",
349
+ identity=("id",),
350
+ links=(
351
+ ("campaign_id", _META + "campaigns", "id", "many_to_one"),
352
+ ),
353
+ ),
354
+ ConnectorTableSpec(
355
+ key=_META + "ads",
356
+ native="Ad",
357
+ source="meta_ads",
358
+ label="Meta ads",
359
+ pinned="name",
360
+ identity=("id",),
361
+ links=(
362
+ ("adset_id", _META + "adsets", "id", "many_to_one"),
363
+ ),
364
+ ),
365
+ ConnectorTableSpec(
366
+ key=_META + "creatives",
367
+ native="AdCreative",
368
+ source="meta_creatives",
369
+ label="Meta creatives",
370
+ pinned="name",
371
+ identity=("id",),
372
+ # a creative is referenced BY an ad rather than naming its parent, so it declares no link
373
+ # of its own — the same posture as `ut_amzn_listings`.
374
+ links=(),
375
+ ),
376
+ ConnectorTableSpec(
377
+ key=_META + "insights",
378
+ native="AdsInsights",
379
+ source="meta_insights_daily",
380
+ label="Meta insights (daily)",
381
+ pinned="date_start",
382
+ identity=("ad_id", "date_start"),
383
+ links=(
384
+ ("ad_id", _META + "ads", "id", "many_to_one"),
385
+ ),
386
+ ),
387
+ )
388
+
389
+
390
+ register("amazon", AMAZON_TABLES)
391
+ register("meta", META_TABLES)
392
+
393
+ __all__ = ["CARDINALITIES", "ConnectorTableSpec", "SPECS", "AMAZON_TABLES", "META_TABLES",
394
+ "register", "connectors", "tables_for", "all_specs", "spec_for", "connector_of",
395
+ "edges_for"]
platform/core/relations.py CHANGED
@@ -81,29 +81,54 @@ OPEN_INVOICE_WHERE = ("state = 'posted' AND move_type IN ('out_invoice','out_ref
81
  #:
82
  #: ⚠ `served` RECORDS WHETHER THE PINNED READ CAN ANSWER THIS EDGE TODAY, and it is a measurement
83
  #: rather than a wish. The pinned read is built into `routes_odoo_tables._compiled_read`, which
84
- #: serves the READ-THROUGH grids only (`GRID_SOURCES` binds exactly `ut_odoo_orders`,
85
- #: `ut_odoo_order_lines`, `ut_odoo_gl_lines` and `ut_odoo_accounts`). `ut_odoo_invoices` is
86
- #: MATERIALISED, so its rows come from `routes_tables.table_rows`, which takes no predicate at all
87
- #: and is in no lane's fence this wave. The edge is still DECLARED, because a tab that is known to
88
- #: exist and cannot yet be served is a reported limit, while an undeclared one is a silent absence.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  BRIDGES = (
90
  {'key': 'bridge_customer_orders',
91
  'label': 'Orders',
92
  'source': 'customer_data', 'target': 'ut_odoo_orders',
93
  'source_col': IDENTITY_COL, 'target_col': 'partner_id',
94
- 'where': None, 'served': True},
95
 
96
  {'key': 'bridge_customer_order_lines',
97
  'label': 'Order lines',
98
  'source': 'customer_data', 'target': 'ut_odoo_order_lines',
99
  'source_col': IDENTITY_COL, 'target_col': 'partner_id',
100
- 'where': None, 'served': True},
101
 
102
  {'key': 'bridge_customer_open_invoices',
103
  'label': 'Open invoices',
104
  'source': 'customer_data', 'target': 'ut_odoo_invoices',
105
  'source_col': IDENTITY_COL, 'target_col': 'partner_id',
106
- 'where': OPEN_INVOICE_WHERE, 'served': False},
 
 
 
107
 
108
  # ⚠ `product_id`, NOT `pid`, AND THE OBVIOUS CHOICE WOULD HAVE JOINED NOTHING AT ALL.
109
  # `product_data.pid` is `crc32(default_code)` (`modules/product_data.sku_pid`), so matching it
@@ -119,13 +144,13 @@ BRIDGES = (
119
  'label': 'Order lines',
120
  'source': 'product_data', 'target': 'ut_odoo_order_lines',
121
  'source_col': 'product_id', 'target_col': 'product_id',
122
- 'where': None, 'served': True},
123
 
124
  {'key': 'bridge_order_order_lines',
125
  'label': 'Order lines',
126
  'source': 'ut_odoo_orders', 'target': 'ut_odoo_order_lines',
127
  'source_col': IDENTITY_COL, 'target_col': 'order_id',
128
- 'where': None, 'served': True},
129
  )
130
 
131
 
@@ -150,7 +175,7 @@ def _link_bag(field):
150
 
151
 
152
  def _entry(key, label, target, direction, field=None, on=None, frm=None, served=True,
153
- where=None):
154
  """ONE `/related` entry, in C6's shape.
155
 
156
  ⚠ TWO ADDITIONS TO C6'S LITERAL `{direction, field?, on?}`, both deliberate, both declared in
@@ -180,6 +205,13 @@ def _entry(key, label, target, direction, field=None, on=None, frm=None, served=
180
  'served': bool(served)}
181
  if where:
182
  out['where'] = str(where)
 
 
 
 
 
 
 
183
  return out
184
 
185
 
@@ -347,23 +379,120 @@ def pick(entries, via):
347
  return hits[0] if len(hits) == 1 else None
348
 
349
 
350
- def unknown_via_refusal(table, via):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  """The SENTENCE an unknown `via` earns: what was asked, why it cannot be answered, what to do.
352
 
353
  ⛔ A SENTENCE, NOT A CODE. C6 says an unknown `via` *"refuses with a sentence"*, and the reason
354
  is that the alternative to refusing is serving the whole table under a tab that claims to show
355
  one record's related rows. A bare 400 leaves the caller unable to tell a typo from a link an
356
  administrator has since deleted.
 
 
 
 
 
 
357
  ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
358
  """
359
  named = ''
360
  if isinstance(via, dict):
361
  named = str(via.get('field') or via.get('on') or via.get('direction') or '')
362
- return ("this account cannot resolve a relation "
 
 
363
  + (f"named '{named}' " if named else "")
364
  + f"on '{table}', so there is no edge to pin these rows to. Ask for the relation by "
365
  f"one of the entries GET /api/v1/grid/" + str(table) + "/related returns, or open "
366
  "the linked database on its own and filter it there")
 
 
 
 
 
 
 
 
367
 
368
 
369
  def unresolvable_source_refusal(table, entry):
@@ -393,14 +522,23 @@ def unresolvable_source_refusal(table, entry):
393
  def unserved_target_refusal(entry):
394
  """The sentence a DECLARED but UNSERVED edge earns.
395
 
396
- `served: False` means the target grid stores its rows rather than being read through, so its
397
- window has no predicate to push a pin into. Naming it is the whole difference between a
398
- reported limit and a feature that quietly does nothing.
 
 
 
 
 
 
 
 
 
 
399
  """
400
- return (f"'{entry.get('target')}' is served from its stored copy rather than read through the "
401
- "live mirror, and that door takes no row filter, so this relation cannot be pinned "
402
- "yet. Open that database directly, or ask for the stored read to accept a relation "
403
- "pin")
404
 
405
 
406
  # --------------------------------------------------------------------------- the pin
@@ -473,3 +611,718 @@ def compiled_pin_matches_filter_sql(id_sql, member_ids, columns=None):
473
  if theirs.endswith(')'):
474
  theirs = theirs[:-1]
475
  return ours, theirs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  #:
82
  #: ⚠ `served` RECORDS WHETHER THE PINNED READ CAN ANSWER THIS EDGE TODAY, and it is a measurement
83
  #: rather than a wish. The pinned read is built into `routes_odoo_tables._compiled_read`, which
84
+ #: serves the READ-THROUGH grids only, i.e. the keys `GRID_SOURCES` binds.
85
+ #:
86
+ #: ⭐⭐ W53-T19 / RULING R5 — ALL FIVE ROWS NOW READ `served: True`, AND THE FLAG STAYS ANYWAY.
87
+ #: R5: *"Every `ut_odoo_*` table becomes read-through bound."* `bridge_customer_open_invoices` was
88
+ #: the ONE row carrying `False`, because `ut_odoo_invoices` had no `GRID_SOURCES` spec and its
89
+ #: stored-read door (`routes_tables.table_rows`) takes no predicate at all. `_odoo_sources` now
90
+ #: binds that grain, so the pinned read can push the open-invoice predicate into SQL and the flag
91
+ #: is True by measurement rather than by wish. ⛔ THE FLAG IS NOT DELETED WITH THE ONE `False`
92
+ #: THAT USED IT: `served` is a per-edge DECLARATION, a bridge onto a grain some future connector
93
+ #: has not bound yet is exactly the case it exists for, and `unserved_target_refusal` below is the
94
+ #: sentence that turns such an edge into a reported limit instead of a tab that quietly serves
95
+ #: nothing (standing rule 1's second sentence). A tab that is known to exist and cannot yet be
96
+ #: served is a reported limit; an undeclared one is a silent absence.
97
+ #:
98
+ #: ⭐⭐ `cardinality` WAS ADDED TO EVERY ROW BY W53-T17 UNDER RULING R12, AND THE BANNER ABOVE IS
99
+ #: WHY THAT SENTENCE IS HERE. "NOTHING ELSE MAY BE ADDED WITHOUT A RULING" asks for a ruling before
100
+ #: this list changes; R12 (*"the connector spec declares edges; the server enumerates what is
101
+ #: reachable within two hops"*) IS that ruling, and it needs every edge to state its own shape.
102
+ #: ⛔ NO SIXTH BRIDGE WAS ADDED. The list is still the five C6 names; what is new is one key on each.
103
+ #: ⛔⛔ AND THE VALUE IS DECLARED, NEVER INFERRED FROM `direction`. An earlier draft of the depth-2
104
+ #: work mapped `bridge -> one_to_many` off the direction alone and got the right answer here by
105
+ #: luck; the same map read `forward -> many_to_one`, which is FALSE of `module_link_fields
106
+ #: ('customer_data')`, where `invoices` and `orders` are forward link fields and both are one-to-MANY
107
+ #: fan-outs. A mislabelled cardinality does not go red, it goes to the client, which unnests the
108
+ #: embedding and repeats values. Each of the five below was read off its own row: one customer has
109
+ #: many orders, many order lines and many open invoices; one product has many order lines; one order
110
+ #: has many order lines.
111
  BRIDGES = (
112
  {'key': 'bridge_customer_orders',
113
  'label': 'Orders',
114
  'source': 'customer_data', 'target': 'ut_odoo_orders',
115
  'source_col': IDENTITY_COL, 'target_col': 'partner_id',
116
+ 'where': None, 'served': True, 'cardinality': 'one_to_many'},
117
 
118
  {'key': 'bridge_customer_order_lines',
119
  'label': 'Order lines',
120
  'source': 'customer_data', 'target': 'ut_odoo_order_lines',
121
  'source_col': IDENTITY_COL, 'target_col': 'partner_id',
122
+ 'where': None, 'served': True, 'cardinality': 'one_to_many'},
123
 
124
  {'key': 'bridge_customer_open_invoices',
125
  'label': 'Open invoices',
126
  'source': 'customer_data', 'target': 'ut_odoo_invoices',
127
  'source_col': IDENTITY_COL, 'target_col': 'partner_id',
128
+ # ⭐ W53-T19 / R5: `served` flipped to True when `ut_odoo_invoices` gained its read-through
129
+ # binding (`routes_odoo_tables._odoo_sources`). The predicate above is pushed into that
130
+ # window's SQL beside the pin, which is the only thing that was ever missing here.
131
+ 'where': OPEN_INVOICE_WHERE, 'served': True, 'cardinality': 'one_to_many'},
132
 
133
  # ⚠ `product_id`, NOT `pid`, AND THE OBVIOUS CHOICE WOULD HAVE JOINED NOTHING AT ALL.
134
  # `product_data.pid` is `crc32(default_code)` (`modules/product_data.sku_pid`), so matching it
 
144
  'label': 'Order lines',
145
  'source': 'product_data', 'target': 'ut_odoo_order_lines',
146
  'source_col': 'product_id', 'target_col': 'product_id',
147
+ 'where': None, 'served': True, 'cardinality': 'one_to_many'},
148
 
149
  {'key': 'bridge_order_order_lines',
150
  'label': 'Order lines',
151
  'source': 'ut_odoo_orders', 'target': 'ut_odoo_order_lines',
152
  'source_col': IDENTITY_COL, 'target_col': 'order_id',
153
+ 'where': None, 'served': True, 'cardinality': 'one_to_many'},
154
  )
155
 
156
 
 
175
 
176
 
177
  def _entry(key, label, target, direction, field=None, on=None, frm=None, served=True,
178
+ where=None, cardinality=None):
179
  """ONE `/related` entry, in C6's shape.
180
 
181
  ⚠ TWO ADDITIONS TO C6'S LITERAL `{direction, field?, on?}`, both deliberate, both declared in
 
205
  'served': bool(served)}
206
  if where:
207
  out['where'] = str(where)
208
+ if cardinality:
209
+ # ⚠ OMITTED WHEN ABSENT, ON PURPOSE (W53-T17). `related()` calls the three builders without
210
+ # a cardinality, so its entries keep the EXACT shape `routes_odoo_tables._related_pin`
211
+ # already resolves against; `one_hop()` is what annotates them, from the declaration each
212
+ # edge came with. A key that appeared unconditionally as None would be a new field in a
213
+ # contract another ticket's fence already reads.
214
+ out['cardinality'] = str(cardinality)
215
  return out
216
 
217
 
 
379
  return hits[0] if len(hits) == 1 else None
380
 
381
 
382
+ def pick_candidates(entries, via):
383
+ """THE LIST `pick` COMPUTES AND THROWS AWAY: every entry the bag `via` could have meant.
384
+
385
+ ⭐⭐ W53-T18 / C3. `pick` answers None for an AMBIGUOUS bag, which is right, and then discards
386
+ the very list that would tell the caller how to disambiguate: `customer_data` really does carry
387
+ two bridges reading `{direction: "bridge", on: "partner_id"}`, and "cannot resolve" plus
388
+ silence leaves the caller no way to find that out except by listing the whole door again. C3
389
+ asks for *"the ENUMERATED candidates ... not prose"* for an unknown OR AMBIGUOUS `via`, and
390
+ this is the ambiguous half of it.
391
+
392
+ ⛔⛔ IT MIRRORS `pick`'s MATCHING AND CHANGES NOTHING ABOUT `pick`. That function is resolved
393
+ against by `routes_odoo_tables._related_pin`, which is in another ticket's fence, so it is left
394
+ byte for byte as it was rather than refactored to share this body. `verify_odoo_relational`
395
+ asserts the two agree in both directions (exactly one candidate iff `pick` answers an entry,
396
+ and it is that entry) rather than letting the duplication drift unobserved.
397
+
398
+ ⛔ IT IS A STRICT MIRROR AND RETURNS `[]` WHEN NOTHING MATCHED. The TEACHING fallback (show the
399
+ caller what IS there when their bag matched nothing) lives in `via_candidates` below, and the
400
+ two are kept apart on purpose: mixing them would break the very biconditional the gate checks,
401
+ because a no-match bag that fell back to a single-entry list would look exactly like the
402
+ unambiguous case `pick` answers.
403
+ """
404
+ entries = list(entries or ())
405
+ if not isinstance(via, dict):
406
+ return []
407
+ want_dir = str(via.get('direction') or '')
408
+ if want_dir not in DIRECTIONS:
409
+ return []
410
+ want_key = str(via.get('key') or '')
411
+ want_field = str(via.get('field') or '')
412
+ want_on = str(via.get('on') or '')
413
+ if not (want_key or want_field or want_on):
414
+ return [] # a direction alone names no edge; `pick` refuses it too
415
+ hits = []
416
+ for entry in entries:
417
+ got = entry['via']
418
+ if got['direction'] != want_dir:
419
+ continue
420
+ if want_key:
421
+ if entry['key'] == want_key:
422
+ hits.append(entry)
423
+ continue
424
+ if want_field and str(got.get('field') or '') != want_field:
425
+ continue
426
+ if want_on and str(got.get('on') or '') != want_on:
427
+ continue
428
+ hits.append(entry)
429
+ return hits
430
+
431
+
432
+ def via_candidates(entries, via=None):
433
+ """WHAT TO OFFER A CALLER WHOSE BAG DID NOT RESOLVE: join columns and a retry bag each.
434
+
435
+ `[{key, label, target, direction, on, from, retry}]`, where `retry` is the LITERAL `via` bag
436
+ that resolves that one edge and nothing else. `via.key` is what makes a bag unambiguous (see
437
+ `_entry`), so that is what the retry carries.
438
+
439
+ ⭐ AMBIGUOUS FIRST, THEN THE DIRECTION, THEN EVERYTHING. An ambiguous bag is offered exactly the
440
+ entries it was ambiguous BETWEEN, which is the shortest useful answer; a bag that matched
441
+ nothing at all is offered its direction's entries, and a malformed one the whole scoped list,
442
+ because a caller who named nothing resolvable has to see what exists before it can name it.
443
+ ⛔ ALWAYS OUT OF THE SCOPED `entries` IT WAS HANDED, so it can never name an edge this account
444
+ would not have been offered.
445
+ """
446
+ hits = pick_candidates(entries, via)
447
+ if not hits:
448
+ want_dir = str((via or {}).get('direction') or '') if isinstance(via, dict) else ''
449
+ hits = [e for e in (entries or ()) if e['via']['direction'] == want_dir] or list(
450
+ entries or ())
451
+ out = []
452
+ for entry in hits:
453
+ got = entry.get('via') or {}
454
+ out.append({'key': str(entry.get('key') or ''), 'label': str(entry.get('label') or ''),
455
+ 'target': str(entry.get('target') or ''),
456
+ 'direction': str(got.get('direction') or ''),
457
+ 'on': str(got.get('on') or ''), 'from': str(got.get('from') or ''),
458
+ 'retry': {'direction': str(got.get('direction') or ''),
459
+ 'key': str(entry.get('key') or '')}})
460
+ return out
461
+
462
+
463
+ def unknown_via_refusal(table, via, candidates=None):
464
  """The SENTENCE an unknown `via` earns: what was asked, why it cannot be answered, what to do.
465
 
466
  ⛔ A SENTENCE, NOT A CODE. C6 says an unknown `via` *"refuses with a sentence"*, and the reason
467
  is that the alternative to refusing is serving the whole table under a tab that claims to show
468
  one record's related rows. A bare 400 leaves the caller unable to tell a typo from a link an
469
  administrator has since deleted.
470
+
471
+ ⭐ `candidates` IS OPTIONAL AND ADDITIVE (W53-T18 / C3), so `routes_odoo_tables._related_pin`
472
+ keeps its exact existing sentence with two positional arguments while a caller that has run
473
+ `via_candidates` gets the enumeration appended. ⛔ THE STRUCTURED LIST IS THE ANSWER AND THIS
474
+ IS ONLY ITS PROSE: a client renders `via_candidates`' array, not this clause, which is why the
475
+ array is returned separately rather than being recoverable by parsing English.
476
  ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
477
  """
478
  named = ''
479
  if isinstance(via, dict):
480
  named = str(via.get('field') or via.get('on') or via.get('direction') or '')
481
+ elif isinstance(via, (list, tuple)):
482
+ named = ' then '.join(str(v) for v in via)
483
+ base = ("this account cannot resolve a relation "
484
  + (f"named '{named}' " if named else "")
485
  + f"on '{table}', so there is no edge to pin these rows to. Ask for the relation by "
486
  f"one of the entries GET /api/v1/grid/" + str(table) + "/related returns, or open "
487
  "the linked database on its own and filter it there")
488
+ cands = list(candidates or ())
489
+ if not cands:
490
+ return base
491
+ shown = '; '.join(
492
+ "'{k}' opens '{t}' joined on '{on}' from '{frm}' (retry with key '{k}')".format(
493
+ k=c.get('key'), t=c.get('target'), on=c.get('on') or '', frm=c.get('from') or '')
494
+ for c in cands)
495
+ return base + f". The relations this account is offered on '{table}': {shown}"
496
 
497
 
498
  def unresolvable_source_refusal(table, entry):
 
522
  def unserved_target_refusal(entry):
523
  """The sentence a DECLARED but UNSERVED edge earns.
524
 
525
+ `served: False` means the target grid has no read-through binding on this deployment, so the
526
+ door that answers its rows accepts no row filter and there is nowhere to push a pin. Naming it
527
+ is the whole difference between a reported limit and a feature that quietly does nothing.
528
+
529
+ ⛔⛔ W53-T19 / R5 — REWRITTEN, NOT DELETED, AND NO EDGE CARRIES `served: False` TODAY. Every
530
+ Odoo bridge is now servable, so this function has no live subject in `BRIDGES`; it is kept
531
+ because `served` is a per-edge DECLARATION that the next connector's bridges will set from
532
+ their own measurement, and deleting the refusal would leave that flag with no consequence
533
+ except an empty tab. ⚠ THE WORDING CHANGED FOR A SECOND REASON: the old sentence described
534
+ the target by where its rows were kept, and R5 retires that phrasing from the tree along
535
+ with the refusal it belonged to. The cause is now named as what it actually is, the ABSENCE
536
+ OF A BINDING, which is also what `routes_odoo_tables`' `not_read_through` refusal now says.
537
+ ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
538
  """
539
+ return (f"'{entry.get('target')}' has no read-through binding on this deployment, so the door "
540
+ "that answers its rows takes no row filter and this relation cannot be pinned yet. "
541
+ "Open that database directly, or ask for a read-through binding to be added for it")
 
542
 
543
 
544
  # --------------------------------------------------------------------------- the pin
 
611
  if theirs.endswith(')'):
612
  theirs = theirs[:-1]
613
  return ours, theirs
614
+
615
+
616
+ # ════════���══════════════════════════════════════════════════════════════════════════════════════
617
+ # ⭐⭐ W53-T17 / RULING R12 / CONTRACT C3 — DEPTH 2, BY NAMED EDGES, AND NEVER A PATH SEARCH.
618
+ #
619
+ # R12, verbatim: *"Relation traversal is DEPTH 2, and every hop is NAMED. The connector spec
620
+ # declares edges; the server enumerates what is reachable within two hops and offers it; the client
621
+ # pins one by naming each edge (`via = ["orders","order_lines"]`). Never a path search. Depth 3
622
+ # REFUSES and names the missing hop. Aggregation stays at depth 1."*
623
+ #
624
+ # ⛔⛔ ENUMERATE, DO NOT SEARCH, AND THE DIFFERENCE IS THE WHOLE TICKET. A search asks "how do I get
625
+ # from A to B" and answers with whichever route it found first; the answer changes when an edge is
626
+ # added somewhere else entirely, silently, and the number on the screen changes with it. Enumeration
627
+ # asks "what is reachable in at most two named hops" and hands the caller the list; the caller pins
628
+ # one BY NAME. `related_paths` below therefore has exactly two levels written out as two loops, does
629
+ # not call itself, and `verify_odoo_relational` asserts that mechanically by parsing this source
630
+ # rather than by trusting this paragraph.
631
+ #
632
+ # ⛔ NOTHING HERE AGGREGATES. R12's last sentence keeps rollups at depth 1, so a two-hop entry is a
633
+ # ROW SET resolved at read time and this module stores nothing about it.
634
+ #
635
+ # ⛔ AN EDGE KEY IS UNIQUE PER SOURCE TABLE, NOT ACROSS A CONNECTOR. `connector_spec.edges_for
636
+ # ("odoo")` returns ten edges carrying seven distinct keys, because four tables link to
637
+ # `ut_odoo_customers` on `partner_id` and the key is `f"{target}_link__{from_col}"`. A `path` is
638
+ # unambiguous ONLY because it is anchored at the table it was enumerated from, exactly as
639
+ # PostgREST's embed syntax is anchored at the table in the URL. ⇒ NEVER build a dict keyed on edge
640
+ # key alone across a connector, and always resolve a path against the entries of ONE source table.
641
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
642
+
643
+ #: ⭐ TWO. R12 fixes it and this constant is the only place it is written down; the route's `depth`
644
+ #: default and the over-depth refusal both read it, and the gate asserts the route's default equals
645
+ #: it rather than letting two literal 2s drift.
646
+ MAX_DEPTH = 2
647
+
648
+ #: The cardinality vocabulary, as a FALLBACK only. `core.connector_spec.CARDINALITIES` is the
649
+ #: source; this copy exists because that import is done lazily (see `_spec`) and a caller in a
650
+ #: stripped environment must still get a sane answer instead of a NameError. `verify_odoo_relational`
651
+ #: asserts the two tuples are equal, which is this file's own idiom for a transcribed constant
652
+ #: (`OPEN_INVOICE_WHERE` is held against `odoo_relational._AR_WHERE` the same way).
653
+ CARDINALITIES = ('many_to_one', 'one_to_many', 'one_to_one', 'many_to_many')
654
+
655
+ #: The inverse of each cardinality, read from the other end of the same edge. ⛔ IT IS A PROPERTY OF
656
+ #: THE EDGE, NOT OF THE DIRECTION IT IS READ IN: `one_to_one` and `many_to_many` are symmetric and
657
+ #: invert to themselves, which a `forward -> many_to_one / reverse -> one_to_many` map cannot say.
658
+ _INVERSE = {'many_to_one': 'one_to_many', 'one_to_many': 'many_to_one',
659
+ 'one_to_one': 'one_to_one', 'many_to_many': 'many_to_many'}
660
+
661
+
662
+ def _spec():
663
+ """`core.connector_spec`, or None when it cannot be imported.
664
+
665
+ ⛔ LAZY AND FORGIVING, like `compiled_pin_matches_filter_sql`'s `harness` import. It is a
666
+ SIBLING inside `core` rather than a layer above, so there is no layering objection to it; the
667
+ laziness is about import spelling (`core.connector_spec` from the api layer, plain
668
+ `connector_spec` from inside `platform/`) and about a caller that has neither.
669
+ """
670
+ try:
671
+ import core.connector_spec as spec # noqa: PLC0415
672
+ return spec
673
+ except Exception: # noqa: BLE001
674
+ pass
675
+ try:
676
+ import connector_spec as spec # noqa: PLC0415
677
+ return spec
678
+ except Exception: # noqa: BLE001
679
+ return None
680
+
681
+
682
+ def cardinality_of_link_field(bag):
683
+ """The cardinality of a FORWARD link field, from the bag's own `single` flag.
684
+
685
+ ⛔⛔ THE INPUT IS THE DECLARATION, NEVER THE DIRECTION, AND THAT IS WHY THIS IS ONE HELPER PER
686
+ SOURCE INSTEAD OF ONE MAP KEYED ON `via.direction`. A map saying `forward -> many_to_one` is
687
+ FALSE of the grid this ticket is about: `odoo_relational.module_link_fields('customer_data')`
688
+ declares `invoices` and `orders` as forward link fields and both are one-to-MANY fan-outs, and
689
+ `agent_link` carries its own warning that Odoo's `agent_ids` is a many2many. All three would
690
+ have reached the client labelled `many_to_one`.
691
+
692
+ `core.user_tables._clean_link` stores `out['single'] = True` when and only when the author asked
693
+ for one row, so `single` IS the declaration and its absence is the declaration of the other case.
694
+ """
695
+ return 'many_to_one' if (bag or {}).get('single') is True else 'one_to_many'
696
+
697
+
698
+ def cardinality_of_reverse_field(bag):
699
+ """The cardinality of a link field read FROM THE TARGET END: the inverse of the forward one.
700
+
701
+ Same rule as above and the same reason it is not keyed on direction: the answer comes from the
702
+ forward declaration, inverted, so a many2many forward stays many2many rather than becoming the
703
+ `one_to_many` a direction map would have produced.
704
+ """
705
+ return _INVERSE[cardinality_of_link_field(bag)]
706
+
707
+
708
+ def _bridge_cardinality(row):
709
+ """A bridge's cardinality, off its own `BRIDGES` row. Declared there, never inferred here."""
710
+ return str(row.get('cardinality') or 'one_to_many')
711
+
712
+
713
+ def compose_cardinality(a, b):
714
+ """The cardinality of a two-hop path, from its two hops. See the vocabulary above.
715
+
716
+ ⭐ TWO `many_to_one` HOPS STAY `many_to_one` (a line names its order names its customer: still
717
+ one customer). Two `one_to_many` hops stay `one_to_many` (a customer's orders' lines: still a
718
+ fan-out). A MIX IS HONESTLY `many_to_many`, and it is NOT rounded toward either side: fanning
719
+ out and then folding back reaches many rows from many, and calling that `one_to_many` would
720
+ promise the client a nesting the rows do not have.
721
+ ⚠ `one_to_one` composes as the identity, because a one-to-one hop changes no multiplicity.
722
+ ⚠ ANYTHING UNRECOGNISED COMPOSES TO `many_to_many`, the widest honest answer, rather than to a
723
+ guess that happens to look tidy.
724
+ """
725
+ a, b = str(a or ''), str(b or '')
726
+ if a not in CARDINALITIES or b not in CARDINALITIES:
727
+ return 'many_to_many'
728
+ if a == 'one_to_one':
729
+ return b
730
+ if b == 'one_to_one':
731
+ return a
732
+ if a == b and a in ('many_to_one', 'one_to_many'):
733
+ return a
734
+ return 'many_to_many'
735
+
736
+
737
+ def spec_entries(table):
738
+ """The CONNECTOR-SPEC edges of `table`, in BOTH directions, in `related()`'s entry shape.
739
+
740
+ ⛔⛔ BOTH DIRECTIONS, AND AN OUTBOUND-ONLY READ CANNOT ANSWER THE QUESTION THIS TICKET ASKS.
741
+ MEASURED after W53-T38 landed: `edges_for('ut_odoo_customers')` is exactly one edge, `agent_id
742
+ -> ut_odoo_agents`, because `connector_spec` declares every Odoo edge CHILD -> PARENT (a line
743
+ names its order, an order names its customer). The edges TARGETING `ut_odoo_customers` are the
744
+ invoices, orders, order lines and GL lines, all on `partner_id`, and none of them is outbound.
745
+ So `ut_odoo_customers -> ut_odoo_orders -> ut_odoo_order_lines` is TWO REVERSE HOPS and an
746
+ outbound-only reader would enumerate a customer's agent and stop. `verify_odoo_relational`
747
+ drives an outbound-only `spec_entries` as a negative control so this stays load-bearing rather
748
+ than decorative.
749
+
750
+ ⛔ THE COLUMNS SWAP WITH THE DIRECTION, EXACTLY AS `reverse_links` WARNS. Read its note before
751
+ changing anything here. Outbound, THIS table's `from_col` is matched against the target's
752
+ `to_col`. Inbound, the roles invert: the tab pins the OTHER table on ITS OWN `from_col`, keyed
753
+ by the value THIS table's `to_col` carries. Getting it backwards is the silent-wrong-join bug,
754
+ which returns a plausible row count and no error.
755
+
756
+ ⚠ THE INBOUND KEY IS `f"{source_key}__{edge_key}"`, the shape `reverse_links` already uses
757
+ (`f"{key}__{field_key}"`), because an edge key is unique per SOURCE table and four Odoo tables
758
+ share `ut_odoo_customers_link__partner_id`. The inbound LABEL names the SOURCE table, since that
759
+ is the database the tab opens.
760
+
761
+ ⚠ `served` TAKES `_entry`'s DEFAULT, exactly as the forward and reverse link FIELDS do. Only
762
+ `BRIDGES` carries a measured `served` today, and inventing one per spec edge here would be a
763
+ second, unmeasured source for the same judgement.
764
+ """
765
+ spec = _spec()
766
+ me = str(table or '')
767
+ if spec is None or not me:
768
+ return []
769
+ out = []
770
+ for edge in spec.edges_for(me):
771
+ out.append(_entry(
772
+ key=str(edge.get('key') or ''), label=str(edge.get('label') or ''),
773
+ target=str(edge.get('target') or ''), direction='forward',
774
+ on=edge.get('to_col'), frm=edge.get('from_col'),
775
+ cardinality=edge.get('cardinality')))
776
+ for source_key, source_spec in sorted((spec.all_specs() or {}).items()):
777
+ if str(source_key) == me:
778
+ continue # a table's link to itself is already an outbound edge
779
+ for from_col, target, to_col, cardinality in (getattr(source_spec, 'links', ()) or ()):
780
+ if str(target) != me:
781
+ continue
782
+ out.append(_entry(
783
+ key=f"{source_key}__{target}_link__{from_col}",
784
+ label=str(getattr(source_spec, 'label', '') or source_key),
785
+ target=str(source_key), direction='reverse',
786
+ on=from_col, # the column on the OTHER table
787
+ frm=to_col, # the column on THIS one
788
+ cardinality=_INVERSE.get(str(cardinality), 'many_to_many')))
789
+ return out
790
+
791
+
792
+ def _link_field_cardinalities(table, fields, defs):
793
+ """`{entry_key: cardinality}` for the FORWARD and REVERSE link-field entries of `table`.
794
+
795
+ It rescans the same two inputs `forward_links` and `reverse_links` scan, keyed the same way, so
796
+ that `related()` keeps its exact current shape and the annotation lives entirely in `one_hop`.
797
+ """
798
+ out = {}
799
+ for field in (fields or ()):
800
+ bag = _link_bag(field)
801
+ if bag is None or not str(bag.get('table') or ''):
802
+ continue
803
+ out[str(field.get('key') or '')] = cardinality_of_link_field(bag)
804
+ me = str(table or '')
805
+ for key, defn in sorted((defs or {}).items()):
806
+ key = str(key)
807
+ if key == me or not isinstance(defn, dict):
808
+ continue
809
+ for field in (defn.get('fields') or ()):
810
+ bag = _link_bag(field)
811
+ if bag is None or str(bag.get('table') or '') != me:
812
+ continue
813
+ out[f"{key}__{field.get('key') or ''}"] = cardinality_of_reverse_field(bag)
814
+ return out
815
+
816
+
817
+ def one_hop(table, fields=None, defs=None):
818
+ """EVERYTHING ONE NAMED HOP FROM `table`: `related()` plus the connector spec, deduplicated.
819
+
820
+ Every entry carries a `cardinality`, taken from the declaration it came with:
821
+
822
+ * a forward link FIELD -> the bag's `single` flag (`cardinality_of_link_field`)
823
+ * a reverse link FIELD -> the inverse of that (`cardinality_of_reverse_field`)
824
+ * a BRIDGE -> its own `BRIDGES` row
825
+ * a CONNECTOR-SPEC edge -> the 4th element of the link tuple, inverted when read inbound
826
+
827
+ ⛔⛔ THE EXISTING SOURCE WINS A COLLISION, which is the same posture `related()` already takes
828
+ when it suppresses a bridge that repeats a link field. `bridge_order_order_lines` and the spec's
829
+ inbound `ut_odoo_order_lines -> ut_odoo_orders` edge are the SAME join, column for column, and
830
+ offering both would give one order two tabs both labelled Order lines over identical rows. R2:
831
+ *"one tab per related table"*. The dedupe is on `edge_identity`, which is target plus both join
832
+ columns plus the predicate; read its docstring for why `where` is in there.
833
+ """
834
+ base = list(related(table, fields, defs))
835
+ cards = _link_field_cardinalities(table, fields, defs)
836
+ bridge_cards = {b['key']: _bridge_cardinality(b) for b in BRIDGES}
837
+ out = []
838
+ for entry in base:
839
+ entry = dict(entry)
840
+ got = cards.get(entry['key']) or bridge_cards.get(entry['key'])
841
+ entry['cardinality'] = str(got or 'many_to_many')
842
+ out.append(entry)
843
+ seen = {edge_identity(e) for e in out}
844
+ for entry in spec_entries(table):
845
+ if edge_identity(entry) in seen:
846
+ continue
847
+ seen.add(edge_identity(entry))
848
+ out.append(dict(entry))
849
+ return out
850
+
851
+
852
+ def _two_hop_entry(first, second):
853
+ """ONE two-hop entry, composed from the two one-hop entries it is made of.
854
+
855
+ ⭐⭐ `via.direction` IS `'path'`, WHICH IS DELIBERATELY **NOT** IN `DIRECTIONS`, AND THAT IS A
856
+ FAIL-CLOSED DESIGN RATHER THAN AN OVERSIGHT. `pick()` returns None for any direction outside
857
+ `DIRECTIONS`, so every existing resolver — including `routes_odoo_tables._related_pin`, which
858
+ is in another ticket's fence — refuses a two-hop pin instead of resolving it as if it were one
859
+ hop. `pick_path` is the only thing that can answer it. The day a resolver learns to serve two
860
+ hops, it opts in by calling `pick_path`; until then nothing serves half a traversal.
861
+
862
+ ⚠ NO `where` IS FLATTENED ONTO THE COMPOSITE. Each hop keeps its own predicate on its own entry
863
+ and `path` names the hops in order, so a resolver applies them in order. Copying one hop's
864
+ predicate onto the pair would claim ONE predicate where there may be two, and the open-invoice
865
+ bridge is exactly an edge whose predicate is half of what it means.
866
+
867
+ ⛔ THE LABEL IS DISPLAY COPY: sentence case, no em dash, no en dash (standing rule 2).
868
+ """
869
+ path = [first['key'], second['key']]
870
+ key = f"{first['key']}>{second['key']}"
871
+ return {
872
+ 'key': key,
873
+ 'label': f"{second['label']} via {first['label']}",
874
+ 'via': {'direction': 'path', 'key': key, 'path': list(path)},
875
+ 'target': second['target'],
876
+ 'served': bool(first.get('served')) and bool(second.get('served')),
877
+ 'path': path,
878
+ 'hops': 2,
879
+ 'cardinality': compose_cardinality(first.get('cardinality'), second.get('cardinality')),
880
+ }
881
+
882
+
883
+ def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None):
884
+ """C3'S `/related` ANSWER: everything reachable from `table` in at most `depth` NAMED hops.
885
+
886
+ `[{key, label, via, target, served, where?, cardinality, path, hops}]`, one-hop entries first
887
+ and in `related()`'s existing order, then the two-hop ones.
888
+
889
+ ⛔⛔ THIS FUNCTION DOES NOT CALL ITSELF AND MUST NEVER LEARN TO. R12 says *"never a path
890
+ search"*, and the two levels are written out as two loops precisely so that the claim is
891
+ checkable: `verify_odoo_relational` parses this source and asserts there is no recursive call
892
+ and that `MAX_DEPTH` is 2. A `depth` argument that recursed would make depth 3 a one-character
893
+ change and R12 a comment.
894
+
895
+ `may_open(key) -> bool` is an optional permission wall, applied to EVERY table on the path
896
+ INCLUDING the intermediate: hop 1 is filtered on its target, and the intermediate of a two-hop
897
+ path IS a hop-1 target, so closing a table removes both the tab and everything reachable
898
+ through it. ⚠ W53-T18 turns that silent disappearance into a NAMED refusal; this ticket only
899
+ makes the filtering correct.
900
+
901
+ `fields_for(key) -> fields` supplies the INTERMEDIATE table's field list, since the caller's
902
+ permission wall is the only thing that knows it. ⛔ `defs` IS PASSED DOWN TO THE SECOND HOP.
903
+ A first cut passed neither, and the intermediate's reverse links were then invisible: the
904
+ entire second half of the answer was missing with nothing red beside it.
905
+
906
+ ⛔ A HOP-2 EDGE POINTING BACK AT `table` IS DROPPED. `customer -> orders -> customer` is a round
907
+ trip, not a relation, and offering it would put a tab on the customers grid labelled Customers.
908
+ """
909
+ if depth not in (1, MAX_DEPTH):
910
+ raise ValueError(
911
+ "relation depth is 1 or %d; %r was asked for. The route turns this into a named "
912
+ "refusal rather than a 500" % (MAX_DEPTH, depth))
913
+ table = str(table or '')
914
+ hop1 = [e for e in one_hop(table, fields, defs)
915
+ if may_open is None or may_open(e['target'])]
916
+ out = []
917
+ for entry in hop1:
918
+ entry = dict(entry)
919
+ entry['path'] = [entry['key']]
920
+ entry['hops'] = 1
921
+ out.append(entry)
922
+ if depth < MAX_DEPTH:
923
+ return out
924
+ seen = set()
925
+ for first in hop1:
926
+ mid = first['target']
927
+ mid_fields = fields_for(mid) if fields_for is not None else None
928
+ for second in one_hop(mid, mid_fields, defs):
929
+ if second['target'] == table:
930
+ continue
931
+ if may_open is not None and not may_open(second['target']):
932
+ continue
933
+ path = (first['key'], second['key'])
934
+ if path in seen:
935
+ continue
936
+ seen.add(path)
937
+ out.append(_two_hop_entry(first, second))
938
+ return out
939
+
940
+
941
+ def pick_path(entries, via):
942
+ """The ONE entry of an ALREADY-BUILT list whose `path` is EXACTLY `via`, or None.
943
+
944
+ ⛔⛔ EXACT. NOT A PREFIX, NOT A SUFFIX, AND THE REASON IS THE ONE `pick()` ALREADY STATES FOR
945
+ THE DICT SHAPE. A prefix match would let `via=["orders"]` be answered by the two-hop
946
+ `orders > order lines` entry, which shares its first key: the caller asked for a customer's
947
+ orders and would be handed their order LINES, correctly shaped and wrong. A suffix match has the
948
+ mirror problem, because an edge key is unique per SOURCE table and the same key appears under
949
+ several sources across a connector. Refusing sends the caller back with a sentence; guessing
950
+ sends it a number.
951
+
952
+ ⚠ A BARE STRING IS ONE HOP, so a client that sends `via=orders` is asking for the one-hop entry
953
+ and gets it. That is the back-compat leg of C3, and it is a one-element PATH rather than a
954
+ second matching rule.
955
+
956
+ ⚠ THE LIST IS AN ARGUMENT, exactly as it is for `pick()`, so the route resolves a pin against
957
+ the SCOPED enumeration and an edge a reader cannot be offered is an edge they cannot pin.
958
+ """
959
+ if isinstance(via, str):
960
+ want = [via]
961
+ elif isinstance(via, (list, tuple)):
962
+ want = [str(v) for v in via]
963
+ else:
964
+ return None
965
+ if not want or not all(want):
966
+ return None
967
+ for entry in (entries or ()):
968
+ if [str(k) for k in (entry.get('path') or ())] == want:
969
+ return entry
970
+ return None
971
+
972
+
973
+ def over_depth_refusal(table, via):
974
+ """The sentence a `via` naming MORE than `MAX_DEPTH` hops earns, naming the hops beyond the limit.
975
+
976
+ ⛔ IT NAMES THEM. R12 says depth 3 *"REFUSES and names the missing hop"*, and the naming is the
977
+ difference between a limit a caller can work around in one more request and a wall. The caller
978
+ is told which hops were dropped and how to reach them: ask for the first two, open that database
979
+ on its own, pin the next hop from there.
980
+ ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
981
+ """
982
+ hops = [str(v) for v in (via or ())]
983
+ beyond = hops[MAX_DEPTH:]
984
+ named = ', '.join(f"'{h}'" for h in beyond) or 'none'
985
+ kept = ', '.join(f"'{h}'" for h in hops[:MAX_DEPTH]) or 'none'
986
+ plural = 'hops' if len(beyond) != 1 else 'hop'
987
+ return (f"a relation on '{table}' is resolved through at most {MAX_DEPTH} named hops, and this "
988
+ f"request names {len(hops)}. The {plural} beyond the limit: {named}. Ask for {kept}, "
989
+ f"open the database that answer lands on, and pin the next hop from there")
990
+
991
+
992
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
993
+ # ⭐⭐ W53-T18 / RULING R13 / CONTRACT C3 — EVERY HOP IS PERMISSION CHECKED, AND A FILTERED HOP
994
+ # SAYS SO. THREE DISTINGUISHABLE ANSWERS, NEVER ONE EMPTY LIST.
995
+ #
996
+ # R13, verbatim: *"Permission on a traversal requires read on EVERY table in the path, intermediate
997
+ # included. A permission-filtered traversal must be distinguishable on the wire from an empty one:
998
+ # 'no related rows', 'you may not see this table' and 'this hop was filtered' are three different
999
+ # answers."*
1000
+ #
1001
+ # W53-T17 made the FILTERING correct: `related_paths` applies `may_open` to every table on the
1002
+ # path, intermediate included, so a closed table removes the tab and everything reachable through
1003
+ # it. What it could not do was SAY SO. A path that vanished under the wall and a path that never
1004
+ # existed came back as the same `None` from `pick_path`, and a listing shortened by the wall came
1005
+ # back as a 200 with a shorter array. That is the exact defect R13 exists to prevent, and it is not
1006
+ # hypothetical anywhere: PostgREST silently EMPTIES an embed under RLS and Odoo omits forbidden
1007
+ # One2many rows with no error at all, so a reader of either cannot tell "nothing here" from "not
1008
+ # for you".
1009
+ #
1010
+ # ⛔⛔ THE MECHANISM IS A DIFF, NOT AN INFERENCE FROM WHERE A WALK STOPPED. An earlier attempt
1011
+ # walked the path one key at a time and named the code after the step that failed, which conflates
1012
+ # "this edge does not exist" with "there are no rows" and cannot tell a permission-filtered
1013
+ # traversal from an empty one at all. The reachable set is instead enumerated TWICE, once WITH the
1014
+ # wall and once WITHOUT it, and the two are compared:
1015
+ #
1016
+ # * present UNFILTERED, absent FILTERED, and a table on the path is closed -> `forbidden_table`,
1017
+ # NAMING that table
1018
+ # * present UNFILTERED, absent FILTERED, and every table on it is open -> `hop_filtered`,
1019
+ # NAMING the hop (the wall that bit is the FIELD wall: the link column the hop is built on is
1020
+ # not visible to this account, so the edge is gone while both of its tables remain open)
1021
+ # * absent from BOTH -> `unknown_via`,
1022
+ # WITH the enumerated candidates, their join columns and the exact retry strings
1023
+ # * present in BOTH, permitted end to end, reaching nothing -> `no_related_rows`
1024
+ #
1025
+ # ⛔⛔ THE UNFILTERED ENUMERATION CHOOSES THE CODE AND NAMES THE TABLE OR HOP. IT NEVER WIDENS WHAT
1026
+ # IS SERVED. Nothing in this block returns a row, an entry or a tab; `wall_refusals` takes the
1027
+ # SERVED list as an argument and only ever reports what is NOT in it, and `verify_odoo_relational`
1028
+ # proves byte for byte that `related_paths`' answer is unchanged by any of it.
1029
+ #
1030
+ # ⚠ NAMING THE FORBIDDEN TABLE IS A DELIBERATE, RULED DISCLOSURE. R13's own words are *"you may
1031
+ # not see this table"*, which cannot be said without saying WHICH. Do not "fix" this as a leak.
1032
+ # ⛔ NOTHING ELSE ABOUT IT IS DISCLOSED: no label, no row count, no column list, no hint about
1033
+ # whether it holds rows for this record. The name, and the fact that the door is shut.
1034
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
1035
+
1036
+ #: ⭐ THE THREE R13 ANSWERS, PLUS THE FOURTH THAT IS NOT A PERMISSION ANSWER AT ALL.
1037
+ #: ⚠ `unknown_via` KEEPS THE NAME `routes_grid.grid_related` ALREADY RAISES rather than gaining a
1038
+ #: synonym: a fourth spelling of the same refusal would be a client-visible rename dressed as a
1039
+ #: feature. `routes_odoo_tables` spells its depth-1 cousin `unknown_relation` and is in another
1040
+ #: ticket's fence, so the two names survive side by side and this constant says which is which.
1041
+ REFUSAL_NO_ROWS = 'no_related_rows'
1042
+ REFUSAL_FORBIDDEN_TABLE = 'forbidden_table'
1043
+ REFUSAL_HOP_FILTERED = 'hop_filtered'
1044
+ REFUSAL_UNKNOWN_VIA = 'unknown_via'
1045
+
1046
+ #: The three R13 answers in R13's own order, and the fourth. A gate reads this rather than four
1047
+ #: literals scattered through two files.
1048
+ REFUSAL_CODES = (REFUSAL_NO_ROWS, REFUSAL_FORBIDDEN_TABLE, REFUSAL_HOP_FILTERED,
1049
+ REFUSAL_UNKNOWN_VIA)
1050
+
1051
+
1052
+ def _named_path(path):
1053
+ """`'a' then 'b'` — how a path is spelled inside a sentence. Empty for an empty path."""
1054
+ return ' then '.join(f"'{k}'" for k in (str(p) for p in (path or ())))
1055
+
1056
+
1057
+ def no_related_rows_refusal(table, path=None):
1058
+ """R13's FIRST answer: everything was open, and there is genuinely nothing on the other side.
1059
+
1060
+ ⛔ IT IS STILL AN ANSWER, NOT AN ABSENCE. C3: *"never one empty list"*. A caller handed `[]`
1061
+ with no code beside it cannot tell this apart from the two refusals below, which is the whole
1062
+ of R13, so the empty case is spelled out loud and says in as many words that nothing was
1063
+ hidden from it.
1064
+ ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1065
+ """
1066
+ named = _named_path(path)
1067
+ if named:
1068
+ return (f"the relation reached by {named} on '{table}' is open to this account at every "
1069
+ f"hop, and it reaches no rows. Nothing was hidden by permission and no hop was "
1070
+ f"filtered: there is simply nothing on the other side of it")
1071
+ return (f"'{table}' reaches no other database within {MAX_DEPTH} named hops that this account "
1072
+ f"may open, and nothing was removed by permission on the way. Ask an administrator to "
1073
+ f"link it to another database, or open the database you want on its own")
1074
+
1075
+
1076
+ def forbidden_table_refusal(table, path, blocked, hop=None):
1077
+ """R13's SECOND answer: a table ON the path, intermediate included, is shut to this account.
1078
+
1079
+ ⭐ IT NAMES `blocked`, AND THAT IS RULED RATHER THAN CARELESS. R13 asks for *"you may not see
1080
+ this table"* as a distinct answer, and an answer that will not say which table is the empty
1081
+ list again wearing a code. Nothing else about that table is disclosed.
1082
+ ⚠ THE CAUSE IS NAMED AS A PAIR, the posture `routes_odoo_tables._related_pin` already takes:
1083
+ the wall is fail-closed and answers False both for a genuine refusal and for a database it
1084
+ could not read at all, so claiming only the first would tell a reader their access was revoked
1085
+ when the store had merely hiccupped.
1086
+ ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1087
+ """
1088
+ named = _named_path(path) or 'this relation'
1089
+ where = f" at the hop named '{hop}'" if hop else ''
1090
+ return (f"the relation reached by {named} on '{table}' passes through '{blocked}'{where}, and "
1091
+ f"this account may not open '{blocked}', either because it is not granted to you or "
1092
+ f"because it could not be read just now. The traversal is refused rather than served "
1093
+ f"short, so no part of it is silently missing. Ask an administrator for access to "
1094
+ f"'{blocked}', or ask for a relation that does not pass through it")
1095
+
1096
+
1097
+ def hop_filtered_refusal(table, path, hop):
1098
+ """R13's THIRD answer: every table on the path is open, and ONE HOP was removed anyway.
1099
+
1100
+ ⭐ THIS IS THE ANSWER THE OTHER TWO CANNOT GIVE AND THE REASON THE DIFF EXISTS. The wall has
1101
+ two halves: the TABLE wall (`may_open`) and the FIELD wall (the column list this account may
1102
+ see). When the second bites, the hop's own link column is invisible while both of its tables
1103
+ stay open, so the traversal is neither forbidden nor empty. Served as `[]` it would read as
1104
+ "this record has nothing here", which is a claim about the business made out of a permission.
1105
+ ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1106
+ """
1107
+ named = _named_path(path) or 'this relation'
1108
+ return (f"the hop named '{hop}' of the relation reached by {named} on '{table}' was filtered "
1109
+ f"out for this account. The databases it crosses are open to you; the link column "
1110
+ f"this hop is built on is not one you may see, so the hop was removed rather than "
1111
+ f"answered empty. Ask an administrator for that column, or ask for a relation that "
1112
+ f"does not use it")
1113
+
1114
+
1115
+ def candidate_paths(table, entries, defs=None, fields_for=None):
1116
+ """EVERY path this account is offered, with its JOIN COLUMNS and the EXACT string to retry.
1117
+
1118
+ `[{key, label, target, path, hops, served, columns: [{key, target, on, from}], via, retry}]`.
1119
+
1120
+ ⭐⭐ PostgREST's `PGRST201` IS THE SHAPE, AND THE REASON IS THAT A REFUSAL SHOULD TEACH. That
1121
+ error does not say "the embed is ambiguous"; it lists every relationship it could have meant,
1122
+ each with the columns it joins on, plus a hint naming the exact strings to retry with. A caller
1123
+ told "resolve this yourself among these N things" without the N things has to go and list them
1124
+ in a second request, and a UI cannot offer them at all.
1125
+
1126
+ ⛔⛔ IT TAKES THE ALREADY-BUILT, ALREADY-SCOPED `entries` AND WIDENS NOTHING. A candidate list
1127
+ computed from the unfiltered enumeration would hand an account the names of edges it may not be
1128
+ offered, which is the opposite of every wall in this file. `pick_path(entries, c['via'])`
1129
+ resolves for every candidate returned, and the gate proves that rather than trusting it.
1130
+
1131
+ ⚠ `columns` CARRIES ONE ROW PER HOP, so a two-hop candidate names BOTH joins. The first hop's
1132
+ columns are on the entry itself; the second hop's are an edge of the INTERMEDIATE table, which
1133
+ is not in `entries` at all, so it is re-read from `one_hop(mid, fields_for(mid), defs)` under
1134
+ the caller's own field wall (memoised per intermediate) rather than invented here.
1135
+
1136
+ ⚠ `retry` IS THE LITERAL QUERY STRING (`via=orders&via=order_lines`), not a description of one.
1137
+ """
1138
+ entries = list(entries or ())
1139
+ by_path = {}
1140
+ for entry in entries:
1141
+ by_path[tuple(str(k) for k in (entry.get('path') or ()))] = entry
1142
+ memo = {}
1143
+ out = []
1144
+ for entry in entries:
1145
+ path = [str(k) for k in (entry.get('path') or ())]
1146
+ if not path:
1147
+ continue
1148
+ columns = []
1149
+ first = by_path.get((path[0],))
1150
+ if first is not None:
1151
+ fv = first.get('via') or {}
1152
+ columns.append({'key': path[0], 'target': str(first.get('target') or ''),
1153
+ 'on': str(fv.get('on') or ''), 'from': str(fv.get('from') or '')})
1154
+ if len(path) > 1 and first is not None:
1155
+ mid = str(first.get('target') or '')
1156
+ if mid not in memo:
1157
+ memo[mid] = one_hop(mid, fields_for(mid) if fields_for is not None else None, defs)
1158
+ second = next((e for e in memo[mid] if str(e.get('key')) == path[1]), None)
1159
+ if second is not None:
1160
+ sv = second.get('via') or {}
1161
+ columns.append({'key': path[1], 'target': str(second.get('target') or ''),
1162
+ 'on': str(sv.get('on') or ''), 'from': str(sv.get('from') or '')})
1163
+ out.append({
1164
+ 'key': str(entry.get('key') or ''), 'label': str(entry.get('label') or ''),
1165
+ 'target': str(entry.get('target') or ''), 'path': path,
1166
+ 'hops': int(entry.get('hops') or len(path)), 'served': bool(entry.get('served')),
1167
+ 'columns': columns, 'via': path,
1168
+ 'retry': '&'.join(f"via={k}" for k in path),
1169
+ })
1170
+ return out
1171
+
1172
+
1173
+ def unknown_via_answer(table, keys, candidates):
1174
+ """The whole `unknown_via` refusal as a BAG: `{code, message, path, candidates}`.
1175
+
1176
+ ⛔ THE CANDIDATES ARE STRUCTURED, NOT PROSE, AND C3 SAYS SO IN AS MANY WORDS. The sentence is
1177
+ still there because a human reads it; the array is there because a client renders it. Spelling
1178
+ them only into the sentence is what `unknown_via_refusal` used to do, and lane E cannot draw a
1179
+ retry button out of an English clause.
1180
+ ⛔ NO EM DASH AND NO EN DASH anywhere in `message` (standing rule 2).
1181
+ """
1182
+ keys = [str(k) for k in (keys or ())]
1183
+ cands = list(candidates or ())
1184
+ named = _named_path(keys) or 'that relation'
1185
+ tail = ''
1186
+ if cands:
1187
+ shown = '; '.join(
1188
+ "'{k}' opens '{t}' joined on '{on}' from '{frm}' (retry with {r})".format(
1189
+ k=c['key'], t=c['target'],
1190
+ on=(c['columns'][-1]['on'] if c.get('columns') else ''),
1191
+ frm=(c['columns'][-1]['from'] if c.get('columns') else ''),
1192
+ r=c['retry'])
1193
+ for c in cands)
1194
+ tail = (f" The relations this account is offered on '{table}', with the exact string to "
1195
+ f"retry with: {shown}")
1196
+ else:
1197
+ tail = (f" Ask GET /api/v1/grid/{table}/related with no 'via' to see every relation this "
1198
+ f"account is offered, then send the 'path' of the one you want, one edge key per "
1199
+ f"hop")
1200
+ return {'code': REFUSAL_UNKNOWN_VIA, 'path': keys, 'candidates': cands,
1201
+ 'message': (f"'{table}' offers no relation reached by {named} to this account, and "
1202
+ f"nothing was removed by permission on the way, so this is an edge that "
1203
+ f"does not exist rather than one you may not see." + tail)}
1204
+
1205
+
1206
+ def _paths_of(entries):
1207
+ """The set of `path` tuples in an enumeration. The unit the diff is computed in."""
1208
+ return {tuple(str(k) for k in (e.get('path') or ())) for e in (entries or ())}
1209
+
1210
+
1211
+ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for=None,
1212
+ depth=MAX_DEPTH, entries=None, open_entries=None,
1213
+ open_fields=None, open_fields_for=None):
1214
+ """WHY `pick_path` came back None, as one of C3's four answers. `{code, message, table?, hop?}`.
1215
+
1216
+ ⛔⛔ NEVER RAISES AND NEVER RETURNS None. A diagnosis that can itself fail is the fail-open bug
1217
+ `routes_grid._may_open` warns about: every branch below ends in a real bag carrying a code from
1218
+ `REFUSAL_CODES` and a sentence.
1219
+
1220
+ THE DIFF, and it is the whole function:
1221
+
1222
+ 1. the FILTERED enumeration (`may_open` + the caller's field wall). If `keys` resolves in it,
1223
+ the path is permitted end to end and reaches nothing: `no_related_rows`.
1224
+ 2. the UNFILTERED enumeration (no `may_open`, and the widest field list the caller can offer).
1225
+ If `keys` does not resolve THERE either, the edge genuinely does not exist and no wall was
1226
+ involved: `unknown_via`, with the candidates, their join columns and the retry strings.
1227
+ 3. otherwise the wall removed it, and WHICH hop it removed is read off the PREFIXES: the
1228
+ shortest prefix of `keys` present unfiltered and absent filtered is the hop that went. If
1229
+ a table on that hop is closed, `forbidden_table` NAMING it; if every table is open, the
1230
+ field wall took the edge and it is `hop_filtered` NAMING the hop.
1231
+
1232
+ ⭐ STEP 3 IS WHY THE INTERMEDIATE IS COVERED WITHOUT A SPECIAL CASE. The intermediate of a
1233
+ two-hop path IS the target of the one-hop prefix, so a closed intermediate makes prefix `[k1]`
1234
+ the first absent one and its target is the intermediate. R13's *"read on EVERY table in the
1235
+ path, intermediate included"* falls out of the prefix walk rather than being asserted beside it.
1236
+
1237
+ ⛔ `open_fields` / `open_fields_for` MUST BE A SUPERSET of `fields` / `fields_for`, or step 2
1238
+ can call a wall-removed path unknown. The route builds them as a UNION for exactly that reason;
1239
+ when they are omitted the diff runs on the table wall alone, which is correct and narrower.
1240
+ ⛔ `entries` / `open_entries` ARE AN OPTIMISATION ONLY. The route has already paid for both
1241
+ enumerations; a gate hands neither and gets the same answer computed from scratch.
1242
+ """
1243
+ keys = [str(k) for k in (keys or ())]
1244
+ table = str(table or '')
1245
+ if entries is None:
1246
+ entries = related_paths(table, fields=fields, defs=defs, depth=depth,
1247
+ may_open=may_open, fields_for=fields_for)
1248
+ if pick_path(entries, keys) is not None:
1249
+ return {'code': REFUSAL_NO_ROWS, 'path': keys,
1250
+ 'message': no_related_rows_refusal(table, keys)}
1251
+ if open_entries is None:
1252
+ open_entries = related_paths(
1253
+ table, fields=(open_fields if open_fields is not None else fields), defs=defs,
1254
+ depth=depth, may_open=None,
1255
+ fields_for=(open_fields_for if open_fields_for is not None else fields_for))
1256
+ if pick_path(open_entries, keys) is None:
1257
+ return unknown_via_answer(table, keys, candidate_paths(table, entries, defs, fields_for))
1258
+
1259
+ have = _paths_of(entries)
1260
+ for idx in range(len(keys)):
1261
+ prefix = tuple(keys[:idx + 1])
1262
+ if prefix in have:
1263
+ continue
1264
+ step = pick_path(open_entries, list(prefix))
1265
+ blocked = str((step or {}).get('target') or '')
1266
+ if blocked and may_open is not None and not may_open(blocked):
1267
+ return {'code': REFUSAL_FORBIDDEN_TABLE, 'path': keys, 'table': blocked,
1268
+ 'hop': keys[idx],
1269
+ 'message': forbidden_table_refusal(table, keys, blocked, keys[idx])}
1270
+ return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': keys[idx],
1271
+ 'message': hop_filtered_refusal(table, keys, keys[idx])}
1272
+ # ⚠ EVERY PREFIX SURVIVED AND THE WHOLE DID NOT. Only reachable if two enumerations disagree
1273
+ # about a path they agree about every prefix of; the last hop is the honest thing to name.
1274
+ return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': (keys[-1] if keys else ''),
1275
+ 'message': hop_filtered_refusal(table, keys, keys[-1] if keys else '')}
1276
+
1277
+
1278
+ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None,
1279
+ entries=None, open_entries=None, open_fields=None, open_fields_for=None):
1280
+ """THE LISTING ANNOTATION: what the wall removed from this table's enumeration, BY NAME.
1281
+
1282
+ `[{code, message, path, table?, hop?}]`, a SIBLING of the served list and never a replacement
1283
+ for it.
1284
+
1285
+ ⛔⛔ AN EMPTY LIST IS NEVER AN ACCEPTABLE ANSWER TO A PERMISSION-FILTERED TRAVERSAL, AND THIS
1286
+ IS THE HALF OF C3 THAT IS EASIEST TO MISS. A 400 on a pin covers the request that named ONE
1287
+ path; the LISTING answers 200 with a shorter array, and a shorter array is exactly the silent
1288
+ empty PostgREST and Odoo both hand out. So a path the wall removed is reported here rather than
1289
+ omitted. ⛔ AND A 403 FOR THE WHOLE STRIP WOULD BE EQUALLY WRONG: the other tabs are
1290
+ legitimately visible, and refusing them all to explain one is a wall with a bug in it.
1291
+
1292
+ ⭐ COLLAPSED ON `(code, table, hop)`, ON PURPOSE. One closed table can remove a dozen paths; a
1293
+ dozen identical refusals naming it would be a longer answer carrying no more information, and
1294
+ on a heavily restricted account it would enumerate most of the tenant on every request. R13
1295
+ asks for the table and the hop to be NAMED, which each distinct row does exactly once.
1296
+
1297
+ ⭐ AND WHEN NOTHING WAS REMOVED AND NOTHING IS THERE, `no_related_rows` IS SAID OUT LOUD. That
1298
+ is the case `{related: []}` alone cannot express, and it is R13's first answer.
1299
+ """
1300
+ table = str(table or '')
1301
+ if entries is None:
1302
+ entries = related_paths(table, fields=fields, defs=defs, depth=depth,
1303
+ may_open=may_open, fields_for=fields_for)
1304
+ if open_entries is None:
1305
+ open_entries = related_paths(
1306
+ table, fields=(open_fields if open_fields is not None else fields), defs=defs,
1307
+ depth=depth, may_open=None,
1308
+ fields_for=(open_fields_for if open_fields_for is not None else fields_for))
1309
+ have = _paths_of(entries)
1310
+ out, seen = [], set()
1311
+ for entry in open_entries:
1312
+ path = [str(k) for k in (entry.get('path') or ())]
1313
+ if not path or tuple(path) in have:
1314
+ continue
1315
+ got = diagnose_path(table, path, fields=fields, defs=defs, may_open=may_open,
1316
+ fields_for=fields_for, depth=depth, entries=entries,
1317
+ open_entries=open_entries)
1318
+ if got.get('code') == REFUSAL_UNKNOWN_VIA:
1319
+ continue # cannot happen: `path` came out of `open_entries` itself
1320
+ ident = (got.get('code'), got.get('table') or '', got.get('hop') or '')
1321
+ if ident in seen:
1322
+ continue
1323
+ seen.add(ident)
1324
+ out.append(got)
1325
+ if not entries and not out:
1326
+ out.append({'code': REFUSAL_NO_ROWS, 'path': [],
1327
+ 'message': no_related_rows_refusal(table)})
1328
+ return out
platform/core/schema_overlay.py CHANGED
@@ -15,6 +15,14 @@ empty overlay must reproduce the contract byte-for-byte, and nothing here may ev
15
  `order` for every field, because a UI that PATCHes back what it read would then pin every column
16
  forever and "absent means inherit" would be gone permanently.
17
 
 
 
 
 
 
 
 
 
18
  R12 — v1 is SHOW/HIDE, RELABEL, REORDER ONLY. No field typing, no hard delete, no endpoint
19
  browser. That wall lives in `clean_patch()` and NOWHERE else, so there is exactly one place to
20
  read when the question is "what may an overlay do".
@@ -329,6 +337,101 @@ def ignored_hides(database_key, fields, overlay_doc, locked=None):
329
  if k in locked_set and isinstance(ov.get(k), dict) and ov[k].get("hidden") is True]
330
 
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  # =================================================================================================
333
  # THE STORE SEAM — injectable, so nothing here has to reach a real store
334
  # =================================================================================================
 
15
  `order` for every field, because a UI that PATCHes back what it read would then pin every column
16
  forever and "absent means inherit" would be gone permanently.
17
 
18
+ ⭐ W53-T27 (R9 / C2) — THE SAME IDEA ONE LEVEL UP, FOR A DATABASE'S OWN NAME, AND WITHOUT A
19
+ SECOND DOCUMENT. `database_label()` / `merge_database_labels()` at the bottom of this file answer
20
+ "what is this database called for this tenant" with the rule the whole module already runs on:
21
+ shipped default, per-tenant override, ABSENT MEANS INHERIT. They are PURE and they touch no
22
+ store, because the database-name override does NOT live in this document — see the section header
23
+ above them for where it does live and why putting it here would have built the very thing R9
24
+ forbids.
25
+
26
  R12 — v1 is SHOW/HIDE, RELABEL, REORDER ONLY. No field typing, no hard delete, no endpoint
27
  browser. That wall lives in `clean_patch()` and NOWHERE else, so there is exactly one place to
28
  read when the question is "what may an overlay do".
 
337
  if k in locked_set and isinstance(ov.get(k), dict) and ov[k].get("hidden") is True]
338
 
339
 
340
+ # =================================================================================================
341
+ # DATABASE LABELS — the same rule, one level up (W53-T27; R9, contract C2)
342
+ #
343
+ # ⛔⛔ THE TRAP FIRST, BECAUSE THE RULING'S OWN PROSE WALKS INTO IT. R9 says a tenant's override of
344
+ # a DATABASE's name "lives in core/schema_overlay.py". It does not, and building it here would
345
+ # have created the second override store R9's own sentence forbids. This document is FIELD scoped
346
+ # — `{database_key: {field_key: {hidden,label,order}}}` — and has no slot for a database's own
347
+ # name; meanwhile this app has renamed a `ut_*` database from the navigation rail since wave 19
348
+ # through the tenant-wide `nav_meta` bucket (`routes_nav.save_nav_meta`). Two documents would mean
349
+ # one workspace holding two names for one database, with the rail and the connector's Databases
350
+ # tab each correct about their own.
351
+ #
352
+ # ⭐ WHAT THIS MODULE OWNS OF THE QUESTION IS THE IDEA, NOT THE STORAGE: a shipped default, a
353
+ # per-tenant override, and ABSENT MEANS INHERIT. These three functions are the ONE place that idea
354
+ # is spelled for a database's NAME, so a route, a gate and a future second connector cannot each
355
+ # decide separately what a blank override means. They are pure: no store, no tenant, no mutation.
356
+ # `routes_connectors` holds the tenant's store handle and calls them.
357
+ #
358
+ # ⛔ AND THAT PURITY IS WHY A RE-SYNC CANNOT CLOBBER AN OVERRIDE (R9's second clause). A connector
359
+ # re-sync (`odoo_relational.apply_plan`) rewrites table DEFINITIONS; it never reaches `nav_meta`
360
+ # and it never calls these. The guarantee is structural rather than remembered.
361
+ # =================================================================================================
362
+
363
+ def database_label(default_label, override):
364
+ """What ONE database is called for this tenant: its override, else our shipped default.
365
+
366
+ ⛔ BLANK IS ABSENT. `""`, `" "`, `None` and a non-string all mean INHERIT, exactly as an
367
+ absent field key does in `merge()`. Treating an empty string as a name is how "clearing the
368
+ override falls back to the default" quietly becomes "clearing the override empties the row",
369
+ and a nameless database is a row nobody can talk about.
370
+ """
371
+ if isinstance(override, str) and override.strip():
372
+ return override.strip()
373
+ return default_label if isinstance(default_label, str) else ""
374
+
375
+
376
+ def override_name(entry):
377
+ """The override carried by one stored entry, normalised to a string. `""` means none.
378
+
379
+ Accepts BOTH shapes a caller has: the stored `{"name": ..., "icon": ...}` record (this module
380
+ has no opinion about the icon and never touches it) and a plain string from a flattened map.
381
+ Anything else is absent, because a malformed record must read as "no override" rather than as
382
+ a name nobody can see the source of.
383
+ """
384
+ if isinstance(entry, str):
385
+ return entry.strip()
386
+ if isinstance(entry, dict):
387
+ name = entry.get("name")
388
+ if isinstance(name, str):
389
+ return name.strip()
390
+ return ""
391
+
392
+
393
+ def merge_database_labels(rows, overrides):
394
+ """C2's shipped defaults plus this tenant's overrides, over a list of database rows.
395
+
396
+ Returns NEW row dicts in the caller's order, each carrying THREE separate facts rather than
397
+ one blended one::
398
+
399
+ defaultLabel our shipped default (C2's `label`), never overwritten by an override
400
+ override this tenant's own name, or "" when none is set
401
+ label what to CALL it today: `database_label` of the two
402
+
403
+ ⛔ THE THREE ARE KEPT APART ON PURPOSE. A payload serving only the effective name cannot tell
404
+ a reader whether they are looking at our default or at their own rename, and a screen that
405
+ cannot tell those apart cannot honestly offer to go back to the default.
406
+
407
+ ⛔ NOTHING IS MUTATED, for the reason in this file's header one level down: the rows a route
408
+ hands in are built from MODULE GLOBALS (`odoo_relational.TABLES`, the Amazon label map), so
409
+ relabelling one in place would leak one tenant's rename into the next tenant's response with
410
+ no error anywhere.
411
+
412
+ ⛔ AND `native` IS NEVER TOUCHED. It is the vendor's own identifier for the table; no tenant
413
+ may edit it (C2), so no function here writes it. A row that arrives without one keeps
414
+ whatever it had.
415
+ """
416
+ ov = overrides if isinstance(overrides, dict) else {}
417
+ out = []
418
+ for row in rows or ():
419
+ if not isinstance(row, dict):
420
+ continue
421
+ new = dict(row)
422
+ default = new.get("defaultLabel")
423
+ if not (isinstance(default, str) and default.strip()):
424
+ default = new.get("label")
425
+ default = default if isinstance(default, str) else ""
426
+ key = new.get("key")
427
+ override = override_name(ov.get(key) if isinstance(key, str) else None)
428
+ new["defaultLabel"] = default
429
+ new["override"] = override
430
+ new["label"] = database_label(default, override)
431
+ out.append(new)
432
+ return out
433
+
434
+
435
  # =================================================================================================
436
  # THE STORE SEAM — injectable, so nothing here has to reach a real store
437
  # =================================================================================================
platform/core/user_tables.py CHANGED
@@ -1841,6 +1841,30 @@ def _clean_metric(raw):
1841
  #: ~3 KB — comfortably inside a text cell, and `MAX_ROWS` bounds the absolute worst case anyway.
1842
  LINK_MAX_IDS = 500
1843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1844
  # Link picker filters are schema, not a View selection: the leaf below constrains candidate rows
1845
  # in the linked table. `sourceField` is explicitly a field on the current record; absence means
1846
  # this is the static/literal form. Keeping the two shapes disjoint prevents a dynamic picker
@@ -2157,6 +2181,50 @@ def _clean_link(raw):
2157
  # than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
2158
  # with the control still on screen.
2159
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2160
  # A semantic hop is meaningful only on a derived link with a first join to travel from.
2161
  # Its absence preserves the historical one-hop bag byte-for-byte.
2162
  if raw.get('via') is not None:
 
1841
  #: ~3 KB — comfortably inside a text cell, and `MAX_ROWS` bounds the absolute worst case anyway.
1842
  LINK_MAX_IDS = 500
1843
 
1844
+ #: ⭐⭐ W53-T40 / STANDING RULE 1 — HOW MANY DISTINCT TARGET RECORDS ONE **TWO-HOP** LINK MAY
1845
+ #: RESOLVE FOR ONE SOURCE ROW, and it is a DIFFERENT QUANTITY from `LINK_MAX_IDS` above.
1846
+ #:
1847
+ #: ⛔ THE TWO ARE NOT INTERCHANGEABLE AND CONFLATING THEM WOULD BE A SILENT TRUNCATION.
1848
+ #: `LINK_MAX_IDS` is a DISPLAY cap: `relation_cells` slices the CELL to it and every rollup keeps
1849
+ #: reading the uncapped `resolved` set, so a 900-record relation shows 500 ids and still averages
1850
+ #: over 900. This one bounds `resolved` ITSELF, because the second hop is where the fan-out is:
1851
+ #: `ut_odoo_order_lines` holds 256,593 in-scope rows (256,502 with a `product_id`), and a walk
1852
+ #: with no ceiling is a cross product of one customer's basket against the catalogue.
1853
+ #:
1854
+ #: ⛔ SO IT MUST BE REPORTED, NEVER SILENTLY APPLIED — standing rule 1's SECOND sentence, which is
1855
+ #: the half that gets dropped. `automation_engine.relation_cells` counts the rows that reach this
1856
+ #: ceiling and emits a `limit_report`-shaped entry naming the route, the count and the fix. A
1857
+ #: rollup folded over a capped set is a number about a subset, and nothing on screen would say so.
1858
+ #:
1859
+ #: ⚠ 5,000 IS CHOSEN AGAINST THE POPULATION, NOT PICKED FOR ROUNDNESS. The shipped two-hop
1860
+ #: (`customer_data -> ut_odoo_order_lines -> product_data`) can never exceed the catalogue, which
1861
+ #: is 5,875 active products, so in production this ceiling is a backstop rather than a filter and
1862
+ #: the report should stay silent. It bounds the pathological case: a bridge grain and a target
1863
+ #: grain that are both large would otherwise build one python list per source row with no bound
1864
+ #: at all. It is deliberately ABOVE `LINK_MAX_IDS`, so on any ordinary relation the display cap
1865
+ #: bites first and the rollups still fold everything.
1866
+ LINK_THROUGH_MAX_IDS = 5000
1867
+
1868
  # Link picker filters are schema, not a View selection: the leaf below constrains candidate rows
1869
  # in the linked table. `sourceField` is explicitly a field on the current record; absence means
1870
  # this is the static/literal form. Keeping the two shapes disjoint prevents a dynamic picker
 
2181
  # than dropped: a bag half of which is silently ignored is [[wrong-parent-not-broken-control]]
2182
  # with the control still on screen.
2183
  return None
2184
+ # ⭐⭐ W53-T40 (a) — `through`: THE SECOND TABLE HOP, AND THE THREE KEYS THAT NAME EVERY LEG.
2185
+ #
2186
+ # ⛔ IT IS NOT `via`, AND READING IT AS ONE IS THE EASY MISTAKE HERE. `_clean_via` above
2187
+ # demands topic/source_dim/target_dim/target_key/scope_key/measure and refuses unless the dims
2188
+ # belong to a semantic TOPIC; it is a governed measure route, `automation_engine` reads a link
2189
+ # bag's `via` ZERO times, and it is not a table hop at all. `through` names a DATABASE the
2190
+ # join travels across, and it is validated the way `table` is — by `is_linkable_target`, the
2191
+ # one predicate that decides whether anything can resolve rows under a key.
2192
+ #
2193
+ # ⛔ A `through` WITH NO `on` CONFIGURES NOTHING, and it is refused for the identical reason
2194
+ # the bare `from` two lines up is: there is no second hop to make when the far side of it is
2195
+ # unnamed, and a bag half of which is silently ignored is the worst of the three outcomes.
2196
+ #
2197
+ # ⭐⭐ WHY THREE KEYS AND NOT ONE. A two-hop join has FOUR join columns, and the existing
2198
+ # vocabulary already names two of them: `from` (on the SOURCE) and `on` (on the TARGET). The
2199
+ # missing two are the bridge's own ends, and they are genuinely different columns — on the
2200
+ # shipped route `customer_data.pid` meets `ut_odoo_order_lines.partner_id` (Odoo's
2201
+ # `order_partner_id`) while `ut_odoo_order_lines.product_id` meets `product_data.product_id`.
2202
+ # ⛔ NEITHER IS DEFAULTED FROM THE OTHER SIDE'S SPELLING. A bridge whose inbound column
2203
+ # happened to share the source's name would make the convention look right and would join two
2204
+ # unrelated columns the first time it did not, with a fully populated cell and nothing red.
2205
+ # Both are REQUIRED, so an incomplete route is refused at this door rather than guessed at the
2206
+ # compute one.
2207
+ #
2208
+ # ⚠ THE BRIDGE MAY NOT BE THE TARGET. `through == table` is a ONE-hop join wearing two names:
2209
+ # it would resolve, it would look configured, and its second hop would be the identity.
2210
+ if raw.get('through') is not None:
2211
+ if 'on' not in out:
2212
+ return None
2213
+ through = _field_key(raw.get('through'))
2214
+ if not is_linkable_target(through) or through == table:
2215
+ return None
2216
+ hop_in = _field_key(raw.get('throughOn'))
2217
+ hop_out = _field_key(raw.get('throughTo'))
2218
+ if not hop_in or not hop_out:
2219
+ return None
2220
+ out['through'] = through
2221
+ out['throughOn'] = hop_in
2222
+ out['throughTo'] = hop_out
2223
+ elif raw.get('throughOn') is not None or raw.get('throughTo') is not None:
2224
+ # ⛔ HALF A ROUTE IS NOT A ROUTE. A bridge column with no bridge names a hop across a
2225
+ # database nobody declared; dropping the two keys would store a bag that reads as an
2226
+ # ordinary one-hop link while its author believed they had configured two.
2227
+ return None
2228
  # A semantic hop is meaningful only on a derived link with a first join to travel from.
2229
  # Its absence preserves the historical one-hop bag byte-for-byte.
2230
  if raw.get('via') is not None:
platform/modules/sheet.py CHANGED
@@ -31,10 +31,11 @@ The only SQL this module writes itself is the aggregate wrapper and the spec's o
31
 
32
  from __future__ import annotations
33
 
 
34
  import re
35
 
36
- #: C2's aggregate vocabulary. `metric_key` is the other arm of that union and is resolved by the
37
- #: route against the same catalogue `routes_query.py::_compatible_metric_dtos` serves.
38
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
39
 
40
  #: ⭐ R9's PERIOD (wave 51, W51-T21). The three units a bound cell can be pinned to, and the month
@@ -69,6 +70,28 @@ REFUSALS = {
69
  "aggregate_unknown": "{subject} is not an aggregate this cell can compute.",
70
  "field_unknown": "{subject} is not a column on this database.",
71
  "period_invalid": "{subject} is not a period this cell can use.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # ── C5's two sharing refusals (wave 51, W51-T25) ──────────────────────────────────────────
73
  #
74
  # ⭐⭐ THEY LIVE HERE, WITH C2's, BECAUSE THIS DICT IS THE ONE PLACE A SHEET REFUSAL IS
@@ -87,13 +110,22 @@ REFUSALS = {
87
 
88
 
89
  class SheetRefusal(Exception):
90
- """A named refusal. `code` is C2 vocabulary; `message` is the sentence a person reads."""
91
 
92
- def __init__(self, code, subject=""):
 
 
 
 
 
 
 
93
  template = REFUSALS.get(code) or "{subject} could not be answered."
94
  self.code = code
95
  self.subject = str(subject or "")
96
- self.message = template.format(subject=self.subject or "this database")
 
 
97
  super().__init__(self.message)
98
 
99
 
@@ -108,6 +140,17 @@ def clean_period(raw):
108
  ⚠ `locked` STORES ONLY TRUE. R9's lock means "a copy of this cell keeps this period"; an
109
  unlocked period is what every cell already is, so storing `false` would make a cell that was
110
  locked and unlocked compare unequal to the cell it started as.
 
 
 
 
 
 
 
 
 
 
 
111
  """
112
  if not isinstance(raw, dict):
113
  return None
@@ -140,7 +183,260 @@ def clean_period(raw):
140
  if raw.get("window") is not None and "unit" not in out and "start" not in out:
141
  out["window"] = raw["window"]
142
 
143
- return out or None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
 
146
  def clean_on_drag(raw):
 
31
 
32
  from __future__ import annotations
33
 
34
+ import datetime
35
  import re
36
 
37
+ #: C2's aggregate vocabulary. `metric_key` is the other arm of that union, and W53-T13 answers it
38
+ #: by NAME rather than leaving it dead: see `metric_key_refusal` and its refusal's own note.
39
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
40
 
41
  #: ⭐ R9's PERIOD (wave 51, W51-T21). The three units a bound cell can be pinned to, and the month
 
70
  "aggregate_unknown": "{subject} is not an aggregate this cell can compute.",
71
  "field_unknown": "{subject} is not a column on this database.",
72
  "period_invalid": "{subject} is not a period this cell can use.",
73
+ # ── W53-T13's two refusals, and the reason each of them is NOT `field_unknown` ────────────
74
+ #
75
+ # ⛔⛔ `field_unknown`'s sentence is "{subject} is not a column on this database", and for a
76
+ # column that IS on this database and simply cannot be TOTALLED here, that sentence is false.
77
+ # A false refusal sends the reader to the column picker to look for a column that is already
78
+ # in front of them. So the two situations are two codes: one says the column is not here, the
79
+ # other says it is here and names what stops it being folded into one number.
80
+ #
81
+ # ⚠ `{detail}` IS SUPPLIED BY `aggregate_refusal`, NEVER BY THE CALL SITE. The reason is a
82
+ # property of the COLUMN (a browser-computed formula, a rollup that folds to text, a text
83
+ # column somebody asked to sum), and computing it in one place is what stops three doors
84
+ # wording the same fact three ways ([[one-question-two-normalizers]]).
85
+ "field_not_aggregable": "{subject} cannot be totalled on this database, because {detail}",
86
+ # ⭐ C2's OTHER aggregate arm. `{metric_key}` names a number measured over a whole SET, and a
87
+ # set measure is not additive: summing a per-record average or a percentage over the rows this
88
+ # cell scopes produces a confident wrong number. The Metric COLUMN path answers the same
89
+ # question honestly, per database and per period, which is exactly ruling R7, so the sentence
90
+ # sends the reader there rather than stopping at "no".
91
+ "metric_key_unsupported": "{subject} is measured over a whole set of records rather than "
92
+ "stored on each one, so this cell cannot total it directly. Add a "
93
+ "Metric column for it on this database, then point this cell at "
94
+ "that column.",
95
  # ── C5's two sharing refusals (wave 51, W51-T25) ──────────────────────────────────────────
96
  #
97
  # ⭐⭐ THEY LIVE HERE, WITH C2's, BECAUSE THIS DICT IS THE ONE PLACE A SHEET REFUSAL IS
 
110
 
111
 
112
  class SheetRefusal(Exception):
113
+ """A named refusal. `code` is C2 vocabulary; `message` is the sentence a person reads.
114
 
115
+ ⚠ `detail` IS OPTIONAL AND EVERY EXISTING CALL SITE IS UNAFFECTED (W53-T13). `str.format`
116
+ ignores a keyword no template names, so a template written before this argument existed is
117
+ formatted exactly as it was; only `field_not_aggregable` reads `{detail}` today, and that
118
+ sentence is unreadable without it, which is why the reason travels WITH the code rather than
119
+ being pasted at each door.
120
+ """
121
+
122
+ def __init__(self, code, subject="", detail=""):
123
  template = REFUSALS.get(code) or "{subject} could not be answered."
124
  self.code = code
125
  self.subject = str(subject or "")
126
+ self.detail = str(detail or "")
127
+ self.message = template.format(subject=self.subject or "this database",
128
+ detail=self.detail)
129
  super().__init__(self.message)
130
 
131
 
 
140
  ⚠ `locked` STORES ONLY TRUE. R9's lock means "a copy of this cell keeps this period"; an
141
  unlocked period is what every cell already is, so storing `false` would make a cell that was
142
  locked and unlocked compare unequal to the cell it started as.
143
+
144
+ ⛔⛔ D-660 (W53-T16) - A PERIOD THAT NAMES NO WINDOW IS NOT A PERIOD, AND STORING ONE IS THE
145
+ WHOLE DEFECT. `{"unit": "month"}` with no `start`, or `{"locked": true}` on its own, used to be
146
+ stored as a period. `period_window` reads either as None, so the CELL still answered all time -
147
+ but the binding now carried a `period` key, and the editor reading it back sees a declared unit,
148
+ fills the missing start with TODAY'S MONTH and shows it as a chosen period. The next save then
149
+ stamps `{unit: "month", start: <this month>}` over a cell nobody meant to narrow: an all-time
150
+ total silently becomes this month's, which is exactly what D-660 names. So a period must name a
151
+ window - a `start`, the legacy `window`, or R14's `ref` - or it is dropped and the cell stays
152
+ all time. ⚠ THE ORDER MATTERS: an unknown unit or a malformed start is still REFUSED BY NAME
153
+ above, because a wrong period and an absent one are different answers.
154
  """
155
  if not isinstance(raw, dict):
156
  return None
 
183
  if raw.get("window") is not None and "unit" not in out and "start" not in out:
184
  out["window"] = raw["window"]
185
 
186
+ #: ⛔ D-660: see the docstring. A unit on its own, a lock on its own, or the empty dict names no
187
+ #: window, so it is not a period and the cell keeps its all-time answer.
188
+ if not ({"start", "window", "ref"} & set(out)):
189
+ return None
190
+ return out
191
+
192
+
193
+ #: ⭐ R7's PERIOD ARITHMETIC, spelled once. How many months each unit spans, which is the whole
194
+ #: difference between the three: a period is always named by the month it OPENS on (`clean_period`
195
+ #: enforces the `YYYY-MM` spelling for that reason), so the unit only decides where it closes.
196
+ PERIOD_MONTHS = {"month": 1, "quarter": 3, "year": 12}
197
+
198
+
199
+ def period_window(period):
200
+ """⭐⭐ R7 — a bound cell's PERIOD as a `harness.windows` CUSTOM window, or None.
201
+
202
+ OWNER, R7: *"must also be bounded by date time lookup"*. A Metric column carries its OWN
203
+ declared window (`{kind: "ltm"}` on both of the two live ones), and that window is what
204
+ `core/measure_resolve.py::column_values` resolves it at. So a cell that says "August 2026" over
205
+ a Metric column would otherwise print a TWELVE MONTH number under a one-month label: an answer
206
+ WIDER than the binding asked for, with nothing on screen saying so, which is standing rule 1's
207
+ second sentence turned into a defect. This function is what lets the route re-resolve that
208
+ column at the window the cell actually names.
209
+
210
+ ⛔ THE SHAPE IS `{"kind": "custom", "from": ..., "to": ...}` BECAUSE THAT IS THE ONE SHAPE
211
+ `harness/windows.py::normalize` ACCEPTS FOR AN ABSOLUTE RANGE, and `windows.resolve` turns it
212
+ into the INCLUSIVE pair every measure query is built from. Inventing a `{unit, start}` window
213
+ kind would be a second date vocabulary beside the one the whole harness already speaks
214
+ ([[date-window-vocabulary]]).
215
+
216
+ ⛔ `to` IS THE LAST DAY OF THE PERIOD, NOT THE FIRST DAY OF THE NEXT ONE. `windows.resolve`'s
217
+ contract is a pair of INCLUSIVE ISO dates, so an exclusive end would silently pull the whole of
218
+ the following month into a monthly cell. It is computed as "the day before the month after the
219
+ period", never as a 28/30/31 table, so February and a leap year need no special case.
220
+
221
+ ⚠ A `{window}` PERIOD (the wave-49 spelling `clean_period` still round trips) IS RETURNED AS
222
+ IT STANDS. It already IS a window spec; normalising it here would be this module's second
223
+ opinion about a vocabulary `harness/windows.py` owns, and `normalize` refuses anything it does
224
+ not recognise anyway.
225
+
226
+ ⚠ None MEANS "THIS CELL NAMES NO PERIOD", and the caller must read it as "leave every Metric
227
+ column at its own declared window", never as "all time". A period that carries only a `ref`
228
+ (R14's cell reference) resolves to None here too: the reference is read by the A1 layer before
229
+ a query is built, and guessing a window for an unresolved reference would answer a question
230
+ nobody asked.
231
+ """
232
+ if not isinstance(period, dict):
233
+ return None
234
+ if period.get("window") is not None:
235
+ return period["window"]
236
+ start = str(period.get("start") or "").strip()
237
+ if not _PERIOD_START.match(start):
238
+ return None
239
+ unit = str(period.get("unit") or "month").strip().lower()
240
+ months = PERIOD_MONTHS.get(unit)
241
+ if not months:
242
+ return None
243
+ year, month = int(start[:4]), int(start[5:7])
244
+ # The exclusive month AFTER the period, as a flat month index, then one day back off its first.
245
+ after = (year * 12 + (month - 1)) + months
246
+ end_year, end_month = divmod(after, 12)
247
+ last = datetime.date(end_year, end_month + 1, 1) - datetime.timedelta(days=1)
248
+ return {"kind": "custom", "from": f"{start}-01", "to": last.isoformat()}
249
+
250
+
251
+ #: The column types `harness/filter_sql.py::NUMERIC_TYPES` compiles as numbers AND
252
+ #: `odoo_relational._REGISTRY_COL_TYPE` materialises as a number. The two lists have to agree or a
253
+ #: column is stored as one thing and compared as another.
254
+ MIRROR_NUMERIC_TYPES = ("currency", "int", "pct")
255
+
256
+ #: ⭐ THE COMPUTED KINDS THE MIRROR HAS TO BE TOLD ABOUT. `_REGISTRY_COL_TYPE` maps the ordinary
257
+ #: field types and falls back to VARCHAR for everything else, so a `metric` or `rating` column
258
+ #: would be materialised as TEXT and then either refuse to SUM or compare as a string. Both hold a
259
+ #: number, so both are declared as one.
260
+ MIRROR_TYPE = {"metric": "currency", "rating": "int"}
261
+
262
+ #: The rollup folds that produce a NUMBER. The rest of `core/user_tables.py::ROLLUP_FNS`
263
+ #: (`latest`, `and`/`or`/`xor`, `concatenate`, `arrayjoin`, `arraycompact`, `arrayunique`) folds
264
+ #: its linked rows into text or a boolean, and a SUM over those is not a smaller number, it is a
265
+ #: DuckDB binder error or a meaningless one.
266
+ NUMERIC_ROLLUP_FNS = ("sum", "average", "stdev", "min", "max", "count", "counta", "countall")
267
+
268
+
269
+ def _rollup_is_numeric(field):
270
+ """True when a `rollup` column's fold produces a number."""
271
+ bag = (field or {}).get("rollup")
272
+ if not isinstance(bag, dict):
273
+ return False
274
+ # A SOURCE-backed rollup names a semantic TOPIC and a METRIC KEY (`core/user_tables.py::
275
+ # _clean_rollup`), and a metric is a number by construction.
276
+ if isinstance(bag.get("source"), dict):
277
+ return True
278
+ return str(bag.get("fn") or "").strip().lower() in NUMERIC_ROLLUP_FNS
279
+
280
+
281
+ def mirror_field_type(field):
282
+ """The type ONE tenant column should be materialised and compiled as on the mirror.
283
+
284
+ ⭐⭐ W53-T13 — THIS IS WHAT MAKES A TENANT'S OWN COLUMN A REAL SQL COLUMN RATHER THAN TEXT.
285
+ `odoo_relational.registry_grid_spec` reads a field's `type` twice: once to pick the temp
286
+ table's column type through `_REGISTRY_COL_TYPE`, and once (through
287
+ `routes_odoo_tables._filter_columns`) to tell `filter_sql` whether the column is a number. A
288
+ `metric`, `rating` or numeric `rollup` column is missing from BOTH tables, so it lands as
289
+ VARCHAR and compares as a string: `sum` over it is a binder error and `>` over it sorts
290
+ "1000" before "9".
291
+
292
+ ⛔ IT CHANGES NOTHING A PERSON SEES. This type is the SQL shape of one throwaway temp column;
293
+ the field's own declared type still governs the grid, the field editor and every format. A
294
+ numeric rollup is declared `currency` here only because `currency` is what `filter_sql`
295
+ already means by "a number", not because the column is money.
296
+
297
+ ⚠ `formula` IS DELIBERATELY LEFT ALONE. Its value is worked out in the BROWSER for each row
298
+ and is never stored, so declaring it a number would materialise a column of NULLs and hand
299
+ back a confident zero. `aggregate_refusal` names it instead.
300
+ """
301
+ kind = str((field or {}).get("type") or "").strip()
302
+ if kind == "rollup":
303
+ return "currency" if _rollup_is_numeric(field) else "text"
304
+ return MIRROR_TYPE.get(kind, kind or "text")
305
+
306
+
307
+ def mirror_fields(fields):
308
+ """`fields`, with every column's type replaced by the one the mirror can hold. Copies."""
309
+ return [dict(f, type=mirror_field_type(f)) for f in (fields or []) if isinstance(f, dict)]
310
+
311
+
312
+ def aggregate_refusal(aggregate, field):
313
+ """The named refusal for an aggregate this database cannot answer, or None.
314
+
315
+ ⛔⛔ IT RUNS BEFORE THE SQL IS BUILT, WHICH IS THE ONLY PLACE IT CAN RUN HONESTLY. Once every
316
+ tenant column is a real column of the materialised table (W53-T13's whole point), a `sum` over
317
+ a text column reaches DuckDB and comes back as a binder error, i.e. a 500 with no sentence, and
318
+ a `sum` over a browser-computed formula column reaches DuckDB and comes back as 0 — which is
319
+ worse, because nothing anywhere looks wrong.
320
+
321
+ ⚠ `min` AND `max` ARE NOT REFUSED ON A TEXT COLUMN. They are defined over any ordered type in
322
+ SQL and answer a real question there ("the earliest code", "the last status"); only `sum` and
323
+ `avg` need a number. Refusing them would take away an answer this database can give.
324
+
325
+ ⚠ `field` IS THE ASSEMBLY'S OWN FIELD DICT, not the binding's text. An unknown key is None
326
+ here and stays `aggregate_sql`'s `field_unknown` to report, because "not a column on this
327
+ database" is then exactly true.
328
+ """
329
+ if not isinstance(field, dict):
330
+ return None
331
+ fn = str((aggregate or {}).get("fn") or "").strip().lower()
332
+ if fn in ("", "count"):
333
+ return None
334
+ label = str(field.get("label") or field.get("key") or "That column")
335
+ kind = str(field.get("type") or "").strip()
336
+ if kind == "formula":
337
+ return SheetRefusal(
338
+ "field_not_aggregable", label,
339
+ "its value is worked out in the browser for each row and is never stored, so this "
340
+ "database holds nothing to add up. Total the columns the formula reads instead.")
341
+ if fn not in ("sum", "avg"):
342
+ return None
343
+ if kind == "rollup" and not _rollup_is_numeric(field):
344
+ return SheetRefusal(
345
+ "field_not_aggregable", label,
346
+ "it folds its linked records into text rather than into a number. Change the rollup "
347
+ "to a numeric fold, or total the linked column directly.")
348
+ if mirror_field_type(field) not in MIRROR_NUMERIC_TYPES:
349
+ return SheetRefusal(
350
+ "field_not_aggregable", label,
351
+ "it holds text rather than a number. Count the records instead, or pick a number "
352
+ "column.")
353
+ return None
354
+
355
+
356
+ def metric_key_refusal(aggregate):
357
+ """The named refusal for C2's `{metric_key}` arm, or None when the binding is not that arm.
358
+
359
+ ⛔⛔ IT IS ANSWERED RATHER THAN LEFT TO FALL THROUGH, and that is the whole of W53-T13's (d).
360
+ `clean_binding` accepts `{metric_key}` and nothing downstream ever resolved it, so it reached
361
+ `aggregate_sql` with no `fn` and no `field` and died as `field_unknown` with an EMPTY subject:
362
+ "That column is not a column on this database." Measured on the running app for
363
+ `{"metric_key": "revenue"}`. That sentence names nothing and is not even true.
364
+
365
+ ⭐ WHY IT REFUSES RATHER THAN RESOLVES, and this is standing rule 9 read forwards. A metric is
366
+ measured over a SET: `harness/measure_filter.py::resolve_series`' own docstring records the
367
+ additivity law it obeys, that a non-additive measure (an average, a percentage) is computed at
368
+ POOL grain and never folded from per-record answers. A bare metric key carries no aggregate
369
+ and no window, so resolving it here would mean choosing both, and choosing `sum` would print a
370
+ wrong number for every ratio metric in the catalogue with nothing to notice. The Metric COLUMN
371
+ path answers the same question with the aggregate and the window both DECLARED, per database,
372
+ which is precisely what R7 asked for, so the sentence sends the reader one step sideways
373
+ rather than stopping them.
374
+ """
375
+ key = str((aggregate or {}).get("metric_key") or "").strip()
376
+ if not key:
377
+ return None
378
+ return SheetRefusal("metric_key_unsupported", key)
379
+
380
+
381
+ def period_limits(period, aggregate, field, bounded_keys=(), depends=()):
382
+ """The `limits` rows for a PERIOD that did not narrow the number (R7, standing rule 1).
383
+
384
+ ⛔⛔ A PERIOD THAT DOES NOTHING MUST SAY SO. A cell labelled "August 2026" over a stored column
385
+ counts every record the filter selects, in every month there has ever been. The number is not
386
+ wrong for the query that ran; it is wider than the query the person wrote, and this repo's rule
387
+ is that the widening travels WITH the value rather than being left for someone to notice.
388
+
389
+ ⛔⛔ AND THE MIRROR OF THAT RULE IS JUST AS BINDING: A PERIOD THAT DID SOMETHING MUST NOT
390
+ CLAIM IT DID NOTHING. `depends` is every column the binding reads, the FILTER's included, and
391
+ it is here because the first version of this function looked at the aggregate's own column
392
+ alone. Measured on the running app: `count` over the filter `Sales the last 12 months > 100000`
393
+ answered 1 with no period and 0 for August 2026 - the period plainly bit, through the filter -
394
+ and this function still reported that it had been ignored. A false widening report is not a
395
+ harmless extra sentence; it teaches a reader to stop believing the true ones.
396
+
397
+ ⚠ `bounded_keys` IS WHAT THE ROUTE ACTUALLY RE-RESOLVED at this period, never what it hoped to.
398
+ A Metric column that failed to resolve at the requested window is NOT in that set, so it is
399
+ reported here as well as by its own row: a cell whose Metric fell back to blank has not been
400
+ bounded either.
401
+ """
402
+ if not period:
403
+ return []
404
+ fn = str((aggregate or {}).get("fn") or "").strip().lower()
405
+ key = str((aggregate or {}).get("field") or "").strip()
406
+ read = set(depends or ())
407
+ if key:
408
+ read.add(key)
409
+ if read & set(bounded_keys or ()):
410
+ return []
411
+ subject = (str((field or {}).get("label") or key) if key
412
+ else ("This count" if fn == "count" else "This cell"))
413
+ return [{
414
+ "subject": subject,
415
+ "effect": "period_ignored",
416
+ "cause": "this cell names a period, and the column it totals holds one stored value per "
417
+ "record rather than a measurement over time, so the period does not narrow it "
418
+ "and this number covers every record the filter selects",
419
+ "recommendation": "point the cell at a Metric column, which is measured over the period "
420
+ "you choose, or add a date condition to the cell's own filter",
421
+ }]
422
+
423
+
424
+ def metric_window_limit(subject, cause):
425
+ """The `limits` row for a Metric column that could NOT be resolved at the cell's period.
426
+
427
+ ⛔⛔ THE ALTERNATIVE IS THE DEFECT. Falling back to the column's own declared window would
428
+ answer twelve months under a one-month label and look completely ordinary. The column goes
429
+ BLANK and this row says which column, and why, and what to do about it.
430
+ """
431
+ return {
432
+ "subject": str(subject or "This metric column"),
433
+ "effect": "metric_not_bounded",
434
+ "cause": str(cause or "this column could not be measured over the period this cell "
435
+ "names, so it was left blank rather than answered over its own "
436
+ "wider window"),
437
+ "recommendation": "widen the cell's period, or open the database and check that the "
438
+ "metric behind this column can be measured over that range",
439
+ }
440
 
441
 
442
  def clean_on_drag(raw):
web/src/connectors/ConnectorModal.tsx CHANGED
@@ -53,7 +53,12 @@ import KeychainTab from "./KeychainTab";
53
  import MonidRunDialog from "./MonidRunDialog";
54
  import { SyncCadenceTab } from "./OdooConfig";
55
  import RelationshipDiagram from "./RelationshipDiagram";
56
- import { stateTone, tileText } from "./ConnectorsPage";
 
 
 
 
 
57
  import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage";
58
  import { parseRelationshipGraph } from "./ConnectorsPage";
59
  import "../styles/wave49/connectors.css";
@@ -171,7 +176,28 @@ export interface ConnectorDatabaseExclusion {
171
 
172
  export interface ConnectorDatabase {
173
  key: string;
 
 
 
 
174
  label: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  enabled: boolean;
176
  fields: ConnectorDatabaseField[];
177
  excluded: ConnectorDatabaseExclusion[];
@@ -286,7 +312,12 @@ function parseDatabases(raw: unknown): ConnectorDatabase[] {
286
  for (const item of raw) {
287
  const row = obj(item);
288
  const key = str(row.key).trim();
289
- const label = str(row.label).trim();
 
 
 
 
 
290
  // Same rule as `parseDirectory`: a database with no name is never rendered from its key,
291
  // which would put an internal identifier on screen.
292
  if (!key || !label) continue;
@@ -313,6 +344,13 @@ function parseDatabases(raw: unknown): ConnectorDatabase[] {
313
  out.push({
314
  key,
315
  label,
 
 
 
 
 
 
 
316
  enabled: row.enabled === true,
317
  fields,
318
  excluded,
@@ -528,11 +566,25 @@ export default function ConnectorModal({
528
  row,
529
  onClose,
530
  initialTab = "overview",
 
531
  }: {
532
  row: ConnectorRow;
533
  onClose: () => void;
534
  /** W49-T13 opens this modal on the Keychain tab from Settings; every other door opens Overview. */
535
  initialTab?: ConnectorTab;
 
 
 
 
 
 
 
 
 
 
 
 
 
536
  }) {
537
  const panelRef = useRef<HTMLDivElement>(null);
538
  const [tab, setTab] = useState<ConnectorTab>(initialTab);
@@ -662,7 +714,33 @@ export default function ConnectorModal({
662
  return <RelationshipDiagram connector={row.label} graph={load.detail.relationships} />;
663
  }
664
  if (tab === "cadence") {
665
- return <SyncCadenceTab row={row} />;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
  }
667
  return (
668
  <ConnectorOverviewPanel
@@ -670,7 +748,7 @@ export default function ConnectorModal({
670
  onPullReviews={canPull ? () => setPulling(true) : undefined}
671
  />
672
  );
673
- }, [canPull, load, reread, row, tab]);
674
 
675
  const status = load.phase === "ready" ? load.detail.overview.status : row.state;
676
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
 
53
  import MonidRunDialog from "./MonidRunDialog";
54
  import { SyncCadenceTab } from "./OdooConfig";
55
  import RelationshipDiagram from "./RelationshipDiagram";
56
+ // ⭐⭐ W53-T28 — `OdooSyncStatus` COMES FROM THE PAGE, and it is imported rather than copied for
57
+ // the same reason `stateTone` is: it is one component with one reading of Odoo's sync state, and
58
+ // `verify_ui`'s `one-enablement-door` leg pins its heading and its `.conn-db-link` to
59
+ // `ConnectorsPage.tsx`. It used to mount on the Odoo card inside `OdooManage`; that door is gone
60
+ // and this modal is where it renders now.
61
+ import { OdooSyncStatus, stateTone, tileText } from "./ConnectorsPage";
62
  import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage";
63
  import { parseRelationshipGraph } from "./ConnectorsPage";
64
  import "../styles/wave49/connectors.css";
 
176
 
177
  export interface ConnectorDatabase {
178
  key: string;
179
+ /**
180
+ * What this database is CALLED today: the tenant's override when there is one, our shipped
181
+ * default otherwise. Resolved on the server (`core/schema_overlay.database_label`), never here.
182
+ */
183
  label: string;
184
+ /**
185
+ * ⭐⭐ W53-T27 · R9 / C2 — THREE NAMES, THREE DIFFERENT FACTS, AND THE TAB SHOWS ALL THREE.
186
+ *
187
+ * `native` is the VENDOR's own identifier for the table (`res.partner`, or an Amazon report
188
+ * type). It is never editable by anybody: it is how the source names its own thing, and a
189
+ * workspace that could rewrite it would be describing a table that does not exist over there.
190
+ */
191
+ native: string;
192
+ /** OUR shipped default name (C2's `label`). It survives an override rather than being replaced,
193
+ * which is what lets the tab offer a way back to it. */
194
+ defaultLabel: string;
195
+ /** This tenant's own name, or `""` when none is set. Absent means inherit the default, and it
196
+ * is the SAME override the navigation rail's rename writes (R9), not a second one. */
197
+ override: string;
198
+ /** May THIS reader rename it? The server's own `may_open` answer, per row, because a control
199
+ * the write door would refuse is a button that always fails. */
200
+ canRename: boolean;
201
  enabled: boolean;
202
  fields: ConnectorDatabaseField[];
203
  excluded: ConnectorDatabaseExclusion[];
 
312
  for (const item of raw) {
313
  const row = obj(item);
314
  const key = str(row.key).trim();
315
+ // ⭐ W53-T27 — THE DEFAULT AND THE EFFECTIVE NAME EACH FALL BACK TO THE OTHER, and neither
316
+ // falls back to the KEY. A payload from a server that predates this ticket carries `label`
317
+ // alone, and the tab must then show that name in both columns rather than an empty cell or an
318
+ // internal identifier.
319
+ const defaultLabel = str(row.defaultLabel).trim() || str(row.label).trim();
320
+ const label = str(row.label).trim() || defaultLabel;
321
  // Same rule as `parseDirectory`: a database with no name is never rendered from its key,
322
  // which would put an internal identifier on screen.
323
  if (!key || !label) continue;
 
344
  out.push({
345
  key,
346
  label,
347
+ // ⛔ `native` IS NOT DEFAULTED TO ANYTHING. An absent one means the server could not name
348
+ // the source's own identifier for this table, and the tab says so; inventing the key or the
349
+ // label here would put OUR word on screen under the vendor's heading.
350
+ native: str(row.native).trim(),
351
+ defaultLabel,
352
+ override: str(row.override).trim(),
353
+ canRename: row.canRename === true,
354
  enabled: row.enabled === true,
355
  fields,
356
  excluded,
 
566
  row,
567
  onClose,
568
  initialTab = "overview",
569
+ onOpenDatabases,
570
  }: {
571
  row: ConnectorRow;
572
  onClose: () => void;
573
  /** W49-T13 opens this modal on the Keychain tab from Settings; every other door opens Overview. */
574
  initialTab?: ConnectorTab;
575
+ /**
576
+ * ⭐⭐ W53-T28 (instructions 22/23) — TOLD, NOT ASKED. The Sync cadence tab mounts
577
+ * `OdooSyncStatus`, whose "Manage fields in the Databases tab" link used to live on the card and
578
+ * be handed the page's own opener. Inside an already-mounted modal that indirection cannot work:
579
+ * `initialTab` is a `useState` INITIALIZER with no resync, so a page-driven jump would need a
580
+ * keyed remount, and a remount re-reads `/detail`, bounces focus off the trap, and goes silently
581
+ * dead the second time the link is used because the page's tab already reads "databases".
582
+ *
583
+ * So the modal moves its OWN tab and calls this afterwards. The page uses it to keep its record
584
+ * of the chosen tab in step with what is on screen, which is what its reset-on-close is clearing.
585
+ * ⚠ Optional: `SettingsModal` opens this on Keychain with no page-level tab state at all.
586
+ */
587
+ onOpenDatabases?: () => void;
588
  }) {
589
  const panelRef = useRef<HTMLDivElement>(null);
590
  const [tab, setTab] = useState<ConnectorTab>(initialTab);
 
714
  return <RelationshipDiagram connector={row.label} graph={load.detail.relationships} />;
715
  }
716
  if (tab === "cadence") {
717
+ /**
718
+ * ⭐⭐ W53-T28 — THE ODOO CARD'S SYNC PANEL LANDS HERE, ABOVE THE CADENCE CONTROLS.
719
+ *
720
+ * `OdooSyncStatus` reports (schedule, health, last run, errors) and links onward to field
721
+ * enablement; `SyncCadenceTab` sets (grids, cadence, server database, disconnect and
722
+ * reconnect). Neither duplicates the other, which is why the card's whole "Sync settings"
723
+ * door collapses into these two lines instead of needing anything built. Reading above
724
+ * setting is the order the card itself used.
725
+ *
726
+ * ⛔ ODOO ONLY. `OdooSyncStatus` calls `getOdooStatus`/`getOdooSchema` unconditionally, so
727
+ * mounting it for Amazon or Meta Ads would print Odoo's health under another connector's
728
+ * name. Those two keep `SyncCadenceTab`'s honest "no cadence control here yet" sentence,
729
+ * which is the whole point of that component's degraded branch.
730
+ */
731
+ return (
732
+ <>
733
+ {row.key === "odoo" ? (
734
+ <OdooSyncStatus
735
+ onOpenDatabases={() => {
736
+ setTab("databases");
737
+ onOpenDatabases?.();
738
+ }}
739
+ />
740
+ ) : null}
741
+ <SyncCadenceTab row={row} />
742
+ </>
743
+ );
744
  }
745
  return (
746
  <ConnectorOverviewPanel
 
748
  onPullReviews={canPull ? () => setPulling(true) : undefined}
749
  />
750
  );
751
+ }, [canPull, load, onOpenDatabases, reread, row, tab]);
752
 
753
  const status = load.phase === "ready" ? load.detail.overview.status : row.state;
754
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
web/src/connectors/ConnectorsPage.tsx CHANGED
@@ -47,7 +47,13 @@ import DirectoryChips, {
47
  // have made the one openable catalogue card a 404. See `ConnectorCard` below for the suppression
48
  // that keeps it out of the modal path.
49
  import MonidRunDialog from "./MonidRunDialog";
50
- import OdooConfigPanel, { type OdooConfig } from "./OdooConfig";
 
 
 
 
 
 
51
  import {
52
  AutomationError,
53
  getOdooSchema,
@@ -162,6 +168,21 @@ export interface ConnectorRow {
162
  * Absent ⇒ business, which is what every connection stored before this wave actually is.
163
  */
164
  scope?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  /** What the admin will be asked for — shown where the decision is made, not in a tour. */
166
  hint?: string;
167
  /**
@@ -224,6 +245,13 @@ type Load =
224
  gaps: ConnectorGap[];
225
  /** W49-T18: the category rail, exactly as the server counted it. */
226
  chips: DirectoryCategory[];
 
 
 
 
 
 
 
227
  }
228
  | { phase: "error"; message: string };
229
 
@@ -325,6 +353,14 @@ export function parseDirectory(body: unknown): ConnectorRow[] {
325
  ...(str(c.startUrl) ? { startUrl: str(c.startUrl) } : {}),
326
  ...(str(c.note) ? { note: str(c.note) } : {}),
327
  ...(str(c.scope) ? { scope: str(c.scope) } : {}),
 
 
 
 
 
 
 
 
328
  ...(str(c.hint) ? { hint: str(c.hint) } : {}),
329
  ...(parsePlatforms(c.platforms).length
330
  ? { platforms: parsePlatforms(c.platforms) }
@@ -531,10 +567,18 @@ export default function ConnectorsPage({
531
  */
532
  const [openKey, setOpenKey] = useState("");
533
  /**
534
- * ⭐⭐ W49-T14 · O9 · R26 — WHICH TAB THE MODAL OPENS ON, and it exists because the modal is now
535
- * the ONE door to field enablement. The Odoo card used to carry its own "Field catalog" chip
536
- * row calling `setOdooFieldEnabled`, so the same setting had two doors that could disagree; the
537
- * chip row is deleted and its place carries a link into this tab instead.
 
 
 
 
 
 
 
 
538
  *
539
  * ⛔ AND IT IS RESET WHEN THE MODAL CLOSES, not by each opener. `ConnectorModal` reads
540
  * `initialTab` as a `useState` INITIALIZER with no resync, so the value simply rides the next
@@ -570,6 +614,21 @@ export default function ConnectorsPage({
570
  * spends money is closed.
571
  */
572
  const [canPull, setCanPull] = useState(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
 
574
  useEffect(() => {
575
  let dead = false;
@@ -579,7 +638,7 @@ export default function ConnectorsPage({
579
  credentials: CREDENTIALS,
580
  });
581
  const body = (await res.json().catch(() => null)) as
582
- | { error?: { message?: string } }
583
  | null;
584
  if (dead) return;
585
  if (!res.ok) {
@@ -594,6 +653,11 @@ export default function ConnectorsPage({
594
  rows: parseDirectory(body),
595
  gaps: parseGaps(body),
596
  chips: parseCategories(body),
 
 
 
 
 
597
  });
598
  } catch {
599
  if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
@@ -675,8 +739,44 @@ export default function ConnectorsPage({
675
  * for the company" here, because the two headings answer different questions about it.
676
  */
677
  const connectedRows = rows.filter((r) => r.state === "connected");
678
- const companyRows = connectedRows.filter((r) => r.scope !== "personal");
679
- const personalRows = connectedRows.filter((r) => r.scope === "personal");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
  // ⚠ Resolved against `allRows`, not the filtered list: typing in the search box while a modal is
681
  // open must not close the modal out from under the reader.
682
  const openRow = allRows.find((row) => row.key === openKey);
@@ -774,7 +874,48 @@ export default function ConnectorsPage({
774
  ⚠ SAME `ConnectorCard`, NOT A FORK — see the note on `companyRows`/`personalRows` above for
775
  why a card can appear here AND in the catalog tiers below.
776
  */}
777
- {companyRows.length > 0 ? (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
778
  <section className="conn-tier" aria-labelledby="conn-tier-company-heading">
779
  <h2 id="conn-tier-company-heading" className="conn-tier-heading">
780
  Connected for the company
@@ -786,17 +927,13 @@ export default function ConnectorsPage({
786
  row={row}
787
  onKeychain={onKeychain}
788
  onOpen={() => setOpenKey(row.key)}
789
- onOpenDatabases={() => {
790
- setOpenTab("databases");
791
- setOpenKey(row.key);
792
- }}
793
  onPullReviews={pullHandler(row)}
794
  />
795
  ))}
796
  </div>
797
  </section>
798
  ) : null}
799
- {personalRows.length > 0 ? (
800
  <section className="conn-tier" aria-labelledby="conn-tier-personal-heading">
801
  <h2 id="conn-tier-personal-heading" className="conn-tier-heading">
802
  Connected by you
@@ -808,10 +945,6 @@ export default function ConnectorsPage({
808
  row={row}
809
  onKeychain={onKeychain}
810
  onOpen={() => setOpenKey(row.key)}
811
- onOpenDatabases={() => {
812
- setOpenTab("databases");
813
- setOpenKey(row.key);
814
- }}
815
  onPullReviews={pullHandler(row)}
816
  />
817
  ))}
@@ -830,10 +963,6 @@ export default function ConnectorsPage({
830
  row={row}
831
  onKeychain={onKeychain}
832
  onOpen={() => setOpenKey(row.key)}
833
- onOpenDatabases={() => {
834
- setOpenTab("databases");
835
- setOpenKey(row.key);
836
- }}
837
  onPullReviews={pullHandler(row)}
838
  />
839
  ))}
@@ -852,10 +981,6 @@ export default function ConnectorsPage({
852
  row={row}
853
  onKeychain={onKeychain}
854
  onOpen={() => setOpenKey(row.key)}
855
- onOpenDatabases={() => {
856
- setOpenTab("databases");
857
- setOpenKey(row.key);
858
- }}
859
  onPullReviews={pullHandler(row)}
860
  />
861
  ))}
@@ -866,6 +991,15 @@ export default function ConnectorsPage({
866
  <ConnectorModal
867
  row={openRow}
868
  initialTab={openTab}
 
 
 
 
 
 
 
 
 
869
  onClose={() => {
870
  setOpenKey("");
871
  // ⛔⛔ THE RESET LIVES ON CLOSE, WHICH IS THE ONLY PLACE THAT CATCHES EVERY DOOR.
@@ -892,131 +1026,32 @@ export default function ConnectorsPage({
892
  );
893
  }
894
 
895
- /**
896
- * ⭐⭐ WAVE 32 (C2 / R9 / R10 / R11) — THE ODOO CARD'S ACTION, and the ONE place this page fetches
897
- * anything besides the directory itself.
 
 
 
 
898
  *
899
- * ⛔ THE FETCHING IS HERE AND THE RENDERING IS IN `OdooConfigPanel`, deliberately: that panel is
900
- * pure, so a static render can paint it with a real payload and the ticket's visual `done-when`
901
- * is provable without a browser session. A component that loaded its own data would be a spinner
902
- * in every shot — the exact reason wave 30 lifted `ConnectorCard` out of the page.
 
 
 
 
 
 
 
903
  *
904
- * ⚠ EVERY WRITE RE-READS THE SERVER'S ANSWER rather than patching local state. The server clamps
905
- * a cadence, rewrites a credential and reports what it did in `notes` — a client that optimistically
906
- * updated its own copy would show the value the user asked for while the server held a different
907
- * one, which is precisely the silent-clamp failure R6's second sentence exists to stop.
 
908
  */
909
- function OdooManage({
910
- connected,
911
- onKeychain,
912
- onOpenDatabases,
913
- }: {
914
- connected: boolean;
915
- onKeychain: () => void;
916
- /** ⭐ W49-T14 · O9 — the page's door into the modal's Databases tab, passed straight through to
917
- * `OdooSyncStatus`. Optional so the static proof sheets keep compiling. */
918
- onOpenDatabases?: () => void;
919
- }) {
920
- const [open, setOpen] = useState(false);
921
- const [cfg, setCfg] = useState<OdooConfig | null>(null);
922
- const [busy, setBusy] = useState(false);
923
- const [err, setErr] = useState("");
924
-
925
- const load = async () => {
926
- setBusy(true);
927
- try {
928
- const res = await fetch(`${API_V1}/admin/connectors/odoo/config`, {
929
- credentials: CREDENTIALS,
930
- });
931
- const body = (await res.json().catch(() => null)) as
932
- | (OdooConfig & { error?: { message?: string } })
933
- | null;
934
- if (!res.ok) {
935
- setErr(body?.error?.message || `The server answered ${res.status}.`);
936
- setCfg(null);
937
- } else {
938
- setErr("");
939
- setCfg(body);
940
- }
941
- } catch {
942
- setErr("Cannot reach the server.");
943
- }
944
- setBusy(false);
945
- };
946
-
947
- const send = async (path: string, method: string, payload?: unknown) => {
948
- setBusy(true);
949
- try {
950
- const res = await fetch(`${API_V1}${path}`, {
951
- method,
952
- credentials: CREDENTIALS,
953
- headers: { "content-type": "application/json" },
954
- ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
955
- });
956
- const body = (await res.json().catch(() => null)) as
957
- | (OdooConfig & { error?: { message?: string } })
958
- | null;
959
- if (!res.ok) setErr(body?.error?.message || `The server answered ${res.status}.`);
960
- else setErr("");
961
- } catch {
962
- setErr("Cannot reach the server.");
963
- }
964
- setBusy(false);
965
- await load();
966
- };
967
-
968
- return (
969
- <>
970
- {/* ⛔ W52-T03 — RENAMED FROM "Manage keys"/"Add keys". Instruction 23's done-when reserves
971
- those two words for inside the connector popup only; this button does something wider
972
- than key management (grids, sync cadence, server database, disconnect/reconnect), so the
973
- rename is also the more accurate label, not merely a dodge of the banned words. */}
974
- <button
975
- type="button"
976
- className="conn-card-go"
977
- onClick={() => {
978
- const next = !open;
979
- setOpen(next);
980
- if (next && !cfg) void load();
981
- }}
982
- >
983
- {connected ? "Sync settings" : "Set up sync"}
984
- </button>
985
- {open ? (
986
- <>
987
- {err ? <p className="conn-card-meta">{err}</p> : null}
988
- <OdooSyncStatus onOpenDatabases={onOpenDatabases} />
989
- {cfg ? (
990
- <OdooConfigPanel
991
- cfg={cfg}
992
- busy={busy}
993
- onToggleGrid={(key, enabled) =>
994
- void send("/admin/connectors/odoo/config", "PUT", {
995
- grids: { [key]: enabled },
996
- })
997
- }
998
- onSyncEvery={(every) =>
999
- void send("/admin/connectors/odoo/config", "PUT", { syncEvery: every })
1000
- }
1001
- onServerDb={(db) =>
1002
- void send("/admin/connectors/odoo/config", "PUT", { serverDb: db })
1003
- }
1004
- onDisconnect={() => void send("/admin/connectors/odoo/disconnect", "POST")}
1005
- onReconnect={() => void send("/admin/connectors/odoo/reconnect", "POST")}
1006
- />
1007
- ) : busy ? (
1008
- <p className="conn-card-meta">Loading…</p>
1009
- ) : null}
1010
- {/* The KEY itself is still the Keychains room's business — this panel configures the
1011
- connector and mints no second credential path. */}
1012
- <button type="button" className="conn-card-go" onClick={onKeychain}>
1013
- {connected ? "Replace the key" : "Add a key"}
1014
- </button>
1015
- </>
1016
- ) : null}
1017
- </>
1018
- );
1019
- }
1020
 
1021
  /**
1022
  * ⭐⭐ W49-T14 · O9 · R26 — THE SYNC PANEL REPORTS; IT NO LONGER SETS.
@@ -1039,6 +1074,18 @@ function OdooManage({
1039
  *
1040
  * ⚠ NO CALLBACK MEANS NO LINK. `_conn_shot.tsx` and any other static painter pass nothing, and a
1041
  * link with no modal behind it is an affordance that cannot work (R8).
 
 
 
 
 
 
 
 
 
 
 
 
1042
  */
1043
  export function OdooSyncStatus({ onOpenDatabases }: { onOpenDatabases?: () => void } = {}) {
1044
  const [status, setStatus] = useState<OdooStatus | null>(null);
@@ -1147,6 +1194,44 @@ export function markKey(key: string): string {
1147
  return key.startsWith("md_") ? key.slice(3) : key;
1148
  }
1149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150
  function ConnectorCardIdentity({ row }: { row: ConnectorRow }) {
1151
  const mark = brandForConnector(markKey(row.key), 22);
1152
  return (
@@ -1196,7 +1281,6 @@ export function ConnectorCard({
1196
  row,
1197
  onKeychain,
1198
  onOpen,
1199
- onOpenDatabases,
1200
  onPullReviews,
1201
  }: {
1202
  row: ConnectorRow;
@@ -1223,17 +1307,15 @@ export function ConnectorCard({
1223
  * 117 stay faded.
1224
  */
1225
  onPullReviews?: () => void;
1226
- /**
1227
- * ⭐⭐ W49-T14 · O9 · R26 — OPEN THE CONNECTOR MODAL ON ITS DATABASES TAB. The Odoo card's sync
1228
- * panel used to enable fields ITSELF, through a chip row wired to `setOdooFieldEnabled`; that
1229
- * made field enablement a setting with two doors, and R26 says the modal is the one door. The
1230
- * chip row is deleted and this prop is what its replacement link calls.
1231
- *
1232
- * ⚠ Optional for the same reason `onOpen` is: `_conn_shot.tsx` paints this card with neither,
1233
- * and a required prop would red `tsc` on a file this ticket does not own. A card handed no
1234
- * callback shows no link rather than a control that cannot work.
1235
  */
1236
- onOpenDatabases?: () => void;
1237
  }) {
1238
  /**
1239
  * ⭐⭐ THE CARD HAS NO DOOR, AND THAT IS THE CONDITION EVERY GUARD BELOW WANTS — not the
@@ -1383,29 +1465,20 @@ export function ConnectorCard({
1383
  {row.state === "reconnect" ? "Reconnect" : "Connect"}
1384
  </a>
1385
  ) : null}
1386
- {/* ⭐⭐ WAVE 32 items 6/11 (C2, R9/R10/R11) — ODOO'S SYNC PANEL OPENS THE
1387
- CONNECTOR, not the credential list. The owner clicked "Manage keys" and got a
1388
- list of keys: no server database, no choice of grids, no cadence, no way off.
1389
- ⚠ `onKeychain` stays reachable underneath: adding or replacing the KEY still
1390
- happens in the room that owns keys, and this panel does not mint a second
1391
- credential path (C11's rule, which is what lets this page be chrome).
1392
- ⛔⛔ W52-T03 — THE PLAIN "Manage keys"/"Add keys" BUTTON THAT STOOD HERE FOR EVERY
1393
- OTHER KEYCHAIN CARD IS DELETED. Instruction 23's done-when says those two words
1394
- live inside the connector popup and nowhere else; `KeychainTab` (mounted in
1395
- `ConnectorModal`'s Keychain tab) already adds, tests and deletes the same
1396
- credential this button opened, so nothing is lost — a reader reaches it through
1397
- the new Settings button below instead of a second door on the card itself.
1398
- Odoo's OWN panel survives (see `OdooManage`'s own header for why: it configures
1399
- grids, cadence and disconnect/reconnect, none of which the modal's Databases tab
1400
- does yet), but its trigger no longer wears the words "Manage keys"/"Add keys" —
1401
- see the rename inside `OdooManage` below. */}
1402
- {!doorless && row.manage === "keychain" && row.key === "odoo" ? (
1403
- <OdooManage
1404
- connected={connected}
1405
- onKeychain={onKeychain}
1406
- onOpenDatabases={doorless ? undefined : onOpenDatabases}
1407
- />
1408
- ) : null}
1409
  {/* ⭐⭐ WAVE 33 · D-204 — THE MEMBER'S OWN DOOR. Same room, different promise: this
1410
  card connects an account that is YOURS, which is why the word is not "Manage
1411
  keys". It appears only for connectors whose credential may be personal — the
@@ -1442,6 +1515,10 @@ export function ConnectorCard({
1442
  aria-label={`Open settings for ${row.label}`}
1443
  onClick={() => onOpen?.()}
1444
  >
 
 
 
 
1445
  Settings
1446
  </button>
1447
  ) : null}
 
47
  // have made the one openable catalogue card a 404. See `ConnectorCard` below for the suppression
48
  // that keeps it out of the modal path.
49
  import MonidRunDialog from "./MonidRunDialog";
50
+ // ⛔⛔ `OdooConfigPanel` AND `type OdooConfig` WERE IMPORTED HERE AND ARE DELETED BY W53-T28.
51
+ // They were `OdooManage`'s imports, and `OdooManage` — the card's own "Sync settings"/"Set up
52
+ // sync" door — is gone with them (see its tombstone below `ConnectorsPage`). The panel itself is
53
+ // not retired: `SyncCadenceTab` in `connectors/OdooConfig.tsx` already fetches the same
54
+ // `/admin/connectors/odoo/config` payload and renders the same `OdooConfigPanel`, and it is
55
+ // mounted by `ConnectorModal`'s Sync cadence tab. Re-importing either name here would be the
56
+ // second door this ticket exists to close.
57
  import {
58
  AutomationError,
59
  getOdooSchema,
 
168
  * Absent ⇒ business, which is what every connection stored before this wave actually is.
169
  */
170
  scope?: string;
171
+ /**
172
+ * ⭐⭐ W53-T29 · RULING R6 — WHICH SCOPES THIS SOURCE MAY EVER CARRY, e.g. `["business"]` for
173
+ * Odoo and both words for Gmail. The server's one declaration of it is
174
+ * `routes_keychain.allowed_scopes`, built on the same `TENANT_WIDE_TYPES` tuple its refusals
175
+ * are built on, and every directory row is stamped with it.
176
+ *
177
+ * ⛔ IT IS THE SOURCE'S RULE, NOT THIS READER'S PERMISSION — that is `canBusiness` on the
178
+ * payload. The Company / Mine toggle needs both: eligibility decides which side a card COULD
179
+ * appear on, permission decides whether the Company side exists for this reader at all.
180
+ *
181
+ * Absent (an older server) ⇒ treated as both, which is the honest degradation: this field only
182
+ * ever NARROWS a tier, so a missing one leaves the page exactly as it was before this ticket
183
+ * rather than hiding a connection the reader really holds.
184
+ */
185
+ allowedScopes?: string[];
186
  /** What the admin will be asked for — shown where the decision is made, not in a tour. */
187
  hint?: string;
188
  /**
 
245
  gaps: ConnectorGap[];
246
  /** W49-T18: the category rail, exactly as the server counted it. */
247
  chips: DirectoryCategory[];
248
+ /**
249
+ * ⭐⭐ W53-T29 · RULING R6 — MAY THIS READER SEE THE COMPANY SIDE AT ALL. The server's
250
+ * `bool(session.admin)`, under the name `routes_keychain` has used for it since W32-T11.
251
+ * ⚠ FALSE UNLESS THE PAYLOAD SAYS OTHERWISE, and false on any failure: the safe direction
252
+ * for an admin-only control is closed, the same discipline `canPull` keeps below.
253
+ */
254
+ canBusiness: boolean;
255
  }
256
  | { phase: "error"; message: string };
257
 
 
353
  ...(str(c.startUrl) ? { startUrl: str(c.startUrl) } : {}),
354
  ...(str(c.note) ? { note: str(c.note) } : {}),
355
  ...(str(c.scope) ? { scope: str(c.scope) } : {}),
356
+ // ⭐⭐ W53-T29 / R6 — the source's declared eligibility, COPIED off the wire like every
357
+ // other field here. `parseCategoryTags` is this file's one reader for a list of words from
358
+ // the server (strings only, blanks dropped, deduped); a second identical parser would be a
359
+ // second place for "read a string list" to go wrong. An empty or absent list yields no key
360
+ // at all, which the tier filters read as "unrestricted".
361
+ ...(parseCategoryTags(c.allowedScopes).length
362
+ ? { allowedScopes: parseCategoryTags(c.allowedScopes) }
363
+ : {}),
364
  ...(str(c.hint) ? { hint: str(c.hint) } : {}),
365
  ...(parsePlatforms(c.platforms).length
366
  ? { platforms: parsePlatforms(c.platforms) }
 
567
  */
568
  const [openKey, setOpenKey] = useState("");
569
  /**
570
+ * ⭐⭐ W49-T14 · O9 · R26 — WHICH TAB A FRESH MOUNT OF THE MODAL OPENS ON, and it exists because
571
+ * the modal is the ONE door to field enablement. The Odoo card used to carry its own "Field
572
+ * catalog" chip row calling `setOdooFieldEnabled`, so the same setting had two doors that could
573
+ * disagree; the chip row is deleted and its place carries a link into this tab instead.
574
+ *
575
+ * ⭐⭐ W53-T28 — THAT LINK NOW LIVES INSIDE THE MODAL, and this state is what keeps the page's
576
+ * record of it honest. `OdooSyncStatus` (which carries "Manage fields in the Databases tab") is
577
+ * mounted in `ConnectorModal`'s Sync cadence tab rather than on the card, so the JUMP itself is
578
+ * the modal's own `setTab` �� it is already on screen and moves instantly, with no remount and no
579
+ * second `/detail` read. What the modal hands BACK is `onOpenDatabases`, and this is the setter
580
+ * behind it: the page's idea of the chosen tab must not go stale under an open modal, or the
581
+ * reset below would be clearing a value that no longer describes anything.
582
  *
583
  * ⛔ AND IT IS RESET WHEN THE MODAL CLOSES, not by each opener. `ConnectorModal` reads
584
  * `initialTab` as a `useState` INITIALIZER with no resync, so the value simply rides the next
 
614
  * spends money is closed.
615
  */
616
  const [canPull, setCanPull] = useState(false);
617
+ /**
618
+ * ⭐⭐ W53-T29 · OWNER RULING R6 — WHICH SIDE OF THE COMPANY / MINE TOGGLE IS SHOWING, HELD IN
619
+ * THE SERVER'S OWN TWO WORDS.
620
+ *
621
+ * ⛔ `business` / `personal` RATHER THAN `company` / `mine`, and that is the whole discipline of
622
+ * this ticket. `routes_keychain.py::SCOPES` already names these two ideas and every row on the
623
+ * wire is filed by them; a second client-only pair of words for the same split would be one
624
+ * rename away from a tier that filters on a word nothing sends. "Company" and "Mine" are the
625
+ * ruling's LABELS, which is a copy decision, and they live in the buttons below and nowhere
626
+ * else. Read as a string for the same reason `state` is (the wave-9 law).
627
+ *
628
+ * ⚠ MEANINGLESS FOR A NON-ADMIN, who never sees the control that changes it: their view is
629
+ * decided structurally below, not by this value.
630
+ */
631
+ const [scopeTier, setScopeTier] = useState("business");
632
 
633
  useEffect(() => {
634
  let dead = false;
 
638
  credentials: CREDENTIALS,
639
  });
640
  const body = (await res.json().catch(() => null)) as
641
+ | { error?: { message?: string }; canBusiness?: unknown }
642
  | null;
643
  if (dead) return;
644
  if (!res.ok) {
 
653
  rows: parseDirectory(body),
654
  gaps: parseGaps(body),
655
  chips: parseCategories(body),
656
+ // ⭐⭐ W53-T29 / R6 — a LITERAL `true` is permission and anything else is not. An older
657
+ // server sends nothing here and this reader gets no Company side, which is the safe way
658
+ // round: the toggle appearing for a member would be the ruling broken, while a missing
659
+ // toggle for an admin is a page that still lists every connection they have.
660
+ canBusiness: (body as { canBusiness?: unknown } | null)?.canBusiness === true,
661
  });
662
  } catch {
663
  if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
 
739
  * for the company" here, because the two headings answer different questions about it.
740
  */
741
  const connectedRows = rows.filter((r) => r.state === "connected");
742
+ /**
743
+ * ⭐⭐ W53-T29 · OWNER RULING R6 — TWO QUESTIONS PER CARD, AND BOTH ARE ASKED.
744
+ *
745
+ * `row.scope` is what this connection WAS STORED AS; `row.allowedScopes` is what its SOURCE may
746
+ * ever be (`routes_keychain.allowed_scopes`, derived from the same `TENANT_WIDE_TYPES` tuple the
747
+ * server's refusals are derived from). A tier needs both: without the second, one stray or
748
+ * legacy `scope` value would put Odoo under Mine, and Odoo is the credential this whole
749
+ * workspace's databases are read through.
750
+ *
751
+ * ⚠ IT ONLY EVER NARROWS. A row that carries no `allowedScopes` (an older server) is treated as
752
+ * unrestricted, so the worst an absent declaration can do is leave the page as it was.
753
+ */
754
+ const eligible = (row: ConnectorRow, scope: string) =>
755
+ !row.allowedScopes || row.allowedScopes.includes(scope);
756
+ const companyRows = connectedRows.filter(
757
+ (r) => r.scope !== "personal" && eligible(r, "business"),
758
+ );
759
+ const personalRows = connectedRows.filter(
760
+ (r) => r.scope === "personal" && eligible(r, "personal"),
761
+ );
762
+ /**
763
+ * ⭐⭐ W53-T29 · OWNER RULING R6 — THE NON-ADMIN CASE IS STRUCTURAL, NOT A HIDDEN BUTTON.
764
+ *
765
+ * R6, verbatim: *"A non-admin does not see the Company side at all; the toggle itself is hidden
766
+ * for them."* So `showCompany` cannot be reached without `canBusiness` and `showPersonal` is
767
+ * unconditionally true without it: a member sees their own connections and no toggle, and no
768
+ * sequence of clicks, stale state or hot reload can produce a Company section for them, because
769
+ * there is no state in which one renders. Hiding a control is not a permission check, which is
770
+ * why the SERVER refuses a member's business-scoped create as well
771
+ * (`routes_keychain.add_key` -> 403 `not_admin`).
772
+ *
773
+ * ⚠ THE TOGGLE NEEDS SOMETHING TO TOGGLE. With no connected card at all it renders nothing
774
+ * rather than two chips over an empty page, the same rule the tier headings already keep.
775
+ */
776
+ const canBusiness = load.phase === "ready" && load.canBusiness;
777
+ const showCompany = canBusiness && scopeTier !== "personal";
778
+ const showPersonal = !canBusiness || scopeTier === "personal";
779
+ const showScopeToggle = canBusiness && connectedRows.length > 0;
780
  // ⚠ Resolved against `allRows`, not the filtered list: typing in the search box while a modal is
781
  // open must not close the modal out from under the reader.
782
  const openRow = allRows.find((row) => row.key === openKey);
 
874
  ⚠ SAME `ConnectorCard`, NOT A FORK — see the note on `companyRows`/`personalRows` above for
875
  why a card can appear here AND in the catalog tiers below.
876
  */}
877
+ {/*
878
+ ⭐⭐ W53-T29 · OWNER RULING R6 — THE COMPANY / MINE TOGGLE, AND ONLY AN ADMIN HAS ONE.
879
+
880
+ ⛔ THE SAME CONTROL SHAPE THE CATEGORY RAIL ALREADY USES (`conn-chips` / `conn-chip` /
881
+ `is-on`, styled in `styles/wave49/connectors.css`). DESIGN.md §4: a filter rail keeps one
882
+ control shape, and this ticket ships no stylesheet, so a class invented here would render
883
+ as unstyled native chrome.
884
+ ⛔ REAL BUTTONS, NOT A DIV. `aria-pressed` carries the selected state to a screen reader
885
+ and `type="button"` keeps it off any form; the visible word IS the accessible name, which
886
+ is why neither carries an `aria-label` that would say something else.
887
+ */}
888
+ {showScopeToggle ? (
889
+ <div className="conn-chips" role="group" aria-label="Which connections to show">
890
+ <button
891
+ type="button"
892
+ className={"conn-chip" + (showCompany ? " is-on" : "")}
893
+ aria-pressed={showCompany}
894
+ onClick={() => setScopeTier("business")}
895
+ >
896
+ <span className="conn-chip-name">Company</span>
897
+ </button>
898
+ <button
899
+ type="button"
900
+ className={"conn-chip" + (showCompany ? "" : " is-on")}
901
+ aria-pressed={!showCompany}
902
+ onClick={() => setScopeTier("personal")}
903
+ >
904
+ <span className="conn-chip-name">Mine</span>
905
+ </button>
906
+ </div>
907
+ ) : null}
908
+ {/* ONE line and the way out, the same shape the empty grid above already uses: a side of
909
+ the toggle with nothing on it must say so, or the reader reads the silence as a page
910
+ that failed to load. */}
911
+ {showScopeToggle && (showCompany ? companyRows.length === 0 : personalRows.length === 0) ? (
912
+ <p className="conn-note">
913
+ {showCompany
914
+ ? "No connection is shared with the whole company yet."
915
+ : "You have no personal connections yet."}
916
+ </p>
917
+ ) : null}
918
+ {showCompany && companyRows.length > 0 ? (
919
  <section className="conn-tier" aria-labelledby="conn-tier-company-heading">
920
  <h2 id="conn-tier-company-heading" className="conn-tier-heading">
921
  Connected for the company
 
927
  row={row}
928
  onKeychain={onKeychain}
929
  onOpen={() => setOpenKey(row.key)}
 
 
 
 
930
  onPullReviews={pullHandler(row)}
931
  />
932
  ))}
933
  </div>
934
  </section>
935
  ) : null}
936
+ {showPersonal && personalRows.length > 0 ? (
937
  <section className="conn-tier" aria-labelledby="conn-tier-personal-heading">
938
  <h2 id="conn-tier-personal-heading" className="conn-tier-heading">
939
  Connected by you
 
945
  row={row}
946
  onKeychain={onKeychain}
947
  onOpen={() => setOpenKey(row.key)}
 
 
 
 
948
  onPullReviews={pullHandler(row)}
949
  />
950
  ))}
 
963
  row={row}
964
  onKeychain={onKeychain}
965
  onOpen={() => setOpenKey(row.key)}
 
 
 
 
966
  onPullReviews={pullHandler(row)}
967
  />
968
  ))}
 
981
  row={row}
982
  onKeychain={onKeychain}
983
  onOpen={() => setOpenKey(row.key)}
 
 
 
 
984
  onPullReviews={pullHandler(row)}
985
  />
986
  ))}
 
991
  <ConnectorModal
992
  row={openRow}
993
  initialTab={openTab}
994
+ /* ⭐⭐ W53-T28 — THE MODAL REPORTS, THE PAGE RECORDS. The "Manage fields in the
995
+ Databases tab" link moved off the card and into the modal's own Sync cadence tab
996
+ (instr 22/23: one action per card), so the modal moves its own tab with `setTab` and
997
+ this callback is how the page learns which tab was chosen while it was open. It is
998
+ deliberately NOT the mechanism: routing the jump through `initialTab` would need a
999
+ keyed remount, which re-reads `/detail`, drops focus back onto the card for a frame
1000
+ and — worse — silently does nothing the second time the same link is used, because
1001
+ `openTab` would already hold "databases". */
1002
+ onOpenDatabases={() => setOpenTab("databases")}
1003
  onClose={() => {
1004
  setOpenKey("");
1005
  // ⛔⛔ THE RESET LIVES ON CLOSE, WHICH IS THE ONLY PLACE THAT CATCHES EVERY DOOR.
 
1026
  );
1027
  }
1028
 
1029
+ /*
1030
+ * ⛔⛔ `OdooManage` STOOD HERE AND IS DELETED BY W53-T28 (instructions 22/23). It was the ODOO
1031
+ * CARD'S OWN ACTION: a "Sync settings"/"Set up sync" button that expanded in place to reveal
1032
+ * `OdooSyncStatus`, `OdooConfigPanel` (grids, sync cadence, server database, disconnect and
1033
+ * reconnect) and a second button reading "Replace the key"/"Add a key". Three controls on a card
1034
+ * that already carried the full-width "Settings" button W52-T03 gave it, which is the "one button
1035
+ * per card" defect the owner is looking at.
1036
  *
1037
+ * ⭐ NOTHING IT DID WAS REBUILT, AND THAT IS WHY THE DELETION IS SAFE RATHER THAN BRAVE:
1038
+ * · the fetch and the panel are ALREADY duplicated, line for line, by `SyncCadenceTab`
1039
+ * (`connectors/OdooConfig.tsx`) — same `GET/PUT /admin/connectors/odoo/config`, same
1040
+ * `disconnect`/`reconnect` posts, same five `OdooConfigPanel` callbacks — and W52-T04 mounted
1041
+ * that in `ConnectorModal`'s Sync cadence tab. This card was rendering a SECOND live copy of
1042
+ * one settings surface, which is the two-doors-can-disagree failure R26 already named once on
1043
+ * this page.
1044
+ * · "Replace the key"/"Add a key" opened the Keychains room; `KeychainTab` in the modal adds,
1045
+ * tests and deletes the same credential.
1046
+ * · `OdooSyncStatus` (below) is the only thing that had no home, and it moved rather than died:
1047
+ * `ConnectorModal` imports and mounts it above `SyncCadenceTab`.
1048
  *
1049
+ * ⛔ W52-T03's SURVIVAL CLAUSE IS RETIRED WITH IT. That ticket spared this panel because it
1050
+ * configured "grids, cadence and disconnect/reconnect, none of which the modal's Databases tab
1051
+ * does yet" — the Sync cadence tab, which did not exist when that sentence was written, now does
1052
+ * all three, so the reason is spent. ⛔ And the words "Manage keys"/"Add keys" it renamed away
1053
+ * from must not come back to a card under any label.
1054
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1055
 
1056
  /**
1057
  * ⭐⭐ W49-T14 · O9 · R26 — THE SYNC PANEL REPORTS; IT NO LONGER SETS.
 
1074
  *
1075
  * ⚠ NO CALLBACK MEANS NO LINK. `_conn_shot.tsx` and any other static painter pass nothing, and a
1076
  * link with no modal behind it is an affordance that cannot work (R8).
1077
+ *
1078
+ * ⭐⭐ W53-T28 — IT IS NO LONGER MOUNTED ON THE CARD, AND IT STILL LIVES IN THIS FILE. Those are
1079
+ * two separate facts and both are deliberate. `OdooManage` used to render this panel inside the
1080
+ * card's expanded "Sync settings" door; that door is deleted, and `ConnectorModal` now imports
1081
+ * this component and mounts it at the top of its Sync cadence tab, beside `SyncCadenceTab`. It is
1082
+ * NOT moved into that file, because this component is the connectors PAGE's reading of Odoo's own
1083
+ * sync state and it is exported for mounting, the same way `ConnectorCard` is; splitting it into
1084
+ * the modal would put one connector's status reader inside the generic modal shell.
1085
+ *
1086
+ * ⚠ THE CALLER DECIDES IT IS ODOO. This reads `getOdooStatus`/`getOdooSchema` unconditionally, so
1087
+ * mounting it under a Meta Ads or Amazon cadence tab would report Odoo's health under another
1088
+ * connector's name. `ConnectorModal` gates the mount on `row.key === "odoo"`.
1089
  */
1090
  export function OdooSyncStatus({ onOpenDatabases }: { onOpenDatabases?: () => void } = {}) {
1091
  const [status, setStatus] = useState<OdooStatus | null>(null);
 
1194
  return key.startsWith("md_") ? key.slice(3) : key;
1195
  }
1196
 
1197
+ /**
1198
+ * ⭐⭐ W53-T28 (instruction 22) — THE GEAR ON THE CARD'S ONE BUTTON, DRAWN LOCALLY, AND THE LOCAL
1199
+ * PART IS A LANE FENCE RATHER THAN A PREFERENCE.
1200
+ *
1201
+ * ⛔ THERE IS NO GEAR THIS FILE MAY IMPORT TODAY. `shell/Shell.tsx::GearIcon` draws exactly this
1202
+ * glyph in exactly this vocabulary but is not exported, and `Shell.tsx` belongs to another lane;
1203
+ * `ui/icons.tsx` is the shared 24x24 module and carries Download/Check/Alert/Bell/Star only.
1204
+ * Contract C4 gives lane G a new `shell/icons.tsx` and THAT is this component's eventual home:
1205
+ * fold it in at the combine and let both callers import one gear, rather than leaving two files
1206
+ * drawing one path (the D-207 two-BellIcons shape, which `verify_ui`'s `one-bell` leg exists to
1207
+ * catch).
1208
+ *
1209
+ * ⚠ NO EMOJI, NO COLOUR AND NO CLASS. DESIGN.md section 4 bans emoji outright; the paint is
1210
+ * `currentColor` so the button's own token drives it and hover repaints the glyph with the label;
1211
+ * and the two geometry values are inline because no connectors stylesheet is inside this ticket's
1212
+ * `files:` fence and a `className` with no rule behind it is a selector that points at nothing.
1213
+ * `.conn-card-open` is `text-align: center` and not flex, so the gear rides the text's own line
1214
+ * box and needs the baseline nudge to sit on the label's optical centre.
1215
+ */
1216
+ function SettingsGearIcon() {
1217
+ return (
1218
+ <svg
1219
+ viewBox="0 0 16 16"
1220
+ width="13"
1221
+ height="13"
1222
+ aria-hidden="true"
1223
+ focusable="false"
1224
+ fill="none"
1225
+ stroke="currentColor"
1226
+ strokeWidth={1.3}
1227
+ style={{ verticalAlign: "-0.13em", marginRight: 6 }}
1228
+ >
1229
+ <circle cx="8" cy="8" r="2.15" />
1230
+ <path d="M8 1.9l.9 1.5 1.7-.4.5 1.7 1.7.5-.4 1.7 1.2 1.1-1.2 1.1.4 1.7-1.7.5-.5 1.7-1.7-.4-.9 1.5-.9-1.5-1.7.4-.5-1.7-1.7-.5.4-1.7L1.7 8l1.2-1.1-.4-1.7 1.7-.5.5-1.7 1.7.4z" />
1231
+ </svg>
1232
+ );
1233
+ }
1234
+
1235
  function ConnectorCardIdentity({ row }: { row: ConnectorRow }) {
1236
  const mark = brandForConnector(markKey(row.key), 22);
1237
  return (
 
1281
  row,
1282
  onKeychain,
1283
  onOpen,
 
1284
  onPullReviews,
1285
  }: {
1286
  row: ConnectorRow;
 
1307
  * 117 stay faded.
1308
  */
1309
  onPullReviews?: () => void;
1310
+ /*
1311
+ * ⛔⛔ `onOpenDatabases` STOOD HERE AND IS DELETED BY W53-T28. It was W49-T14's door into the
1312
+ * modal's Databases tab, and the card reached it through `OdooManage` -> `OdooSyncStatus`. The
1313
+ * card no longer renders either: `OdooSyncStatus` and the "Manage fields in the Databases tab"
1314
+ * link it owns are mounted inside `ConnectorModal`'s Sync cadence tab, where the jump is the
1315
+ * modal's own `setTab("databases")`. R26's one-door rule is untouched; only the door's side of
1316
+ * the wall changed. ⚠ Do not re-add it as a convenience: an optional prop on this card is one
1317
+ * `onClick` away from being a second action, which is the thing this ticket removed.
 
1318
  */
 
1319
  }) {
1320
  /**
1321
  * ⭐⭐ THE CARD HAS NO DOOR, AND THAT IS THE CONDITION EVERY GUARD BELOW WANTS — not the
 
1465
  {row.state === "reconnect" ? "Reconnect" : "Connect"}
1466
  </a>
1467
  ) : null}
1468
+ {/* ⭐⭐ WAVE 32 items 6/11 (C2, R9/R10/R11) PUT ODOO'S SYNC PANEL ON THIS CARD, AND
1469
+ W53-T28 (instructions 22/23) TAKES IT OFF AGAIN. W52-T03 deleted the plain
1470
+ "Manage keys"/"Add keys" button from every other keychain card and spared Odoo's
1471
+ because the modal could not yet configure grids, cadence and disconnect; W52-T04
1472
+ then built the Sync cadence tab that does all three, so the exception expired and
1473
+ this branch goes with it.
1474
+ ⛔ THE CARD IS NOT LOSING A CAPABILITY, IT IS LOSING A SECOND COPY OF ONE. The
1475
+ panel behind this branch and the panel behind the modal's Sync cadence tab were
1476
+ the same `OdooConfigPanel` over the same route, open at the same time, each with
1477
+ its own state — two doors onto one setting, which is the failure R26 named on
1478
+ this very page. Grids, cadence, server database and disconnect/reconnect are in
1479
+ the Sync cadence tab; the key is in the Keychain tab; both are behind the one
1480
+ Settings button below. ⛔ And the words "Manage keys"/"Add keys" stay retired
1481
+ from every card, under any label. */}
 
 
 
 
 
 
 
 
 
1482
  {/* ⭐⭐ WAVE 33 · D-204 — THE MEMBER'S OWN DOOR. Same room, different promise: this
1483
  card connects an account that is YOURS, which is why the word is not "Manage
1484
  keys". It appears only for connectors whose credential may be personal — the
 
1515
  aria-label={`Open settings for ${row.label}`}
1516
  onClick={() => onOpen?.()}
1517
  >
1518
+ {/* ⭐ W53-T28 (instruction 22) — the gear rides INSIDE the button and is
1519
+ `aria-hidden`, so the accessible name stays the `aria-label` above and the
1520
+ glyph adds no second reading of the same control. */}
1521
+ <SettingsGearIcon />
1522
  Settings
1523
  </button>
1524
  ) : null}
web/src/connectors/DatabasesTab.tsx CHANGED
@@ -35,6 +35,21 @@
35
  // `/dependents` fails for any reason the table is LEFT ON and the cause is
36
  // printed. Writing the flag anyway would make R23 a suggestion.
37
  //
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  // ⚠ PURE OVER PROPS, AND IT FETCHES ONLY ON A CLICK. The modal reads `/detail`
39
  // on mount and `renderToStaticMarkup` runs no effects, so a static proof of
40
  // this tab has to be paintable from a payload — the same reason
@@ -257,6 +272,102 @@ function DatabasePanel({
257
  );
258
  }
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  /**
261
  * ⭐ THE TAB, PURE AND EXPORTED. Everything it lists is `detail`; the only network it does is a
262
  * write the reader asked for, plus R23's pre-flight on the way to one.
@@ -272,12 +383,19 @@ export default function DatabasesTab({
272
  onChanged: () => void;
273
  }) {
274
  const { databases, introspection } = detail;
275
- const [open, setOpen] = useState<Record<string, boolean>>(() =>
276
- databases.length ? { [databases[0].key]: true } : {}
277
- );
 
 
 
 
278
  const [busy, setBusy] = useState("");
279
  const [refusals, setRefusals] = useState<Record<string, string>>({});
280
  const [error, setError] = useState("");
 
 
 
281
 
282
  const labels = useMemo(() => {
283
  const out: Record<string, string> = {};
@@ -343,6 +461,36 @@ export default function DatabasesTab({
343
  [onChanged]
344
  );
345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  if (!introspection.introspectable) {
347
  return <DatabasesUnavailable row={row} reason={introspection.reason} />;
348
  }
@@ -369,70 +517,126 @@ export default function DatabasesTab({
369
  <span className="conn-db-n">{databases.length}</span> databases are created from this
370
  connection.
371
  </p>
372
- <ul className="conn-db-list">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  {databases.map((database) => {
374
  const isOpen = open[database.key] === true;
375
  const refusal = refusals[database.key] || "";
376
  return (
377
- <li className="conn-db-item" key={database.key}>
378
- <div className="conn-db-head">
379
- <button
380
- type="button"
381
- className="conn-db-more"
382
- aria-expanded={isOpen}
383
- onClick={() =>
384
- setOpen((current) => ({ ...current, [database.key]: !isOpen }))
385
- }
386
- >
387
- <span className="conn-db-name">{database.label}</span>
388
- <span className="conn-db-count">
389
- {database.fields.length ? `${database.fields.length} fields` : "Fields"}
390
- </span>
391
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  {/* ⭐ R22 — ANY table can be switched off, not only the ones we mark optional.
393
  Every row gets the same control, and nothing here decides that one of them is
394
  too important to turn off: R23's ask is what protects a table in use. */}
395
- {introspection.canToggleTables ? (
396
- <Switch
397
- on={database.enabled}
398
- busy={busy === database.key}
399
- label={
400
- database.enabled
401
- ? `Switch off the database ${database.label}`
402
- : `Switch on the database ${database.label}`
403
- }
404
- onFlip={(next) => void flipTable(database, next)}
405
- />
406
- ) : (
407
- <span className="conn-db-state">{database.enabled ? "On" : "Off"}</span>
408
- )}
409
- </div>
 
 
410
  {refusal ? (
411
  // ⚠ A REFUSAL IS NOT AN ERROR THE READER CAUSED (DESIGN.md section 4). It states
412
  // the cause and the subject, in the server's own sentence, and offers nothing to
413
  // dismiss because the table simply stayed on.
414
- <p className="conn-db-refusal" role="alert">
415
- {refusal}
416
- </p>
 
 
 
 
417
  ) : null}
418
  {isOpen ? (
419
- <DatabasePanel
420
- database={database}
421
- siblingLabels={database.sharesFieldsWith
422
- .map((key) => labels[key] || "")
423
- .filter((label) => label.length > 0)}
424
- fieldsVisible={introspection.fieldsVisible}
425
- canToggleFields={introspection.canToggleFields}
426
- catalogueComplete={introspection.catalogueComplete}
427
- excludedBasis={introspection.excludedBasis}
428
- busyField={busy}
429
- onField={(fieldKey, next) => void flipField(fieldKey, next)}
430
- />
 
 
 
 
431
  ) : null}
432
- </li>
433
  );
434
  })}
435
- </ul>
436
  </div>
437
  );
438
  }
 
35
  // `/dependents` fails for any reason the table is LEFT ON and the cause is
36
  // printed. Writing the flag anyway would make R23 a suggestion.
37
  //
38
+ // ⭐⭐ W53-T27, R9 / C2 — THREE NAMES PER DATABASE, AND THE TAB MUST NOT BLEND THEM. `native` is
39
+ // the vendor's own identifier for the table, `defaultLabel` is the name WE ship, and `override`
40
+ // is this tenant's own. All three arrive on `/detail`: there is no native-name map and no
41
+ // default-label map in this file, for the same reason there is no table list in it.
42
+ //
43
+ // ⛔ THE OVERRIDE IS THE ONE THE NAVIGATION RAIL WRITES. R9, verbatim: *"the rename database
44
+ // under the Navigation rail also works, it should then sync to the navigation in the connector
45
+ // too."* So the rename control here PATCHes the connector door that writes the rail's own
46
+ // `nav_meta` bucket, and clearing it falls back to `defaultLabel` rather than blanking the row.
47
+ // A second store would give one workspace two names for one database.
48
+ //
49
+ // ⛔ `native` IS NEVER EDITABLE, AND THE SCREEN SAYS SO RATHER THAN SHOWING A DEAD CONTROL. A
50
+ // disabled input with no sentence beside it reads as "not yet", which is a promise this product
51
+ // cannot keep: the source names its own tables.
52
+ //
53
  // ⚠ PURE OVER PROPS, AND IT FETCHES ONLY ON A CLICK. The modal reads `/detail`
54
  // on mount and `renderToStaticMarkup` runs no effects, so a static proof of
55
  // this tab has to be paintable from a payload — the same reason
 
272
  );
273
  }
274
 
275
+ /**
276
+ * ⭐ W53-T27 — THE TENANT'S OWN NAME FOR ONE DATABASE, and the way back to ours.
277
+ *
278
+ * ⛔ PURE OVER PROPS, DRAFT INCLUDED. The text being typed lives in the tab's own state rather
279
+ * than in here, so a cleared override cannot leave a stale draft behind in a cell nobody
280
+ * remounted, and so this whole tab still paints under `renderToStaticMarkup`.
281
+ *
282
+ * ⛔ NO CONTROL AT ALL FOR A READER WHO MAY NOT RENAME (`canRename` is the server's own `may_open`
283
+ * answer). This directory's rule is that a door the write side would refuse is not drawn.
284
+ */
285
+ function NameCell({
286
+ database,
287
+ editing,
288
+ draft,
289
+ busy,
290
+ onDraft,
291
+ onEdit,
292
+ onCancel,
293
+ onSave,
294
+ }: {
295
+ database: ConnectorDatabase;
296
+ editing: boolean;
297
+ draft: string;
298
+ busy: boolean;
299
+ onDraft: (next: string) => void;
300
+ onEdit: () => void;
301
+ onCancel: () => void;
302
+ /** An empty string CLEARS, which is what falling back to our default means. */
303
+ onSave: (next: string) => void;
304
+ }) {
305
+ if (!editing) {
306
+ // ⚠ `conn-db-head` IS THE ROW SHAPE THIS TAB ALREADY USES for a name beside its control, and
307
+ // it is reused rather than re-declared: two adjacent inline controls with no rule between
308
+ // them set flush against each other, which is the run-on this surface reads as one word.
309
+ return (
310
+ <div className="conn-db-head">
311
+ {database.override ? (
312
+ <span className="conn-db-name">{database.override}</span>
313
+ ) : (
314
+ <span className="conn-db-state">Inherits the default name</span>
315
+ )}
316
+ {database.canRename ? (
317
+ <button
318
+ type="button"
319
+ className="conn-db-link"
320
+ aria-label={`Rename the database ${database.label}`}
321
+ onClick={onEdit}
322
+ >
323
+ {database.override ? "Change" : "Rename"}
324
+ </button>
325
+ ) : null}
326
+ </div>
327
+ );
328
+ }
329
+ return (
330
+ <>
331
+ {/* ⚠ THE FIELD AND LINK SHAPES ARE THE MODAL'S OWN, borrowed rather than invented: this
332
+ ticket ships no stylesheet, and a bare input inside a styled tab is the native chrome
333
+ DESIGN.md section 4 rules out. */}
334
+ <div className="conn-kc-field">
335
+ <label htmlFor={`conn-db-rename-${database.key}`}>Your name for this database</label>
336
+ <input
337
+ id={`conn-db-rename-${database.key}`}
338
+ value={draft}
339
+ disabled={busy}
340
+ autoComplete="off"
341
+ onChange={(event) => onDraft(event.target.value)}
342
+ />
343
+ </div>
344
+ <div className="conn-db-head">
345
+ <button
346
+ type="button"
347
+ className="conn-db-link"
348
+ disabled={busy || !draft.trim()}
349
+ onClick={() => onSave(draft)}
350
+ >
351
+ Save
352
+ </button>
353
+ {database.override ? (
354
+ <button
355
+ type="button"
356
+ className="conn-db-link"
357
+ disabled={busy}
358
+ onClick={() => onSave("")}
359
+ >
360
+ Use the default name
361
+ </button>
362
+ ) : null}
363
+ <button type="button" className="conn-db-link" disabled={busy} onClick={onCancel}>
364
+ Cancel
365
+ </button>
366
+ </div>
367
+ </>
368
+ );
369
+ }
370
+
371
  /**
372
  * ⭐ THE TAB, PURE AND EXPORTED. Everything it lists is `detail`; the only network it does is a
373
  * write the reader asked for, plus R23's pre-flight on the way to one.
 
383
  onChanged: () => void;
384
  }) {
385
  const { databases, introspection } = detail;
386
+ /**
387
+ * ⚠ W53-T27 — EVERY ROW STARTS CLOSED, and that changed here. Until this ticket the first
388
+ * database was opened for you, because the field list WAS the content of this tab. The content
389
+ * is now the eight rows and their three names, and one open row buries the other seven under a
390
+ * 190-field table: the reader cannot see the list they came to read.
391
+ */
392
+ const [open, setOpen] = useState<Record<string, boolean>>({});
393
  const [busy, setBusy] = useState("");
394
  const [refusals, setRefusals] = useState<Record<string, string>>({});
395
  const [error, setError] = useState("");
396
+ /** The one row being renamed, and the text in its box. Empty means nobody is renaming. */
397
+ const [renaming, setRenaming] = useState("");
398
+ const [draft, setDraft] = useState("");
399
 
400
  const labels = useMemo(() => {
401
  const out: Record<string, string> = {};
 
461
  [onChanged]
462
  );
463
 
464
+ /**
465
+ * ⭐ W53-T27 / R9 — THE OVERRIDE, WRITTEN THROUGH THE DOOR THAT WRITES THE NAVIGATION RAIL'S
466
+ * OWN BUCKET. An empty `name` CLEARS it, which is the half `POST /nav/meta` refuses and the
467
+ * reason this door exists at all.
468
+ *
469
+ * ⛔ THE MESSAGE ON A FAILURE IS THE SERVER'S, verbatim, exactly as a dependents refusal is.
470
+ * This screen does not know why a rename was refused and must not compose a guess.
471
+ */
472
+ const renameDatabase = useCallback(
473
+ async (database: ConnectorDatabase, next: string) => {
474
+ setBusy(database.key);
475
+ setError("");
476
+ const message = await write(
477
+ `/connectors/${encodeURIComponent(row.key)}/databases/` +
478
+ `${encodeURIComponent(database.key)}/name`,
479
+ "PATCH",
480
+ { name: next }
481
+ );
482
+ setBusy("");
483
+ if (message) {
484
+ setError(message);
485
+ return;
486
+ }
487
+ setRenaming("");
488
+ setDraft("");
489
+ onChanged();
490
+ },
491
+ [onChanged, row.key]
492
+ );
493
+
494
  if (!introspection.introspectable) {
495
  return <DatabasesUnavailable row={row} reason={introspection.reason} />;
496
  }
 
517
  <span className="conn-db-n">{databases.length}</span> databases are created from this
518
  connection.
519
  </p>
520
+ {/* ⛔ THE IDENTITY BLOCK IS EXPLAINED, NOT INFERRED FROM A GREYED CONTROL. Which of the
521
+ three names is ours, which is theirs and which one a rename touches is the question this
522
+ screen exists to answer, so it is answered in words above the table. */}
523
+ <p className="conn-db-note">
524
+ Source name is what {row.label} calls the table, so it cannot be changed here. Default
525
+ name is ours. Your name replaces it everywhere in this workspace, including the
526
+ navigation rail, and clearing it brings the default back.
527
+ </p>
528
+ <table className="conn-db-fields">
529
+ <thead>
530
+ <tr>
531
+ <th scope="col">Source name</th>
532
+ <th scope="col">Default name</th>
533
+ <th scope="col">Your name</th>
534
+ <th scope="col">Fields</th>
535
+ <th scope="col">Enabled</th>
536
+ </tr>
537
+ </thead>
538
  {databases.map((database) => {
539
  const isOpen = open[database.key] === true;
540
  const refusal = refusals[database.key] || "";
541
  return (
542
+ <tbody key={database.key}>
543
+ <tr>
544
+ {/* ⛔ AN ABSENT NATIVE NAME IS SAID, NOT FILLED IN. Amazon names a table by the
545
+ report it is filled from, and a table whose report type we cannot read has no
546
+ vendor identifier to show. Printing the key there would put our own word under
547
+ the source's heading. */}
548
+ <td className="conn-db-src">
549
+ {database.native || <span className="conn-db-state">Not published</span>}
550
+ </td>
551
+ <td>{database.defaultLabel}</td>
552
+ <td>
553
+ <NameCell
554
+ database={database}
555
+ editing={renaming === database.key}
556
+ draft={draft}
557
+ busy={busy === database.key}
558
+ onDraft={setDraft}
559
+ onEdit={() => {
560
+ setRenaming(database.key);
561
+ setDraft(database.override || database.defaultLabel);
562
+ setError("");
563
+ }}
564
+ onCancel={() => {
565
+ setRenaming("");
566
+ setDraft("");
567
+ }}
568
+ onSave={(next) => void renameDatabase(database, next)}
569
+ />
570
+ </td>
571
+ <td>
572
+ <button
573
+ type="button"
574
+ className="conn-db-more"
575
+ aria-expanded={isOpen}
576
+ aria-label={`Show the fields in ${database.label}`}
577
+ onClick={() =>
578
+ setOpen((current) => ({ ...current, [database.key]: !isOpen }))
579
+ }
580
+ >
581
+ <span className="conn-db-count">
582
+ {database.fields.length ? `${database.fields.length} fields` : "Fields"}
583
+ </span>
584
+ </button>
585
+ </td>
586
  {/* ⭐ R22 — ANY table can be switched off, not only the ones we mark optional.
587
  Every row gets the same control, and nothing here decides that one of them is
588
  too important to turn off: R23's ask is what protects a table in use. */}
589
+ <td className="conn-db-cell-switch">
590
+ {introspection.canToggleTables ? (
591
+ <Switch
592
+ on={database.enabled}
593
+ busy={busy === database.key}
594
+ label={
595
+ database.enabled
596
+ ? `Switch off the database ${database.label}`
597
+ : `Switch on the database ${database.label}`
598
+ }
599
+ onFlip={(next) => void flipTable(database, next)}
600
+ />
601
+ ) : (
602
+ <span className="conn-db-state">{database.enabled ? "On" : "Off"}</span>
603
+ )}
604
+ </td>
605
+ </tr>
606
  {refusal ? (
607
  // ⚠ A REFUSAL IS NOT AN ERROR THE READER CAUSED (DESIGN.md section 4). It states
608
  // the cause and the subject, in the server's own sentence, and offers nothing to
609
  // dismiss because the table simply stayed on.
610
+ <tr>
611
+ <td colSpan={5}>
612
+ <p className="conn-db-refusal" role="alert">
613
+ {refusal}
614
+ </p>
615
+ </td>
616
+ </tr>
617
  ) : null}
618
  {isOpen ? (
619
+ <tr>
620
+ <td colSpan={5}>
621
+ <DatabasePanel
622
+ database={database}
623
+ siblingLabels={database.sharesFieldsWith
624
+ .map((key) => labels[key] || "")
625
+ .filter((label) => label.length > 0)}
626
+ fieldsVisible={introspection.fieldsVisible}
627
+ canToggleFields={introspection.canToggleFields}
628
+ catalogueComplete={introspection.catalogueComplete}
629
+ excludedBasis={introspection.excludedBasis}
630
+ busyField={busy}
631
+ onField={(fieldKey, next) => void flipField(fieldKey, next)}
632
+ />
633
+ </td>
634
+ </tr>
635
  ) : null}
636
+ </tbody>
637
  );
638
  })}
639
+ </table>
640
  </div>
641
  );
642
  }
web/src/connectors/RelationshipDiagram.tsx CHANGED
@@ -640,6 +640,22 @@ export function edgeSummary(connector: string, graph: DiagramInput): string {
640
  if (!graph.relationships.length) {
641
  return name + " relationship map. No declared links join these databases.";
642
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  // ⚠ THE DATABASE'S NAME, NOT ITS STORAGE KEY. A summary reading "ut_odoo_bills" says the
644
  // table's internal key out loud to the one reader who cannot see the card that translates it.
645
  const named = (key: string): string => {
@@ -651,7 +667,8 @@ export function edgeSummary(connector: string, graph: DiagramInput): string {
651
  const parts = graph.relationships.map((relation) =>
652
  named(relation.from.table) + " to " + named(relation.to.table) + ", by " + relation.label);
653
  return name + " relationship map. " + String(graph.relationships.length)
654
- + (graph.relationships.length === 1 ? " link: " : " links: ") + parts.join("; ") + ".";
 
655
  }
656
 
657
  export default function RelationshipDiagram({
 
640
  if (!graph.relationships.length) {
641
  return name + " relationship map. No declared links join these databases.";
642
  }
643
+ /* ⭐ W53-T30: a database that joins NOTHING is on the screen and was absent from
644
+ * this sentence, so the one reader who cannot see the cards was told about part
645
+ * of the picture. `relationshipLayout` already lays such a table out on its own
646
+ * below the bands; naming it here is the same fact in words. It is a real state
647
+ * of this graph rather than an error: a database can be part of a connection and
648
+ * declare no relation to its siblings. */
649
+ const joined = new Set<string>();
650
+ for (const relation of graph.relationships) {
651
+ joined.add(relation.from.table);
652
+ joined.add(relation.to.table);
653
+ }
654
+ const alone = graph.tables.filter((table) => !joined.has(table.key)).map((table) => table.label);
655
+ const aloneText = alone.length === 0
656
+ ? ""
657
+ : " " + (alone.length === 1 ? "One database declares no link: " : "These declare no link: ")
658
+ + alone.join(", ") + ".";
659
  // ⚠ THE DATABASE'S NAME, NOT ITS STORAGE KEY. A summary reading "ut_odoo_bills" says the
660
  // table's internal key out loud to the one reader who cannot see the card that translates it.
661
  const named = (key: string): string => {
 
667
  const parts = graph.relationships.map((relation) =>
668
  named(relation.from.table) + " to " + named(relation.to.table) + ", by " + relation.label);
669
  return name + " relationship map. " + String(graph.relationships.length)
670
+ + (graph.relationships.length === 1 ? " link: " : " links: ") + parts.join("; ") + "."
671
+ + aloneText;
672
  }
673
 
674
  export default function RelationshipDiagram({
web/src/customer-grid/RecordDetail.css CHANGED
@@ -134,6 +134,26 @@
134
  background: var(--lp-surface);
135
  }
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  .cg-record-layout {
138
  flex: 1 1 auto;
139
  min-height: 0;
@@ -141,6 +161,47 @@
141
  grid-template-columns: minmax(0, 1.95fr) minmax(300px, 0.95fr);
142
  }
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  .cg-record-modal--single {
145
  width: min(880px, calc(100vw - 48px));
146
  }
 
134
  background: var(--lp-surface);
135
  }
136
 
137
+ /* ⭐⭐ W53-T22 (instr 7, R4) — THE DRILL TRAIL'S OWN BAND, and it is the ONLY new rule this
138
+ ticket adds. The crumbs themselves wear `cg-path-segments` / `cg-path-segment-wrap` /
139
+ `cg-path-separator` / `cg-path-segment` / `cg-path-history-button`, which are unscoped in
140
+ `index.css` and already shared by the Data rail and the Sheet rail; a second crumb treatment
141
+ here is how two of the three would drift apart.
142
+ ⚠ `flex: 0 0 auto` inside `.cg-record-shell`, so the band takes its own height and the layout
143
+ below keeps the rest — a growing crumb list must never eat the record it describes.
144
+ ⚠ AND IT IS RENDERED ONLY WHILE A FRAME IS PUSHED (`stack.length > 0` in the TSX), so no
145
+ record in the product gains a permanent empty strip. */
146
+ .cg-record-path {
147
+ flex: 0 0 auto;
148
+ min-width: 0;
149
+ display: flex;
150
+ align-items: center;
151
+ gap: 2px;
152
+ padding: 4px 12px 5px;
153
+ border-bottom: 1px solid var(--lp-line);
154
+ background: var(--lp-surface);
155
+ }
156
+
157
  .cg-record-layout {
158
  flex: 1 1 auto;
159
  min-height: 0;
 
161
  grid-template-columns: minmax(0, 1.95fr) minmax(300px, 0.95fr);
162
  }
163
 
164
+ /* ⭐⭐ W53-T21 (instr 5) — A LINKED-DATABASE TAB IS ONE COLUMN, THE WHOLE PANE.
165
+ `RecordDetail.tsx` already WITHHOLDS `RecordComments` on a linked-database tab (W52-T24:
166
+ `!frame && showComments && scope != null && activeTab === "fields"`), but the grid above is
167
+ unconditional on the open tab, so the comments column kept RESERVING its 300px minimum with
168
+ nothing in it while the embedded grid was squeezed into the rest. Reserved-but-empty is the
169
+ owner's screenshot (reference/ERROR 21.png), and this is the rule that ends it: the layout
170
+ carries `data-related-tab` (its value is the open EDGE KEY, so the DOM says WHICH linked
171
+ database is open) exactly when a linked tab is active, and drops the attribute on Details, so
172
+ the two-column anatomy comes straight back.
173
+ ⚠ AN ATTRIBUTE, NOT A SECOND CLASS: `verify_record_layout.py`'s `drawer_anatomy_shape`
174
+ greps the TSX for the literal, unconcatenated `className="cg-record-layout"`, so a templated
175
+ class or a `clsx` call would read to that gate as the two-column drawer having been deleted.
176
+ ⚠ AND AN ATTRIBUTE SELECTOR, NOT A BARE CLASS, FOR A SECOND REASON: this is specificity
177
+ (0,2,0), which outranks the mobile `@media` block's own bare `.cg-record-layout` rule (0,1,0)
178
+ near the end of this file no matter which of them comes last in source order.
179
+ ⚠ THE ROW TRACK IS DECLARED TOO. A grid's implicit row is `auto`, which sizes to CONTENT:
180
+ with the second column gone the mounted `.cg-shell` would stretch the drawer instead of
181
+ scrolling inside it. `minmax(0, 1fr)` bounds the single cell to the layout's own height, which
182
+ is what lets `.cg-record-related`'s `height: 100%` resolve. */
183
+ .cg-record-layout[data-related-tab] {
184
+ grid-template-columns: minmax(0, 1fr);
185
+ grid-template-rows: minmax(0, 1fr);
186
+ }
187
+
188
+ /* ⭐⭐ W53-T21 (instr 5) — THE EMBEDDED GRID'S OWN VIEW RAIL, HIDDEN IN THIS ONE PLACE.
189
+ `ViewSidebar`'s "All views / Create new / Find / <view name>" rail is the STANDALONE Data
190
+ page's chrome for browsing other databases and folders from scratch; nested inside a record
191
+ drawer it is a switcher with nowhere to go, and it eats the width this ticket is reclaiming.
192
+ `.cg-record-related` is the wrapper `RecordDetail.tsx` already draws around the `RelatedGrid`
193
+ mount, so this reaches that sidebar and ONLY that one: `RecordRail` is a direct child of
194
+ `.cg-record-modal` and a SIBLING of `.cg-record-shell`, so it is not a descendant of
195
+ `.cg-record-related` and this selector can never reach it.
196
+ ⛔ NOT THE SAME LEVER AS `embedded`. `CustomerGrid.tsx::embedded` also switches the read to
197
+ the WHOLE table filtered client-side, which is standing rule 1 pointed the wrong way on a
198
+ connected source, and that file is outside this ticket's fence. This paints over the rail; the
199
+ server-narrowed pinned read underneath is untouched. Precedent for hiding this exact sibling:
200
+ `.cg-shell.is-view-fullscreen .cg-views` in index.css. */
201
+ .cg-record-related .cg-views {
202
+ display: none;
203
+ }
204
+
205
  .cg-record-modal--single {
206
  width: min(880px, calc(100vw - 48px));
207
  }
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -47,15 +47,20 @@ import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditFiel
47
  declares what a `/related` entry and a pinned read ARE, so this panel and `CustomerGrid`
48
  cannot come to hold two opinions about one wire contract
49
  [[two-lanes-one-contract-dead-feature]]. */
50
- import { CUSTOMER_TOPIC, PRODUCT_TOPIC, relatedTabs, topicForScope } from "./types";
51
- import type { CustomerDoc, Field, RelatedEntry, RelatedVia, Row,
 
52
  Viewer } from "./types";
53
  /* ⭐ THE THREE DOORS THIS PANEL ASKS, ALL OF THEM ALREADY OWNED BY `apiBridge`: what is related
54
  to this table, what the databases are called, and whether an edge's pinned read can be served
55
  today. No `fetch` is written here — `apiBridge` owns the credential mode, the session handling
56
  and the refusal reading, and a fourth copy of that in a drawer is how one surface stops
57
  noticing an expired cookie. */
58
- import { fetchLinkTargets, fetchRelated, probeRelatedRead, readThroughTables } from "./apiBridge";
 
 
 
 
59
 
60
  /**
61
  * ⭐⭐ WAVE-34 (owner ruling R13) — whose value sits in this enrichment cell, in words.
@@ -408,13 +413,100 @@ function ChoiceCreateInput({
408
  * table's door (`routes_tables.table_rows`) takes none either. R6's second sentence makes that
409
  * a REPORTED limit with a cause and a recommendation, never a tab that quietly shows nothing
410
  * and never a tab that quietly shows EVERYTHING.
411
- * ⚠ `ready` is the only state that mounts a grid. Collapsing `refused` into it would paint the
412
- * whole target database under a chip that names one record.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
  */
414
  type RelatedTabState =
415
  | { status: "probing" }
416
  | { status: "ready" }
417
- | { status: "refused"; reason: string };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
 
419
  /**
420
  * ⭐ W51-T06 CLAUSE 9 — ONE HOP of the record view's navigation, carrying everything needed to
@@ -427,8 +519,32 @@ interface RecordFrame {
427
  label: string;
428
  record: Row;
429
  fields: Field[];
 
 
 
 
 
 
 
 
 
 
 
 
430
  }
431
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  /**
433
  * ⭐⭐ CLAUSE 10's STORE, AND IT IS `localStorage` BECAUSE R5 SAYS **"nothing new is stored"**.
434
  *
@@ -490,6 +606,15 @@ function writeTabViews(value: Record<string, string>): void {
490
  * exists for exactly one state, and it says the same three things the server's own do: what was
491
  * asked, why it cannot be answered, and what to do instead.
492
  * ⛔ NO EM DASH AND NO EN DASH: this reaches a screen (standing rule 2).
 
 
 
 
 
 
 
 
 
493
  */
494
  function unpinnableNote(target: string): string {
495
  return `'${target}' is not read through the live mirror on this deployment, so its rows door `
@@ -497,6 +622,31 @@ function unpinnableNote(target: string): string {
497
  + `database on its own and filter it there, or ask for its stored read to accept a pin`;
498
  }
499
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  function relatedScope(target: string): SurfaceScope {
501
  if (target === CUSTOMER_TOPIC.key) return CUSTOMER_TOPIC.scope as SurfaceScope;
502
  if (target === PRODUCT_TOPIC.key) return PRODUCT_TOPIC.scope as SurfaceScope;
@@ -565,28 +715,25 @@ export default function RecordDetail({
565
  setStack((prev) => (prev.length ? [] : prev));
566
  }, [baseRecord.pid, scope]);
567
  /**
568
- * ⭐ CLAUSE 9's FORWARD HALF. The row, the fields and the table all arrive from the grid that
569
- * already had them; only the LABEL is derived here, and only from what came with the row.
570
- * ⚠ `title` on a frame is the frame's own label: `titleKey` belongs to the base table and
571
- * reading it off a foreign row answers "Untitled" for every one of them.
 
 
 
572
  */
573
- const pushFrame = useCallback(
574
- (pid: number, table: string, row?: Row, rowFields?: Field[]) => {
575
- if (!row || !rowFields || rowFields.length === 0) return;
576
- const first = rowFields[0];
577
- const named = first ? String(row[first.key] ?? "") : "";
578
- setStack((prev) => [...prev, {
579
- table,
580
- pid,
581
- label: named || `Record ${pid}`,
582
- record: row,
583
- fields: rowFields,
584
- }]);
585
- },
586
- []
587
- );
588
- const popFrame = useCallback(() => setStack((prev) => prev.slice(0, -1)), []);
589
  const title = frame ? frame.label : String(record[titleKey] ?? "Untitled");
 
 
 
590
  // Wave 19 (item 12): `scope` joins the predicate — the comments rail addresses a server
591
  // endpoint per topic now, so a host that names no surface gets no rail rather than a rail
592
  // pointed at a guess. In practice CustomerGrid always names one; this is the fail-closed edge.
@@ -746,28 +893,72 @@ export default function RecordDetail({
746
  /**
747
  * R2's answer for this table. Empty until it arrives and empty on any failure, which is the
748
  * honest degradation: a record whose relations cannot be listed still opens on its Fields tab.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
749
  */
750
- const [entries, setEntries] = useState<RelatedEntry[]>([]);
 
 
 
 
 
 
 
 
751
  /**
752
- * ⭐ CLAUSE 2's OTHER HALF — `target key -> the DATABASE's own name`.
 
753
  *
754
- * ⛔ THE `/related` ENTRY'S OWN `label` IS NOT IT, measured in `relations.py` rather than
755
- * assumed: a FORWARD entry is labelled with the FIELD's label, which is exactly what clause 2
756
- * wants as the SUBTITLE. The roster behind the link picker (`GET /tables?brief=1`) is the one
757
- * producer of a database's display name in this product, so the name comes from there and the
758
- * entry's own label is only the fallback.
 
 
 
 
759
  */
760
  const [tableLabels, setTableLabels] = useState<Record<string, string>>({});
761
  useEffect(() => {
762
  // No scope, no tabs: the same fail-closed edge the comments rail takes. A pid means nothing
763
  // without the table it belongs to, and guessing one asks a question nobody asked.
764
  if (scope == null) {
765
- setEntries([]);
 
 
766
  return;
767
  }
768
  let live = true;
 
 
 
 
 
 
 
 
 
769
  void fetchRelated(recordTable).then((got) => {
770
- if (live) setEntries(got);
 
 
 
 
771
  });
772
  void fetchLinkTargets().then((targets) => {
773
  if (!live) return;
@@ -791,7 +982,21 @@ export default function RecordDetail({
791
  * has disappeared (a link column deleted while the drawer was open) drops back to Fields
792
  * rather than rendering a panel for an edge that is no longer offered.
793
  */
794
- const [tab, setTab] = useState("fields");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795
  const activeTab = tabs.some((entry) => entry.entry.key === tab) ? tab : "fields";
796
  const activeRelated = tabs.find((entry) => entry.entry.key === activeTab) ?? null;
797
 
@@ -833,11 +1038,26 @@ export default function RecordDetail({
833
  * ⚠ MEMOISED ON A SERIALISED KEY. The grid takes this as an effect dependency; a fresh object
834
  * per render would re-read on every keystroke in the drawer.
835
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
836
  const relatedPinKey = activeRelated
837
  ? JSON.stringify({
838
  table: recordTable,
839
  record: Number(record.pid),
840
- via: activeRelated.entry.via,
 
 
841
  label: title,
842
  })
843
  : "";
@@ -849,6 +1069,177 @@ export default function RecordDetail({
849
  [relatedPinKey]
850
  );
851
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852
  /**
853
  * ⭐⭐ CAN THIS EDGE BE SERVED, AND IF NOT, IN WHOSE WORDS? See `RelatedTabState`.
854
  *
@@ -895,14 +1286,73 @@ export default function RecordDetail({
895
  setTabState({ status: "ready" });
896
  return;
897
  }
898
- const reason = await probeRelatedRead(target, pin);
 
 
 
 
 
 
 
 
 
 
 
899
  if (!live) return;
900
- setTabState({ status: "refused", reason: reason ?? unpinnableNote(target) });
 
 
 
 
 
 
 
 
 
901
  })();
902
  return () => {
903
  live = false;
904
  };
905
- }, [activeRelated, relatedPin]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
906
 
907
  /**
908
  * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
@@ -1552,9 +2002,20 @@ export default function RecordDetail({
1552
 
1553
  // One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
1554
  // Focus stays inside it, then returns to the exact opener on close.
 
 
 
 
 
 
 
 
 
 
 
1555
  useOverlayLayer({
1556
  panelRef,
1557
- onDismiss: onClose,
1558
  dismissOnOutside: true,
1559
  initialFocus: "[data-overlay-autofocus]",
1560
  trapFocus: true,
@@ -1583,30 +2044,23 @@ export default function RecordDetail({
1583
  <div className="cg-record-shell">
1584
  <div className="cg-detail-header">
1585
  <div className="cg-detail-nav">
1586
- {/* ⭐⭐ W51-T06 CLAUSE 9 — THE BACK ARROW, AND IT **REPLACES** PREV/NEXT RATHER THAN
1587
- JOINING THEM. Prev/next walk the HOST grid's row order, which a pushed record is
1588
- not in: offering them here would move the base record silently underneath the
1589
- one on screen. One way in, one way out, and the way out is the way back.
1590
- ⚠ The glyph is the same `‹` the previous-record key uses, on purpose: this is
1591
- the same gesture (go back one) reading the same direction, and inventing a second
1592
- arrow shape for it would make two controls out of one idea. */}
1593
- {frame ? (
1594
- <button
1595
- type="button"
1596
- className="cg-detail-navbtn"
1597
- onClick={popFrame}
1598
- aria-label="Back to the record you came from"
1599
- title="Back to the record you came from"
1600
- >
1601
- ‹
1602
- </button>
1603
- ) : (
1604
- <>
1605
  <button
1606
  type="button"
1607
  className="cg-detail-navbtn"
1608
- onClick={onPrev}
1609
- disabled={!canPrev}
1610
  aria-label="Previous record"
1611
  title="Previous record"
1612
  >
@@ -1615,15 +2069,13 @@ export default function RecordDetail({
1615
  <button
1616
  type="button"
1617
  className="cg-detail-navbtn"
1618
- onClick={onNext}
1619
- disabled={!canNext}
1620
  aria-label="Next record"
1621
  title="Next record"
1622
  >
1623
  ›
1624
  </button>
1625
- </>
1626
- )}
1627
  {/* ⭐⭐ W35-T29 (R5, R6) — THE SAME RECORD STAR AS THE GRID'S, in the drawer.
1628
  ⛔ THE SAME STATE, NOT A SECOND ONE: `starred`/`onStar` come from the grid's own
1629
  `useRecordStars`, so starring here and starring in the row are one act on one list.
@@ -1655,8 +2107,12 @@ export default function RecordDetail({
1655
  </button>
1656
  )}
1657
  {/* ⚠ W51-T06 — the caption counts the HOST grid's rows, so a pushed frame has
1658
- no position in it and says nothing rather than a number about somewhere else. */}
1659
- <span className="cg-detail-pos">{frame ? "" : positionLabel}</span>
 
 
 
 
1660
  </div>
1661
  <button
1662
  type="button"
@@ -1670,7 +2126,99 @@ export default function RecordDetail({
1670
  </button>
1671
  </div>
1672
 
1673
- <div className="cg-record-layout">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1674
  <main className="cg-record-main">
1675
  <div className="cg-detail-titlewrap">
1676
  <div className="cg-detail-title" id={titleId} title={title}>
@@ -1687,19 +2235,74 @@ export default function RecordDetail({
1687
  <div className="cg-record-related">
1688
  {/* ⭐⭐ CLAUSES 4 + 6 + 7 — THE TARGET DATABASE'S OWN GRID, over rows the SERVER
1689
  narrowed to this record.
1690
- ⛔ NO `embedded` AND NO `embeddedRecordIds`. That pair is the mode that hides
1691
- the view rail and pulls the whole table into the browser to filter it there;
1692
- R5 asks for the target's own saved views WITH the rail, over a pre-filtered
1693
- read. Passing `related` and passing `embedded` are mutually exclusive by
1694
- design, and this mount passes only the first.
 
 
 
 
1695
  ⛔ THE GRID IS THE PANEL, not a card inside one. DESIGN section 4 allows ONE
1696
  containment layer and the drawer is already it; a bordered box around a grid
1697
  inside a drawer inside a modal is the card-in-card the section names. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1698
  {tabState.status === "refused" ? (
1699
  /* ⭐ R6's SECOND SENTENCE — the limit, its cause and what to do instead, in the
1700
  SERVER's words. `role="status"` rather than `alert`: a declared relation that
1701
- is not served yet is a reported boundary, not a failure. */
1702
- <p className="cg-record-related-note" role="status">{tabState.reason}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1703
  ) : tabState.status === "probing" ? (
1704
  /* Owner R6 — one small bare rotating mark, NO WORDS on screen. The `aria-label`
1705
  is not a word on screen and stays, or the wait is announced as nothing at all
@@ -1707,6 +2310,56 @@ export default function RecordDetail({
1707
  <p className="cg-record-related-note">
1708
  <span className="lp-spin" role="status" aria-label="Loading" />
1709
  </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1710
  ) : (
1711
  <Suspense
1712
  fallback={
 
47
  declares what a `/related` entry and a pinned read ARE, so this panel and `CustomerGrid`
48
  cannot come to hold two opinions about one wire contract
49
  [[two-lanes-one-contract-dead-feature]]. */
50
+ import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs,
51
+ topicForScope } from "./types";
52
+ import type { CustomerDoc, Field, RelatedEntry, RelatedPin, RelatedRefusal, RelatedVia, Row,
53
  Viewer } from "./types";
54
  /* ⭐ THE THREE DOORS THIS PANEL ASKS, ALL OF THEM ALREADY OWNED BY `apiBridge`: what is related
55
  to this table, what the databases are called, and whether an edge's pinned read can be served
56
  today. No `fetch` is written here — `apiBridge` owns the credential mode, the session handling
57
  and the refusal reading, and a fourth copy of that in a drawer is how one surface stops
58
  noticing an expired cookie. */
59
+ /* ⭐ W53-T22 adds a FOURTH and a FIFTH, and for the same reason: `fetchTableWindow` +
60
+ `WINDOW_ROWS` are the one windowed read this product owns, and the sibling set a pushed
61
+ frame's chevrons page is that read with the frame's own pin on it. */
62
+ import { fetchLinkTargets, fetchRelated, fetchTableWindow, probeRelatedRead, readThroughTables,
63
+ WINDOW_ROWS } from "./apiBridge";
64
 
65
  /**
66
  * ⭐⭐ WAVE-34 (owner ruling R13) — whose value sits in this enrichment cell, in words.
 
413
  * table's door (`routes_tables.table_rows`) takes none either. R6's second sentence makes that
414
  * a REPORTED limit with a cause and a recommendation, never a tab that quietly shows nothing
415
  * and never a tab that quietly shows EVERYTHING.
416
+ * ⚠ `ready` is the only state that mounts a PINNED grid. Collapsing `refused` into it would paint
417
+ * the whole target database under a chip that names one record.
418
+ * ⚠ W53-T25 amends the first half of that sentence and not its second: `projected` mounts a grid
419
+ * too, but an UNPINNED one over an explicit pid list, and it is reachable only where the target is
420
+ * absent from the read-through roster. See its own note below.
421
+ */
422
+ /**
423
+ * ⭐⭐ W53-T24 · RULING R13 — `refused` NOW CARRIES THE SERVER'S **CODE** BESIDE THE SERVER'S
424
+ * SENTENCE, AND THAT IS THE WHOLE OF WHAT MAKES THREE ANSWERS THREE ANSWERS.
425
+ *
426
+ * R13: "no related rows", "you may not see this table" and "this hop was filtered" are THREE
427
+ * DIFFERENT ANSWERS. One `reason` string could be PRINTED three ways but never BRANCHED on
428
+ * without this file re-reading the server's prose, which is a second author of one contract
429
+ * wearing a regular expression. So the code rides along and picks the TREATMENT; the words stay
430
+ * the server's in all three.
431
+ * ⛔ AND NONE OF THE THREE IS AN EMPTY GRID. That is the failure this ticket exists to delete:
432
+ * an empty grid says "this record has no related rows" whichever of the three actually happened,
433
+ * and two of the three are then a wrong answer wearing the right chrome.
434
+ * ⚠ `code` is `""` when the body carried none (an unreachable server, an older route). That
435
+ * falls through to today's behaviour: the server's own sentence, plainly.
436
+ */
437
+ /**
438
+ * ⭐⭐ W53-T25 · D-657 — THE THIRD OUTCOME, AND IT IS A RESTORATION RATHER THAN A NEW FEATURE.
439
+ *
440
+ * ⛔ THE REGRESSION, STATED: W51-T05 built the ODOO half of the pinned read, and W51-T06 then
441
+ * deleted `linkSections` — the client mechanism that USED to paint a related tab whose target is
442
+ * an ordinary `ut_*` table. Each half was right on its own; together a related tab on a plain
443
+ * user table shows a sentence where it showed rows, which is the owner's instruction 8 exactly.
444
+ * Neither lane held both halves, so nothing went red.
445
+ *
446
+ * ⭐ WHAT REPLACED `linkSections` STILL EXISTS AND IS THE ANSWER: `CustomerGrid`'s `embedded` +
447
+ * `embeddedRecordIds` mode (wave 27's `LinkedGrid`), which reads the target table through its own
448
+ * ordinary door and projects an explicit pid list in the browser. It is intact and `LinkGridModal`
449
+ * still mounts it. `projected` is that mount, reached only where it is legitimate.
450
+ *
451
+ * ⛔⛔ AND IT IS STANDING-RULE-1 SAFE HERE FOR THE REASON IT WOULD NOT BE ON ODOO. The rule's
452
+ * test is `records_mutable(key)`: a table read THROUGH the mirror must never be pulled whole, and
453
+ * that is precisely the set `readThroughTables()` names — which `ready` owns and `projected` is
454
+ * forbidden to touch. A target the roster does NOT name is served by `routes_tables.table_rows`,
455
+ * the same whole-table door its own Data page already uses, under the same `MAX_ROWS` the server
456
+ * already reports in `limits`. So this pulls nothing the product does not already pull, and the
457
+ * mounted grid paints the server's own cap sentence through `counts.limitSummary` with no second
458
+ * opinion authored here.
459
+ *
460
+ * ⚠ ONLY A **FORWARD** EDGE IS PROJECTABLE, and that is a real boundary rather than a first cut.
461
+ * A forward link's pid list is a cell on the record already in hand. A reverse or bridge edge
462
+ * keeps its list on the OTHER table's rows, so finding it would mean reading that whole table and
463
+ * scanning a column — a different and far more expensive thing than reading a cell. Those stay
464
+ * `refused`, naming their cause, until the server's rows door learns a relation predicate.
465
  */
466
  type RelatedTabState =
467
  | { status: "probing" }
468
  | { status: "ready" }
469
+ | { status: "projected" }
470
+ | { status: "refused"; reason: string; code: string; table?: string; hop?: string };
471
+
472
+ /**
473
+ * ⭐⭐ W53-T24 · R13 — **WHO THE REFUSAL IS ABOUT**, and it is the SERVER'S OWN DATUM every time.
474
+ *
475
+ * ⛔ THIS AUTHORS NO PROSE AND MINES NONE. R13 asks "you may not see this table" and "this hop
476
+ * was filtered" to NAME their subject, and the envelope already carries `table` and `hop` as
477
+ * fields; reading the subject out of the sentence with a regular expression would make this file
478
+ * a second author of one wire contract, which is the failure `unpinnableNote`'s comment guards
479
+ * against directly above. The sentence stays the server's, whole; this only decides what is
480
+ * emphasised above it.
481
+ *
482
+ * ⚠ THE TABLE GOES THROUGH THE DISPLAY-NAME ROSTER, the one producer of a database's name in
483
+ * this product (`fetchLinkTargets`), because a raw `ut_odoo_order_lines` on screen is a key and
484
+ * not a name. A hop is an EDGE key with no roster of its own, so it takes the house transform
485
+ * `relatedTabs` already uses on a column (`_` to space), sentence case per DESIGN.
486
+ * ⭐ AND THE TABLE MAY BE THE INTERMEDIATE OF A TWO-HOP PATH. That is not an edge case bolted
487
+ * on: it is the case R13 was written for, and it needs no branch here precisely because the
488
+ * server names whichever table the wall was on.
489
+ */
490
+ function hopWords(hop: string): string {
491
+ const words = hop.replace(/_/g, " ").trim();
492
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : "";
493
+ }
494
+
495
+ function refusalSubject(
496
+ code: string,
497
+ labelFor: (table: string) => string,
498
+ table?: string,
499
+ hop?: string,
500
+ ): string {
501
+ /* ⚠ NAMED RATHER THAN LEFT TO THE FALLBACK, so R13's three codes are three VISIBLE branches
502
+ in one place. `no_related_rows` carries no subject on purpose: it is an empty state, not a
503
+ wall, and there is nobody to name. C3 also makes it a LISTING answer only (a path that
504
+ resolves is a path that exists), so the pinned probe cannot reach this line at all. */
505
+ if (code === RELATED_REFUSAL.noRelatedRows) return "";
506
+ if (code === RELATED_REFUSAL.forbiddenTable && table) return labelFor(table) || table;
507
+ if (code === RELATED_REFUSAL.hopFiltered && hop) return hopWords(hop);
508
+ return "";
509
+ }
510
 
511
  /**
512
  * ⭐ W51-T06 CLAUSE 9 — ONE HOP of the record view's navigation, carrying everything needed to
 
519
  label: string;
520
  record: Row;
521
  fields: Field[];
522
+ /**
523
+ * ⭐⭐ W53-T22 (R4) — THE PIN THAT PRODUCED THIS FRAME, so the chevrons can page its SIBLINGS.
524
+ *
525
+ * ⛔ IT IS THE **PARENT'S** PIN, AND THAT IS NOT A BUG IN THE NAMING. A pinned read is
526
+ * `{table: the table the record lives in, record: its pid, via: the edge}` — the customer and
527
+ * the customer-to-orders edge — and the rows it answers with are the ORDERS. So the pin that
528
+ * fetched the row this frame was pushed from is exactly the pin that fetches the row set this
529
+ * frame belongs to, which is what "sibling" means here.
530
+ * ⚠ `null` when the frame was pushed with no live pin. That is the honest unknown: the
531
+ * chevrons go disabled and the caption says nothing, rather than paging a guess.
532
+ */
533
+ pin: RelatedPin | null;
534
  }
535
 
536
+ /**
537
+ * ⭐⭐ W53-T22 — STABLE EMPTY IDENTITIES, module level, and they are load-bearing rather than
538
+ * tidy. `entries` and the sibling row set below are DERIVED per render from a stamped state
539
+ * (see `recordTable`'s note); a fresh `[]` at each of those sites would be a new identity every
540
+ * render, and both feed `useMemo`/`useEffect` dependency lists that would then churn forever.
541
+ */
542
+ const EMPTY_ENTRIES: RelatedEntry[] = [];
543
+ /** ⭐ W53-T24 — and the listing's refusals need one for exactly the same reason. */
544
+ const EMPTY_REFUSALS: RelatedRefusal[] = [];
545
+ const EMPTY_ROWS: Row[] = [];
546
+ const EMPTY_FIELDS: Field[] = [];
547
+
548
  /**
549
  * ⭐⭐ CLAUSE 10's STORE, AND IT IS `localStorage` BECAUSE R5 SAYS **"nothing new is stored"**.
550
  *
 
606
  * exists for exactly one state, and it says the same three things the server's own do: what was
607
  * asked, why it cannot be answered, and what to do instead.
608
  * ⛔ NO EM DASH AND NO EN DASH: this reaches a screen (standing rule 2).
609
+ *
610
+ * ⭐⭐ W53-T25 · D-657 — IT SURVIVES, AND IT IS NOW REACHED BY STRICTLY LESS. D-657's recorded
611
+ * exit says to delete this; deleting it outright would leave the roster-says-no state with no
612
+ * words at all, because the server still has no sentence for a fact about the CLIENT's read path.
613
+ * What changed is who reaches it: a FORWARD edge whose pid list is a cell on this record is now
614
+ * `projected` and shows rows, so this sentence is left to the edges that genuinely cannot be
615
+ * narrowed today (reverse, bridge, and a record that carries no link column at all). It should
616
+ * survive until the rows door itself learns a relation predicate, at which point the state it
617
+ * describes stops existing and it goes with it.
618
  */
619
  function unpinnableNote(target: string): string {
620
  return `'${target}' is not read through the live mirror on this deployment, so its rows door `
 
622
  + `database on its own and filter it there, or ask for its stored read to accept a pin`;
623
  }
624
 
625
+ /**
626
+ * ⭐⭐ W53-T25 — THE PIDS IN A LINK CELL, and the shape is the one this product already stores.
627
+ *
628
+ * A link cell is a COMMA-JOINED PID STRING. The precedent is `CustomerGrid`'s own reader
629
+ * (`linkValue.split(",")…`), and this is that reader, inlined rather than shared: there is no
630
+ * exported helper for it today and `CustomerGrid.tsx` is not this ticket's fence, so the choice
631
+ * is one more copy or an edit to a file this lane does not own. ⚠ IF ONE IS EVER EXPORTED, THIS
632
+ * IS THE CALL SITE TO DELETE — two spellings of one storage format is how a link column comes to
633
+ * mean different things in two panels.
634
+ *
635
+ * ⛔ DE-DUPLICATED AND FAIL-CLOSED. A blank, a stray separator or anything that is not a positive
636
+ * integer is DROPPED rather than coerced: a `NaN` in this list projects nothing and reads on
637
+ * screen as "no linked records", which is a wrong answer wearing the right chrome.
638
+ */
639
+ function linkedPids(value: unknown): number[] {
640
+ const raw = value === null || value === undefined ? "" : String(value);
641
+ if (!raw.trim()) return [];
642
+ const seen = new Set<number>();
643
+ for (const part of raw.split(",")) {
644
+ const pid = Number(part.trim());
645
+ if (Number.isInteger(pid) && pid > 0) seen.add(pid);
646
+ }
647
+ return [...seen];
648
+ }
649
+
650
  function relatedScope(target: string): SurfaceScope {
651
  if (target === CUSTOMER_TOPIC.key) return CUSTOMER_TOPIC.scope as SurfaceScope;
652
  if (target === PRODUCT_TOPIC.key) return PRODUCT_TOPIC.scope as SurfaceScope;
 
715
  setStack((prev) => (prev.length ? [] : prev));
716
  }, [baseRecord.pid, scope]);
717
  /**
718
+ * ⭐⭐ W53-T22 (R4) — THE ONE PLACE THE STACK IS SHORTENED, and it is one place on purpose.
719
+ *
720
+ * `depth` is the number of pushed frames to KEEP, which is also the crumb index: crumb 0 is the
721
+ * BASE record, so `popTo(0)` empties the stack and `popTo(1)` keeps the first hop. A NEGATIVE
722
+ * depth counts back from the top, so `popTo(-1)` is "up one level" and `popFrame` is that and
723
+ * nothing else. Writing the slice twice is how the breadcrumb and the back control would come
724
+ * to disagree about what "one level" means the first time either was touched.
725
  */
726
+ const popTo = useCallback((depth: number) => {
727
+ setStack((prev) => {
728
+ const keep = depth < 0 ? prev.length + depth : depth;
729
+ return keep >= prev.length ? prev : prev.slice(0, Math.max(0, keep));
730
+ });
731
+ }, []);
732
+ const popFrame = useCallback(() => popTo(-1), [popTo]);
 
 
 
 
 
 
 
 
 
733
  const title = frame ? frame.label : String(record[titleKey] ?? "Untitled");
734
+ /** ⭐ W53-T22 — the FIRST crumb's words, and they come from the BASE record rather than from
735
+ * `title`, which follows the frame and would spell the deepest hop twice. */
736
+ const baseLabel = String(baseRecord[titleKey] ?? "") || "Untitled";
737
  // Wave 19 (item 12): `scope` joins the predicate — the comments rail addresses a server
738
  // endpoint per topic now, so a host that names no surface gets no rail rather than a rail
739
  // pointed at a guess. In practice CustomerGrid always names one; this is the fail-closed edge.
 
893
  /**
894
  * R2's answer for this table. Empty until it arrives and empty on any failure, which is the
895
  * honest degradation: a record whose relations cannot be listed still opens on its Fields tab.
896
+ *
897
+ * ⭐⭐ W53-T22 (instr 7) — THE EDGES ARE HELD **WITH THE TABLE THEY WERE FETCHED FOR**, and
898
+ * that stamp is the whole fix for the owner's error sentence.
899
+ *
900
+ * ⛔ THE BUG WAS A ONE-RENDER READ OF STALE STATE, NOT A MISSING RESET. `recordTable` flips to
901
+ * the CHILD's table on the very render that pushes a frame, while `entries` still holds the
902
+ * PARENT's edges until an effect refetches them. For that one render the open tab still matched
903
+ * a parent edge, so `relatedPin` was built as `{table: the CHILD, via: the PARENT's edge}` and
904
+ * the mounted grid fired it from its own effect. `relations.py` then refused correctly: *"this
905
+ * account cannot resolve a relation named 'orders' on 'ut_odoo_orders'"*.
906
+ * ⛔ AND A `setTab("fields")` INSIDE THIS COMPONENT'S EFFECT CANNOT FIX IT. Child effects run
907
+ * BEFORE parent effects in React, so the mounted grid's request has already gone by the time
908
+ * the reset lands. An earlier attempt did exactly that; this is why it is not repeated.
909
+ * ⇒ STAMP THE STATE INSTEAD OF RESETTING IT. `entries` below is DERIVED, so on the push render
910
+ * the stamp does not match, the derived list is empty, `activeRelated` is null, no grid is
911
+ * mounted and no request is ever built. There is no effect ordering left to reason about.
912
  */
913
+ /* ⭐ W53-T24 — THE REFUSALS ARE STAMPED WITH THE SAME TABLE AS THE ENTRIES, deliberately in
914
+ one state rather than two. They arrive in one body and describe one listing; split across
915
+ two states they could be shown against a different record's edges for exactly one render,
916
+ which is the stale-read class this stamping exists to delete. */
917
+ const [related, setRelated] = useState<
918
+ { table: string; entries: RelatedEntry[]; refusals: RelatedRefusal[] }
919
+ >({ table: "", entries: EMPTY_ENTRIES, refusals: EMPTY_REFUSALS });
920
+ const entries = related.table === recordTable ? related.entries : EMPTY_ENTRIES;
921
+ const refusals = related.table === recordTable ? related.refusals : EMPTY_REFUSALS;
922
  /**
923
+ * ⭐ CLAUSE 2's OTHER HALF — `target key -> the DATABASE's own name`, which since W53-T23 is
924
+ * what a tab carries as its SUBTITLE, not as its label.
925
  *
926
+ * ⛔ THE ROSTER IS NOT THE TAB'S NAME, and the correction is the whole of that ticket: three
927
+ * different edges out of `customer_data` land on `ut_odoo_invoices`, so naming all three after
928
+ * the target rendered three rail rows reading "Odoo open invoices" (the owner's ERROR 21).
929
+ * The `/related` entry's own `label` is the per-EDGE name — measured in `relations.py`, where
930
+ * a FORWARD entry takes the FIELD's label, a REVERSE one the source table's and a BRIDGE the
931
+ * bridge's — so it leads, and this roster (`GET /tables?brief=1`, the one producer of a
932
+ * database's display name in this product) answers underneath it.
933
+ * ⚠ THE CALL BELOW DOES NOT CHANGE. `relatedTabs` owns that precedence, in `types.ts`; this
934
+ * file only hands it the roster lookup, exactly as before.
935
  */
936
  const [tableLabels, setTableLabels] = useState<Record<string, string>>({});
937
  useEffect(() => {
938
  // No scope, no tabs: the same fail-closed edge the comments rail takes. A pid means nothing
939
  // without the table it belongs to, and guessing one asks a question nobody asked.
940
  if (scope == null) {
941
+ setRelated((prev) => (prev.entries.length || prev.refusals.length
942
+ ? { table: "", entries: EMPTY_ENTRIES, refusals: EMPTY_REFUSALS }
943
+ : prev));
944
  return;
945
  }
946
  let live = true;
947
+ // ⚠ The table is captured, not re-read: what lands in state must be stamped with the table
948
+ // this call ASKED about, or a slow answer for the parent would be filed under the child.
949
+ // ⛔ AND THE CALL IS SPELLED `fetchRelated(recordTable)`, NOT `fetchRelated(forTable)`, even
950
+ // though the two hold the same value here. `verify_grid_ux.py:7143` asserts that exact
951
+ // literal as T06 clause 1 ("the tabs come from the SERVER's /related, not from this file
952
+ // reading link fields"), so renaming the argument reads to that gate as the server-sourced
953
+ // tab list having been torn out. The capture below is what the stamping needs; the argument
954
+ // is what the gate needs; they are deliberately the same value written two ways.
955
+ const forTable = recordTable;
956
  void fetchRelated(recordTable).then((got) => {
957
+ /* ⭐⭐ W53-T24 · R12 — DEPTH 2 IS `fetchRelated`'s OWN DEFAULT, so this call site keeps the
958
+ exact literal `fetchRelated(recordTable)` that `verify_grid_ux.py:7143` asserts as T06
959
+ clause 1. A `, 2` written here would read to that gate as the server-sourced tab list
960
+ having been torn out, for a value the function already holds. */
961
+ if (live) setRelated({ table: forTable, entries: got.entries, refusals: got.refusals });
962
  });
963
  void fetchLinkTargets().then((targets) => {
964
  if (!live) return;
 
982
  * has disappeared (a link column deleted while the drawer was open) drops back to Fields
983
  * rather than rendering a panel for an edge that is no longer offered.
984
  */
985
+ /* ⭐⭐ W53-T22 — STAMPED WITH ITS TABLE, THE SAME WAY `related` IS, AND FOR THE SAME RENDER.
986
+ An edge key belongs to ONE database's relation list; carried across a hop it names an edge
987
+ the new table has never declared, which is the second half of the owner's error. Derived
988
+ rather than reset, so the push render reads `"fields"` and nothing downstream can see the
989
+ parent's selection at all.
990
+ ⚠ `setTab` STAYS A `(tab: string) => void`, so `RecordRail`'s props do not change and the
991
+ mount below stays byte-identical to what `verify_wiring.py` asserts. */
992
+ const [tabSel, setTabSel] = useState<{ table: string; key: string }>(
993
+ { table: "", key: "fields" }
994
+ );
995
+ const tab = tabSel.table === recordTable ? tabSel.key : "fields";
996
+ const setTab = useCallback(
997
+ (next: string) => setTabSel({ table: recordTable, key: next }),
998
+ [recordTable]
999
+ );
1000
  const activeTab = tabs.some((entry) => entry.entry.key === tab) ? tab : "fields";
1001
  const activeRelated = tabs.find((entry) => entry.entry.key === activeTab) ?? null;
1002
 
 
1038
  * ⚠ MEMOISED ON A SERIALISED KEY. The grid takes this as an effect dependency; a fresh object
1039
  * per render would re-read on every keystroke in the drawer.
1040
  */
1041
+ /* ⭐⭐ W53-T24 · RULING R12 · CONTRACT C3 — **THE BAG FOR ONE HOP, THE ARRAY FOR TWO**, and
1042
+ the branch is on the entry's OWN hop count rather than on anything reconstructed here.
1043
+
1044
+ R12: "the client pins a traversal by NAMING EACH EDGE (`via = ["orders","order_lines"]`),
1045
+ never a path search." `entry.path` is the server's array, handed over in the listing; this
1046
+ file selects it and never assembles one, which is the difference between naming a traversal
1047
+ and searching for it.
1048
+
1049
+ ⛔ AND THE ONE-HOP BRANCH IS UNCHANGED ON PURPOSE. MEASURED 2026-09-05 against the server on
1050
+ this branch: a pinned read with `via` as an ARRAY answers 400 `bad_relation`, and only the
1051
+ bag is accepted, because lane D's route is not merged here yet. Sending the array only when
1052
+ `hops === 2` makes this a NO-OP on today's wire (no entry reports two hops) and leaves the
1053
+ six one-hop tabs resolving byte for byte as they did at HEAD. */
1054
  const relatedPinKey = activeRelated
1055
  ? JSON.stringify({
1056
  table: recordTable,
1057
  record: Number(record.pid),
1058
+ via: activeRelated.entry.hops === 2
1059
+ ? activeRelated.entry.path
1060
+ : activeRelated.entry.via,
1061
  label: title,
1062
  })
1063
  : "";
 
1069
  [relatedPinKey]
1070
  );
1071
 
1072
+ /**
1073
+ * ⭐⭐ W53-T25 · D-657 — **THE PID LIST A FORWARD EDGE ALREADY HANDED US**, or `null` when this
1074
+ * edge is not projectable at all. See `RelatedTabState` above for why this exists and why it is
1075
+ * bounded to forward edges.
1076
+ *
1077
+ * ⛔ NOTHING IS FETCHED HERE AND NOTHING NEEDS TO BE. `via.field` names a column on THIS
1078
+ * record's own row, which this panel is already holding, so the list is read straight out of the
1079
+ * cell. A reverse or bridge edge keeps its list on the OTHER table's rows and cannot be answered
1080
+ * from anything in hand, which is precisely why those stay refused.
1081
+ * ⚠ THE COLUMN IS CHECKED AGAINST THE FIELD CONTRACT, NOT AGAINST THE ROW. An absent key on a
1082
+ * row is a blank cell (nothing linked yet) and belongs in the empty state; a column this table
1083
+ * never declared is not projectable and belongs in the refusal, with its cause. Reading only the
1084
+ * row would collapse those two into one answer, and the wrong one.
1085
+ * ⚠ MEMOISED ON A SERIALISED KEY, the discipline `relatedPin` above uses and for the same
1086
+ * reason: this feeds an effect's dependency list, and a fresh array per render would re-probe
1087
+ * the server on every keystroke in this drawer.
1088
+ */
1089
+ const projectedIdsKey = (() => {
1090
+ const via = activeRelated?.entry.via;
1091
+ const column = via?.field;
1092
+ if (!via || via.direction !== "forward" || !column) return "";
1093
+ if (!fields.some((field) => field.key === column)) return "";
1094
+ return JSON.stringify(linkedPids(record[column]));
1095
+ })();
1096
+ const projectedIds = useMemo(
1097
+ () => (projectedIdsKey ? (JSON.parse(projectedIdsKey) as number[]) : null),
1098
+ [projectedIdsKey]
1099
+ );
1100
+
1101
+ /**
1102
+ * ⭐ CLAUSE 9's FORWARD HALF. The row, the fields and the table all arrive from the grid that
1103
+ * already had them; only the LABEL is derived here, and only from what came with the row.
1104
+ * ⚠ `title` on a frame is the frame's own label: `titleKey` belongs to the base table and
1105
+ * reading it off a foreign row answers "Untitled" for every one of them.
1106
+ *
1107
+ * ⭐⭐ W53-T22 — IT IS DECLARED **HERE**, BELOW `relatedPin`, RATHER THAN BESIDE `popFrame`.
1108
+ * A frame has to carry the pin that produced it (see `RecordFrame.pin`) and that pin is
1109
+ * derived from the open tab thirty lines above this; a ref written from render to smuggle it
1110
+ * upwards would be the same stale read this ticket exists to delete, one indirection along.
1111
+ */
1112
+ const pushFrame = useCallback(
1113
+ (pid: number, table: string, row?: Row, rowFields?: Field[]) => {
1114
+ if (!row || !rowFields || rowFields.length === 0) return;
1115
+ const first = rowFields[0];
1116
+ const named = first ? String(row[first.key] ?? "") : "";
1117
+ setStack((prev) => [...prev, {
1118
+ table,
1119
+ pid,
1120
+ label: named || `Record ${pid}`,
1121
+ record: row,
1122
+ fields: rowFields,
1123
+ // ⛔ THE PIN WITHOUT ITS `label`. `RelatedPin` is `{table, record, via}` and carries no
1124
+ // display words on purpose (`types.ts::RelatedPin`); folding the chip's sentence in
1125
+ // would fork the rows cache key on a rename.
1126
+ pin: relatedPin
1127
+ ? { table: relatedPin.table, record: relatedPin.record, via: relatedPin.via }
1128
+ : null,
1129
+ }]);
1130
+ },
1131
+ [relatedPin]
1132
+ );
1133
+
1134
+ /* ═══════════════════════════════════════════════════════════════════════════════════════
1135
+ ⭐⭐ W53-T22 · OWNER RULING R4 — **THE CHEVRONS ALWAYS PAGE SIBLINGS.**
1136
+
1137
+ R4, verbatim: *"Record-detail drill navigation: the `‹ ›` chevrons ALWAYS page siblings in
1138
+ the database currently displayed. Drill history is a clickable breadcrumb across the top
1139
+ plus Escape to go up one level."*
1140
+
1141
+ ⛔ WHAT THIS REPLACES. The header used to swap the two chevrons for a single history back
1142
+ arrow the moment a frame was pushed, which is drill history living in the chevrons — the
1143
+ one arrangement R4 names and forbids. History moved to the crumb strip and to Escape; the
1144
+ chevrons stayed chevrons and now need a row set of their OWN on a pushed frame, because the
1145
+ host's `canPrev`/`canNext` describe the BASE grid and are not repurposed (R4).
1146
+
1147
+ ⛔ THE SIBLING SET IS THE FRAME'S OWN PIN, READ THROUGH THE WINDOWED DOOR. `frame.pin` is
1148
+ the pin that fetched the row this frame was pushed from, so the same pin fetches the rest of
1149
+ that row set. One window, no predicate, no sort: whatever the related tab was showing.
1150
+ ⚠ GUARDED ON `readThroughTables()` BEFORE THE CALL, mirroring `tabState`'s own guard below.
1151
+ `fetchTableWindow` raises `DATA_ERROR_EVENT` on a refusal, which replaces the entire surface
1152
+ with an error card — a sibling list that cannot be fetched must degrade to DISABLED
1153
+ chevrons and a silent caption, never to a broken screen.
1154
+ ═══════════════════════════════════════════════════════════════════════════════════════ */
1155
+ const framePinKey = frame && frame.pin
1156
+ ? JSON.stringify({ table: frame.table, pin: frame.pin })
1157
+ : "";
1158
+ const [siblings, setSiblings] = useState<{ key: string; rows: Row[]; fields: Field[] }>(
1159
+ { key: "", rows: EMPTY_ROWS, fields: EMPTY_FIELDS }
1160
+ );
1161
+ useEffect(() => {
1162
+ if (!framePinKey) return;
1163
+ const asked = JSON.parse(framePinKey) as { table: string; pin: RelatedPin };
1164
+ let live = true;
1165
+ void (async () => {
1166
+ const through = await readThroughTables();
1167
+ // ⛔ Not read through ⇒ no request at all. See the guard note above.
1168
+ if (!live || !through.has(asked.table)) return;
1169
+ const payload = await fetchTableWindow(asked.table,
1170
+ { offset: 0, limit: WINDOW_ROWS, related: asked.pin });
1171
+ if (!live || !payload) return;
1172
+ setSiblings({ key: framePinKey, rows: payload.rows, fields: payload.fields });
1173
+ })();
1174
+ return () => {
1175
+ live = false;
1176
+ };
1177
+ }, [framePinKey]);
1178
+
1179
+ /* Stamped, like everything else this ticket touched: a set fetched for the previous frame is
1180
+ not this frame's, and reading it would number the reader against another database's rows. */
1181
+ const siblingRows = framePinKey && siblings.key === framePinKey ? siblings.rows : EMPTY_ROWS;
1182
+ const siblingIndex = frame
1183
+ ? siblingRows.findIndex((row) => Number(row.pid) === frame.pid)
1184
+ : -1;
1185
+ const frameCanPrev = siblingIndex > 0;
1186
+ const frameCanNext = siblingIndex >= 0 && siblingIndex < siblingRows.length - 1;
1187
+ /**
1188
+ * One step along the frame's own row set. It REPLACES the top frame rather than pushing one,
1189
+ * so paging orders inside a customer leaves the breadcrumb reading `Customer / Order` at the
1190
+ * same depth it already had; a push would grow a trail out of a sideways move.
1191
+ * ⚠ The replacement is built exactly the way `pushFrame` builds one, from the payload's own
1192
+ * `fields` and the sibling row, and it inherits the same pin because it is the same row set.
1193
+ */
1194
+ const stepFrame = useCallback(
1195
+ (delta: number) => {
1196
+ if (!frame || siblingIndex < 0) return;
1197
+ const next = siblingRows[siblingIndex + delta];
1198
+ if (!next) return;
1199
+ const first = siblings.fields[0];
1200
+ const named = first ? String(next[first.key] ?? "") : "";
1201
+ const pid = Number(next.pid);
1202
+ setStack((prev) => (prev.length === 0 ? prev : [...prev.slice(0, -1), {
1203
+ table: frame.table,
1204
+ pid,
1205
+ label: named || `Record ${pid}`,
1206
+ record: next,
1207
+ fields: siblings.fields,
1208
+ pin: frame.pin,
1209
+ }]));
1210
+ },
1211
+ [frame, siblingIndex, siblingRows, siblings.fields]
1212
+ );
1213
+ /**
1214
+ * The frame's own caption, in the host's shape (`Record 3 of 3,673`) with the DATABASE's name
1215
+ * where the host says "Record", because on a frame the reader needs to know which database
1216
+ * they are counting through. Empty whenever the set is unknown: not read through, the fetch
1217
+ * failed, or this pid is not in the window. Disabled and silent, never a wrong number.
1218
+ */
1219
+ const framePositionLabel = frame && siblingIndex >= 0
1220
+ ? `${tableLabels[frame.table] || "Record"} ${(siblingIndex + 1).toLocaleString()} of `
1221
+ + `${siblingRows.length.toLocaleString()}`
1222
+ : "";
1223
+
1224
+ /**
1225
+ * ⭐⭐ R4's OTHER HALF — THE DRILL TRAIL, as crumbs. The BASE record first, then one per pushed
1226
+ * frame, and the index of a crumb IS the `popTo` depth that returns to it (crumb 0 keeps zero
1227
+ * frames, which is the base record).
1228
+ * ⚠ The key carries the INDEX as well as the pid: the same order can legitimately appear twice
1229
+ * in one trail (order -> line -> the same order through a back-reference), and two React
1230
+ * children cannot share a key.
1231
+ */
1232
+ const crumbs = useMemo(
1233
+ () => [
1234
+ { key: "base", label: baseLabel },
1235
+ ...stack.map((entry, index) => ({
1236
+ key: `${entry.table}:${entry.pid}:${index}`,
1237
+ label: entry.label,
1238
+ })),
1239
+ ],
1240
+ [baseLabel, stack]
1241
+ );
1242
+
1243
  /**
1244
  * ⭐⭐ CAN THIS EDGE BE SERVED, AND IF NOT, IN WHOSE WORDS? See `RelatedTabState`.
1245
  *
 
1286
  setTabState({ status: "ready" });
1287
  return;
1288
  }
1289
+ /* ⭐⭐ W53-T25 · D-657 — THE THIRD OUTCOME, AND THE ROSTER IS STILL WHAT SEPARATES IT FROM
1290
+ THE FIRST. `through.has(target)` is asked again rather than inferred from `!pinnable`,
1291
+ because those two come apart on exactly the edge that matters: a target the roster DOES
1292
+ name whose entry is `served: false` is a read-through table, and pulling one whole is the
1293
+ standing-rule-1 violation this branch must never commit. Not on the roster ⇒ the whole
1294
+ table is what its own Data page reads anyway, through the same door, under the same
1295
+ reported cap. See `RelatedTabState` and `projectedIds`. */
1296
+ if (!through.has(target) && projectedIds) {
1297
+ setTabState({ status: "projected" });
1298
+ return;
1299
+ }
1300
+ const refused = await probeRelatedRead(target, pin);
1301
  if (!live) return;
1302
+ /* ⚠ A `null` here means the pinned door answered 200 while the ROSTER said no, which is
1303
+ the one state with no server sentence (see `unpinnableNote`) and therefore no code
1304
+ either. `""` sends it down the plain branch, which is exactly where it belongs. */
1305
+ setTabState({
1306
+ status: "refused",
1307
+ reason: refused?.reason ?? unpinnableNote(target),
1308
+ code: refused?.code ?? "",
1309
+ table: refused?.table,
1310
+ hop: refused?.hop,
1311
+ });
1312
  })();
1313
  return () => {
1314
  live = false;
1315
  };
1316
+ }, [activeRelated, relatedPin, projectedIds]);
1317
+
1318
+ /** ⭐ W53-T24 · R13 — the emphasised subject of the open tab's refusal, or `""` for the two
1319
+ * states that have none (`no_related_rows`, and any code this client does not know). */
1320
+ const refusedSubject = tabState.status === "refused"
1321
+ ? refusalSubject(
1322
+ tabState.code,
1323
+ (table) => tableLabels[table] ?? "",
1324
+ tabState.table,
1325
+ tabState.hop,
1326
+ )
1327
+ : "";
1328
+
1329
+ /**
1330
+ * ⭐⭐ W53-T25 · D-657 — **AN EMPTY LINK CELL IS AN ANSWER, NOT A REFUSAL**, and it gets words
1331
+ * of its own rather than a grid with no rows in it.
1332
+ *
1333
+ * ⛔ THE FAILURE THIS AVOIDS IS W53-T24's, ONE STATE ALONG: an empty grid reads as "nothing is
1334
+ * linked" whatever actually happened, so the one case where that IS the truth still has to say
1335
+ * so out loud to be distinguishable from the cases where it is not. It also spares a whole-table
1336
+ * read taken to project an empty list.
1337
+ * ⛔ NO EM DASH AND NO EN DASH: this reaches a screen (standing rule 2). Sentence case, two
1338
+ * short sentences, no card of its own (DESIGN section 4 allows one containment layer and the
1339
+ * drawer is already it).
1340
+ * ⚠ IT NAMES THE COLUMN, because "nothing linked" without a place to add one is a dead end.
1341
+ * The label comes from the record's own field contract, which `projectedIds` has already
1342
+ * established carries this column.
1343
+ */
1344
+ const emptyLinkNote = (() => {
1345
+ if (tabState.status !== "projected" || !activeRelated) return "";
1346
+ const target = activeRelated.entry.target;
1347
+ const database = tableLabels[target] || activeRelated.entry.label || target;
1348
+ const column = activeRelated.entry.via.field;
1349
+ const label = column ? fieldByKey.get(column)?.label ?? "" : "";
1350
+ /* ⚠ "Nothing from <database>" RATHER THAN "No <database> records": a display name is
1351
+ already plural about half the time on this tenant, and "No Odoo agents records" is the
1352
+ sentence that reads as a bug in the app rather than as an answer about the data. */
1353
+ const where = label ? ` Add a link in the ${label} field.` : "";
1354
+ return `Nothing from ${database} is linked to this record yet.${where}`;
1355
+ })();
1356
 
1357
  /**
1358
  * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
 
2002
 
2003
  // One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
2004
  // Focus stays inside it, then returns to the exact opener on close.
2005
+ /* ⭐⭐ W53-T22 (R4) — **ESCAPE GOES UP ONE LEVEL** while a frame is on screen, and closes the
2006
+ drawer only from the base record. R4 names Escape as the other half of drill history, beside
2007
+ the breadcrumb, and a reader two hops deep who presses it expects to come back one hop, not
2008
+ to lose the whole record.
2009
+ ⚠ THIS HOOK TAKES **ONE** `onDismiss` AND FIRES IT FOR BOTH ESCAPE AND AN OUTSIDE
2010
+ POINTERDOWN (`OverlaySurface.tsx::useOverlayLayer` — one `dismissRef`, read by
2011
+ `useEscapeClose` and by the pointerdown listener alike); there is no second hook to split
2012
+ them. So an outside click on a pushed frame ALSO goes up one level. That is a deliberate
2013
+ reading of "dismiss the thing on top" rather than an oversight: the thing on top is the
2014
+ frame, and dismissing the whole drawer from under a reader who is three hops in would throw
2015
+ away more than the gesture asked for. */
2016
  useOverlayLayer({
2017
  panelRef,
2018
+ onDismiss: stack.length > 0 ? popFrame : onClose,
2019
  dismissOnOutside: true,
2020
  initialFocus: "[data-overlay-autofocus]",
2021
  trapFocus: true,
 
2044
  <div className="cg-record-shell">
2045
  <div className="cg-detail-header">
2046
  <div className="cg-detail-nav">
2047
+ {/* ⭐⭐ W53-T22 (OWNER RULING R4) — TWO CHEVRONS, ALWAYS, AND THEY ALWAYS PAGE
2048
+ SIBLINGS OF WHAT IS ON SCREEN.
2049
+ ⛔ WHAT WAS HERE AND WHY IT WENT. W51-T06 replaced this pair with a single
2050
+ history back arrow on a pushed frame. R4 forbids exactly that: *"the `‹ ›`
2051
+ chevrons ALWAYS page siblings in the database currently displayed. Drill history
2052
+ is a clickable breadcrumb across the top plus Escape to go up one level."*
2053
+ ⛔ AND THE OLD COMMENT'S FEAR IS STILL ANSWERED, JUST DIFFERENTLY. It warned that
2054
+ prev/next walk the HOST grid's row order, which a pushed record is not in, so
2055
+ they would move the base record silently underneath the one on screen. They no
2056
+ longer do: on a frame these read `frameCanPrev`/`frameCanNext` and `stepFrame`,
2057
+ which page the FRAME's own row set (`siblings`) and touch the base record not at
2058
+ all. `canPrev`/`canNext` keep meaning N of M in the base database (R4). */}
 
 
 
 
 
 
 
2059
  <button
2060
  type="button"
2061
  className="cg-detail-navbtn"
2062
+ onClick={frame ? () => stepFrame(-1) : onPrev}
2063
+ disabled={frame ? !frameCanPrev : !canPrev}
2064
  aria-label="Previous record"
2065
  title="Previous record"
2066
  >
 
2069
  <button
2070
  type="button"
2071
  className="cg-detail-navbtn"
2072
+ onClick={frame ? () => stepFrame(1) : onNext}
2073
+ disabled={frame ? !frameCanNext : !canNext}
2074
  aria-label="Next record"
2075
  title="Next record"
2076
  >
2077
  ›
2078
  </button>
 
 
2079
  {/* ⭐⭐ W35-T29 (R5, R6) — THE SAME RECORD STAR AS THE GRID'S, in the drawer.
2080
  ⛔ THE SAME STATE, NOT A SECOND ONE: `starred`/`onStar` come from the grid's own
2081
  `useRecordStars`, so starring here and starring in the row are one act on one list.
 
2107
  </button>
2108
  )}
2109
  {/* ⚠ W51-T06 — the caption counts the HOST grid's rows, so a pushed frame has
2110
+ no position in it and says nothing rather than a number about somewhere else.
2111
+ ⭐ W53-T22 (R4) — a pushed frame now HAS a position, in its own database, so it
2112
+ reads one: `Orders 3 of 12`, the host's own shape with the database's name where
2113
+ the host says "Record". It falls back to silence, not to a guess, whenever the
2114
+ sibling set could not be read (see `framePositionLabel`). */}
2115
+ <span className="cg-detail-pos">{frame ? framePositionLabel : positionLabel}</span>
2116
  </div>
2117
  <button
2118
  type="button"
 
2126
  </button>
2127
  </div>
2128
 
2129
+ {/* ═══════════════════════════════════════════════════════════════════════════════
2130
+ ⭐⭐ W53-T22 (instruction 7, OWNER RULING R4) — THE DRILL TRAIL, ACROSS THE TOP.
2131
+
2132
+ R4: *"Drill history is a clickable breadcrumb across the top plus Escape to go up
2133
+ one level."* This is that breadcrumb, and it exists ONLY while something has been
2134
+ drilled into: on the base record there is no trail to draw and a one-crumb strip
2135
+ would be a permanent empty band over every record in the product.
2136
+
2137
+ ⛔ A SIBLING OF THE HEADER, NOT A CHILD OF IT. `.cg-record-shell` is the column
2138
+ that stacks header over layout, so a crumb row placed here spans the full drawer
2139
+ width the way the header does; inside `.cg-detail-nav` it would have been squeezed
2140
+ between two 28px keys and the close button.
2141
+
2142
+ ⛔ THE EXISTING BREADCRUMB ATOMS, NOT A SECOND BREADCRUMB SHAPE. `cg-path-segments`
2143
+ / `cg-path-segment-wrap` / `cg-path-separator` / `cg-path-segment` /
2144
+ `cg-path-history-button` are unscoped rules in `index.css` and are already worn by
2145
+ `ViewSidebar.tsx` and `SheetRail.tsx`. Only `.cg-record-path`, the strip's own
2146
+ wrapper, is new, and it lives in `RecordDetail.css`. A third crumb treatment is how
2147
+ two of the three would drift the first time either was touched.
2148
+ ⛔ THE SEPARATOR IS AN ASCII SLASH. Standing rule 2, and a breadcrumb is the single
2149
+ most likely place in the product for a dash to be typed.
2150
+
2151
+ ⭐ THE BACK KEY RIDES IN THE STRIP RATHER THAN IN THE CHEVRONS, which is the whole
2152
+ point of R4: history here, siblings there. It is the same `popFrame` the Escape key
2153
+ fires, so the two doors out of a hop cannot come to mean different things.
2154
+ ═══════════════════════════════════════════════════════════════════════════════ */}
2155
+ {stack.length > 0 && (
2156
+ <nav className="cg-record-path" aria-label="Record trail">
2157
+ <button
2158
+ type="button"
2159
+ className="cg-path-history-button"
2160
+ onClick={popFrame}
2161
+ aria-label="Back to the record you came from"
2162
+ title="Back to the record you came from"
2163
+ >
2164
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
2165
+ <path
2166
+ d="M10 3.5 5.5 8l4.5 4.5"
2167
+ stroke="currentColor"
2168
+ strokeWidth="1.5"
2169
+ strokeLinecap="round"
2170
+ strokeLinejoin="round"
2171
+ />
2172
+ </svg>
2173
+ </button>
2174
+ <div className="cg-path-segments">
2175
+ {crumbs.map((crumb, index) => (
2176
+ <span className="cg-path-segment-wrap" key={crumb.key}>
2177
+ {index > 0 ? (
2178
+ <span className="cg-path-separator" aria-hidden="true">
2179
+ /
2180
+ </span>
2181
+ ) : null}
2182
+ {/* ⚠ EVERY crumb is a live button, the LAST one included. `popTo` on the
2183
+ current depth is a no-op that returns the same array, so React bails out
2184
+ and nothing repaints; disabling it (the Data rail's own choice for a
2185
+ folder path) would make the crumb the reader is looking at the one thing
2186
+ they cannot click, which is not what instruction 7 asked for. */}
2187
+ <button
2188
+ type="button"
2189
+ className="cg-path-segment"
2190
+ title={crumb.label}
2191
+ aria-current={index === crumbs.length - 1 ? "page" : undefined}
2192
+ onClick={() => popTo(index)}
2193
+ >
2194
+ {crumb.label}
2195
+ </button>
2196
+ </span>
2197
+ ))}
2198
+ </div>
2199
+ </nav>
2200
+ )}
2201
+
2202
+ {/* ⭐⭐ W53-T21 (instr 5) — THE COMMENTS COLUMN IS RESERVED SPACE, NOT RENDERED
2203
+ CONTENT, AND THE TWO HAD DRIFTED APART. `RecordComments` below is already withheld
2204
+ on a linked-database tab (`activeTab === "fields"`, W52-T24), but the layout that
2205
+ reserves a >=300px column for it never learned the same fact, so an empty column
2206
+ sat beside a squeezed embedded grid. `activeRelated` is the SAME edge lookup that
2207
+ decides which tab is open, so one linked tab collapses this to a single full-width
2208
+ column and Details (`activeRelated === null`) restores both.
2209
+ ⭐ THE VALUE IS THE OPEN EDGE KEY, not an empty marker: `[data-related-tab]` matches
2210
+ either way, and the key makes the open linked database legible in the DOM to a
2211
+ reader and to a screenshot review.
2212
+ ⚠ A `data-*` ATTRIBUTE, AND THE CLASS STAYS THE LITERAL STRING: the layout gate
2213
+ (`verify_record_layout.py::drawer_anatomy_shape`) greps this file for exactly
2214
+ `className="cg-record-layout"`, so concatenating a modifier into the class would
2215
+ read as the two-column drawer having been removed. The static string a gate can
2216
+ grep and the conditional behaviour a reader needs live as two things on one
2217
+ element, and the collapse itself is a CSS rule in RecordDetail.css. */}
2218
+ <div
2219
+ className="cg-record-layout"
2220
+ data-related-tab={activeRelated ? activeRelated.entry.key : undefined}
2221
+ >
2222
  <main className="cg-record-main">
2223
  <div className="cg-detail-titlewrap">
2224
  <div className="cg-detail-title" id={titleId} title={title}>
 
2235
  <div className="cg-record-related">
2236
  {/* ⭐⭐ CLAUSES 4 + 6 + 7 — THE TARGET DATABASE'S OWN GRID, over rows the SERVER
2237
  narrowed to this record.
2238
+ ⛔ NO `embedded` AND NO `embeddedRecordIds` **ON THIS MOUNT**. That pair is the
2239
+ mode that hides the view rail and pulls the whole table into the browser to
2240
+ filter it there; R5 asks for the target's own saved views WITH the rail, over a
2241
+ pre-filtered read. Passing `related` and passing `embedded` are mutually
2242
+ exclusive by design, and this mount passes only the first.
2243
+ ⚠ W53-T25 · D-657 — THE OTHER MOUNT EXISTS AGAIN, and it is a sibling of this
2244
+ one rather than a replacement for it: a target the read-through roster does not
2245
+ name has no pre-filtered read to ask for, so `projected` mounts the `embedded`
2246
+ pair below. Neither mount ever passes both.
2247
  ⛔ THE GRID IS THE PANEL, not a card inside one. DESIGN section 4 allows ONE
2248
  containment layer and the drawer is already it; a bordered box around a grid
2249
  inside a drawer inside a modal is the card-in-card the section names. */}
2250
+ {/* ⭐⭐ W53-T24 · RULING R13 — **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud.
2251
+ A traversal filtered out of the rail is otherwise a tab that never appears, and
2252
+ a tab that never appears is indistinguishable from an edge that was never
2253
+ declared. `refusals` is `[]` whenever nothing was walled off, so this block is
2254
+ absent on every ordinary record rather than a permanent apology.
2255
+ ⚠ IN THE PANEL, NOT AN OVERLAY, and a FLEX ITEM of `.cg-record-related` rather
2256
+ than a sibling of it: that wrapper is `height: 100%` of the scrolling body
2257
+ (`styles/wave51/grid.css`), so a paragraph placed BEFORE it would push a
2258
+ full-height block down and overflow the drawer. Inside, the grid keeps
2259
+ `flex: 1 1 auto` and simply takes the remaining height. */}
2260
+ {refusals.map((refusal) => {
2261
+ const subject = refusalSubject(
2262
+ refusal.code,
2263
+ (table) => tableLabels[table] ?? "",
2264
+ refusal.table,
2265
+ refusal.hop,
2266
+ );
2267
+ return (
2268
+ <p
2269
+ key={`${refusal.code}:${refusal.path.join(">")}`}
2270
+ className="cg-record-related-note"
2271
+ role="status"
2272
+ data-refusal={refusal.code}
2273
+ >
2274
+ {subject ? <><strong>{subject}</strong><br /></> : null}
2275
+ {refusal.message}
2276
+ </p>
2277
+ );
2278
+ })}
2279
  {tabState.status === "refused" ? (
2280
  /* ⭐ R6's SECOND SENTENCE — the limit, its cause and what to do instead, in the
2281
  SERVER's words. `role="status"` rather than `alert`: a declared relation that
2282
+ is not served yet is a reported boundary, not a failure.
2283
+ ⭐⭐ W53-T24 · R13 — AND THE THREE REFUSALS ARE THREE STATES, NOT ONE.
2284
+ · `no_related_rows` → the sentence alone, muted, no subject line. Not an error.
2285
+ · `forbidden_table` → the walled table NAMED above it, intermediate hop included.
2286
+ · `hop_filtered` → the filtered hop NAMED above it.
2287
+ · anything else → exactly what shipped before: the server's own sentence.
2288
+ ⛔ AND NOT ONE OF THEM IS AN EMPTY GRID. An empty grid reads as "this record has
2289
+ no related rows" whichever of the three actually happened, so two thirds of the
2290
+ time it is a WRONG answer wearing the right chrome — the failure class this
2291
+ ticket exists to delete.
2292
+ ⛔ THE SENTENCE IS STILL THE SERVER'S, WHOLE. The code chooses the treatment
2293
+ (what is emphasised, what the state is called in the DOM); it never rewrites the
2294
+ words, which would fork one wire contract into two opinions.
2295
+ ⚠ `data-refusal` IS THE STATE, MACHINE-READABLE. Three renders that differ only
2296
+ in prose cannot be told apart by QA or by a gate; this attribute is how the
2297
+ distinction survives a screenshot. */
2298
+ <p
2299
+ className="cg-record-related-note"
2300
+ role="status"
2301
+ data-refusal={tabState.code || undefined}
2302
+ >
2303
+ {refusedSubject ? <><strong>{refusedSubject}</strong><br /></> : null}
2304
+ {tabState.reason}
2305
+ </p>
2306
  ) : tabState.status === "probing" ? (
2307
  /* Owner R6 — one small bare rotating mark, NO WORDS on screen. The `aria-label`
2308
  is not a word on screen and stays, or the wait is announced as nothing at all
 
2310
  <p className="cg-record-related-note">
2311
  <span className="lp-spin" role="status" aria-label="Loading" />
2312
  </p>
2313
+ ) : tabState.status === "projected" ? (
2314
+ /* ⭐⭐ W53-T25 · D-657 — **THE ROWS AGAIN**, on a related tab whose target is an
2315
+ ordinary user table. This is wave 27's `LinkedGrid` mount, which W51-T06
2316
+ removed the last caller of: the target read through its OWN ordinary door and
2317
+ projected to the pid list this record's link cell already carries.
2318
+ ⛔ `embedded` AND `related` ARE MUTUALLY EXCLUSIVE BY CONSTRUCTION and this
2319
+ mount passes only the first, exactly as the `ready` mount above passes only the
2320
+ second. The two modes disagree about WHO evaluates the predicate (the browser
2321
+ here, the server there); passing both would ask one grid to do both and mean
2322
+ neither. There is no `relatedViewId` for the same reason: `embedded` hides the
2323
+ view rail (`hostViews = []`), so a remembered view would be a preference with
2324
+ nothing to apply it to.
2325
+ ⛔ AND THE CAP IS THE SERVER'S TO REPORT, NOT THIS PANEL'S TO GUESS.
2326
+ `routes_tables.table_rows` answers `limits` from its own `limit_report`, and
2327
+ the mounted grid already paints it through `counts.limitSummary` in the strip
2328
+ that carries every other "why is this number what it is" sentence. A second
2329
+ cap sentence written here would be this file inventing a limit the wire did
2330
+ not declare, which is the opposite of standing rule 1's second sentence. */
2331
+ projectedIds && projectedIds.length > 0 ? (
2332
+ <Suspense
2333
+ fallback={
2334
+ <p className="cg-record-related-note">
2335
+ <span className="lp-spin" role="status" aria-label="Loading" />
2336
+ </p>
2337
+ }
2338
+ >
2339
+ <RelatedGrid
2340
+ scope={relatedScope(activeRelated.entry.target)}
2341
+ embedded
2342
+ embeddedRecordIds={projectedIds}
2343
+ /* ⭐ CLAUSE 9 — a row click NAVIGATES THIS PANEL rather than stacking a
2344
+ second drawer on top of the one it is already inside. */
2345
+ onOpenRecord={pushFrame}
2346
+ />
2347
+ </Suspense>
2348
+ ) : (
2349
+ /* An empty link cell is an ANSWER. See `emptyLinkNote`. `role="status"` for
2350
+ the same reason the refusal above uses it: a reported state, not a failure.
2351
+ ⛔ AND IT IS **NOT** `data-refusal`. That attribute carries the SERVER's own
2352
+ refusal code (W53-T24 / R13) and nothing was refused here; spelling a client
2353
+ state into that namespace would make one attribute mean two things and put a
2354
+ value on it that `relations.py` can never emit. */
2355
+ <p
2356
+ className="cg-record-related-note"
2357
+ role="status"
2358
+ data-related-state="no-linked-records"
2359
+ >
2360
+ {emptyLinkNote}
2361
+ </p>
2362
+ )
2363
  ) : (
2364
  <Suspense
2365
  fallback={
web/src/customer-grid/RecordRail.tsx CHANGED
@@ -111,10 +111,31 @@ export default function RecordRail({ tabs, activeTab, onSelect }: RecordRailProp
111
  aria-current={activeTab === tab.entry.key ? "page" : undefined}
112
  onClick={() => onSelect(tab.entry.key)}
113
  >
114
- <span className="cg-record-rail-row-label">{tab.label}</span>
 
 
 
 
 
115
  {/* Clause 2 — the FIELD, and only when two edges share one target (R2). A second
116
  line under a row with no sibling would answer a question nobody asked. */}
117
- {tab.subtitle && <span className="cg-record-rail-row-sub">{tab.subtitle}</span>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  </button>
119
  ))}
120
  </div>
 
111
  aria-current={activeTab === tab.entry.key ? "page" : undefined}
112
  onClick={() => onSelect(tab.entry.key)}
113
  >
114
+ {/* ⚠ W53-T24 — `title` ON THE LABEL, and it is a legibility fix rather than
115
+ decoration: `.cg-record-rail-row-label` is `text-overflow: ellipsis` on one
116
+ line inside a narrow rail, so an edge whose name runs long is readable ONLY as
117
+ a tooltip. The attribute repeats the visible text exactly; it never says
118
+ something the row does not. */}
119
+ <span className="cg-record-rail-row-label" title={tab.label}>{tab.label}</span>
120
  {/* Clause 2 — the FIELD, and only when two edges share one target (R2). A second
121
  line under a row with no sibling would answer a question nobody asked. */}
122
+ {tab.subtitle && (
123
+ <span className="cg-record-rail-row-sub" title={tab.subtitle}>{tab.subtitle}</span>
124
+ )}
125
+ {/* ⭐⭐ W53-T24 · RULING R12 — **HOW FAR AWAY THIS DATABASE IS**, marked on the row.
126
+ R12 caps traversal at DEPTH 2, so the only two answers are one hop and two, and
127
+ a two-hop row is the one that needs saying: its rows are a customer's PRODUCTS
128
+ by way of their orders, which is a different claim from a customer's orders and
129
+ a reader who cannot tell them apart is reading a number wrong.
130
+ ⛔ QUIET, AND NO NEW ANYTHING. It reuses `.cg-record-rail-row-sub` — already the
131
+ rail's muted third-size line — so there is no new class, no new colour literal
132
+ and no new font size, which matters because this ticket owns no stylesheet.
133
+ Sentence case, no emoji, no badge.
134
+ ⛔ AND IT TRAVELS ON THE TAB, NOT AS A RAIL PROP. `verify_wiring.py` and
135
+ `verify_record_layout.py` both assert this component's mount as the exact string
136
+ `<RecordRail tabs={tabs} activeTab={activeTab} onSelect={setTab} />`; a fourth
137
+ prop would redden two gates to carry a number that belongs to one row. */}
138
+ {tab.hops === 2 && <span className="cg-record-rail-row-sub">2 hops</span>}
139
  </button>
140
  ))}
141
  </div>
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -822,7 +822,24 @@ function DataDatabaseNavigator({
822
  const draggable = !!onMove && !database.protected && database.managedBy !== "loopable";
823
  const content = (
824
  <>
825
- <DatabaseMark size={16} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826
  <span className="cg-fold-name">{database.label}</span>
827
  {database.locked ? (
828
  <span
 
822
  const draggable = !!onMove && !database.protected && database.managedBy !== "loopable";
823
  const content = (
824
  <>
825
+ {/* ⭐⭐ W53-T35 / C4 (owner instruction 26) — THE WRAPPER IS THE FIX, and the mark is
826
+ deliberately unchanged. Owner: *"The icon for a database should be standardized,
827
+ including the one in the View rail. It shouldn't be filled with purple. The icon on
828
+ the home page is the correct one."* The purple was never in this SVG:
829
+ `styles/wave45/data-applications.css` fills every `.cg-folder-mark path` with
830
+ `--lp-purple-deep`, `DatabaseMark` renders under that class, and a class rule beats
831
+ the mark's own `fill="none"`. That folder rule is CORRECT for a folder and is
832
+ asserted verbatim by `verify_folders.py`, so it cannot be edited; what is wrong is a
833
+ DATABASE wearing a FOLDER class. `shell/shell.css` scopes the override to
834
+ `.cg-db-mark .cg-folder-mark path` — two classes, so it wins on specificity rather
835
+ than on import order — and paints the cylinder in `--lp-muted`, which is the exact
836
+ `LP_MUTED` the Home tile's copy of this mark already strokes.
837
+ ⛔ DO NOT "SIMPLIFY" THIS BY SWAPPING THE MARK: `verify_ui.py::database_mark_faults`
838
+ requires this file to import `DatabaseMark` from `./iconShapes`, to declare no local
839
+ copy of it, and to render it. One drawing, one definition (W50-T09, ruling R16). */}
840
+ <span className="cg-db-mark">
841
+ <DatabaseMark size={16} />
842
+ </span>
843
  <span className="cg-fold-name">{database.label}</span>
844
  {database.locked ? (
845
  <span
web/src/customer-grid/apiBridge.ts CHANGED
@@ -55,9 +55,9 @@ import {
55
  import { setStandaloneSink } from "./hostBridge";
56
  import { changedBuckets } from "./liveWorkspace";
57
  import type { ChangeTokens } from "./liveWorkspace";
58
- import { CUSTOMER_TOPIC, relatedEntries } from "./types";
59
  import type { CustomersPayload, Field, FilterNode, GridLimit, GridWorkspace, HostEvent,
60
- RelatedEntry, RelatedPin, Row, SortSpec, TopicConfig } from "./types";
61
  import type { TsPayload, TsRequest } from "./timeSeriesData";
62
 
63
  const JSON_HEADERS = { "Content-Type": "application/json" };
@@ -652,26 +652,70 @@ export async function fetchAggregates(
652
  // ═══════════════════════════════════════════════════════════════════════════════════════════
653
 
654
  /**
655
- * `GET /api/v1/grid/{table}/related` — every edge THIS ACCOUNT may follow, forward then reverse
656
- * then bridge.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
657
  *
658
- * ⛔ AN EMPTY LIST ON ANY FAILURE, NEVER A THROW. A record whose relations cannot be listed
659
  * still opens on its Fields tab; a rejected promise here would take the whole drawer down for a
660
  * list that is chrome.
661
  * ⚠ The permission narrowing happens SERVER-SIDE (`routes_grid.related_entries` filters on
662
  * `_may_open`), so an edge that is not in this answer is also an edge that cannot be pinned.
663
  * There is deliberately no second, laxer resolution on this side.
 
 
 
 
 
 
664
  */
665
- export async function fetchRelated(table: string): Promise<RelatedEntry[]> {
666
  try {
667
  const res = await fetch(
668
- `${API_V1}/grid/${encodeURIComponent(table)}/related`,
669
  { credentials: CREDENTIALS }
670
  );
671
- if (handledSession(res) || !res.ok) return [];
672
- return relatedEntries(await readJson(res));
 
673
  } catch {
674
- return [];
675
  }
676
  }
677
 
@@ -692,22 +736,45 @@ export async function fetchRelated(table: string): Promise<RelatedEntry[]> {
692
  * such edge today (`ut_odoo_invoices` is materialised and absent from `GRID_SOURCES`), and a
693
  * link whose target is an ordinary user table is the same shape for a different reason: that
694
  * door (`routes_tables.table_rows`) takes no predicate at all.
 
 
 
 
 
 
 
 
 
695
  */
696
  export async function probeRelatedRead(
697
  tableKey: string,
698
  related: RelatedPin
699
- ): Promise<string | null> {
700
  const path = windowRowsPath(tableKey, { offset: 0, limit: 1, related });
701
  let res: Response;
702
  try {
703
  res = await fetch(`${API_V1}/${path}`, { credentials: CREDENTIALS });
704
  } catch {
705
- return "The server could not be reached, so these related records cannot be shown yet. "
706
- + "Check the connection and open this tab again.";
 
 
 
 
 
707
  }
708
  if (handledSession(res)) return null;
709
  if (res.ok) return null;
710
- return refusalMessage(await readJson(res), res.status);
 
 
 
 
 
 
 
 
 
711
  }
712
 
713
  /**
 
55
  import { setStandaloneSink } from "./hostBridge";
56
  import { changedBuckets } from "./liveWorkspace";
57
  import type { ChangeTokens } from "./liveWorkspace";
58
+ import { CUSTOMER_TOPIC, relatedEntries, relatedRefusals } from "./types";
59
  import type { CustomersPayload, Field, FilterNode, GridLimit, GridWorkspace, HostEvent,
60
+ RelatedEntry, RelatedPin, RelatedRefusal, Row, SortSpec, TopicConfig } from "./types";
61
  import type { TsPayload, TsRequest } from "./timeSeriesData";
62
 
63
  const JSON_HEADERS = { "Content-Type": "application/json" };
 
652
  // ═══════════════════════════════════════════════════════════════════════════════════════════
653
 
654
  /**
655
+ * ⭐⭐ W53-T24 · R13 · C3 — THE LISTING IS TWO LISTS NOW, AND THAT IS THE WHOLE POINT.
656
+ *
657
+ * `related` is what a reader may follow; `refusals` is what was walled off on the way. R13 says
658
+ * "no related rows", "you may not see this table" and "this hop was filtered" are three
659
+ * different answers, and an answer that arrived only as a SHORTER `related` array would be
660
+ * indistinguishable from the database simply having fewer edges. So both travel, together, and
661
+ * the caller renders the second rather than dropping it.
662
+ * ⛔ THE REFUSALS NEVER WIDEN THE ENTRIES. They are parsed by a different function off a
663
+ * different key, so there is no path by which one becomes the other.
664
+ */
665
+ export interface RelatedListing {
666
+ entries: RelatedEntry[];
667
+ refusals: RelatedRefusal[];
668
+ }
669
+
670
+ /** A stable identity, so a failed listing is not a fresh object on every render. */
671
+ const EMPTY_LISTING: RelatedListing = { entries: [], refusals: [] };
672
+
673
+ /**
674
+ * ⭐ W53-T24 · R13 — WHAT A REFUSED PIN ANSWERS WITH: the server's CODE and the server's
675
+ * SENTENCE. `null` still means the pin is served, unchanged.
676
+ */
677
+ export interface RelatedRead {
678
+ code: string;
679
+ reason: string;
680
+ /**
681
+ * ⚠ THE X2 ENVELOPE'S OWN `table` AND `hop`, CARRIED BECAUSE R13 ASKS THE REFUSAL TO NAME ITS
682
+ * SUBJECT and the client must not mine the sentence for it. `table` rides on `forbidden_table`
683
+ * and MAY name the INTERMEDIATE table of a two-hop path, which is the exact case R13 exists
684
+ * for: read on both ends, walled out of the middle. `hop` rides on `hop_filtered` and names
685
+ * the edge key the wall took.
686
+ */
687
+ table?: string;
688
+ hop?: string;
689
+ }
690
+
691
+ /**
692
+ * `GET /api/v1/grid/{table}/related?depth=2` — every edge THIS ACCOUNT may follow, forward then
693
+ * reverse then bridge, and (at depth 2) the SECOND JUMPS beyond them.
694
  *
695
+ * ⛔ AN EMPTY LISTING ON ANY FAILURE, NEVER A THROW. A record whose relations cannot be listed
696
  * still opens on its Fields tab; a rejected promise here would take the whole drawer down for a
697
  * list that is chrome.
698
  * ⚠ The permission narrowing happens SERVER-SIDE (`routes_grid.related_entries` filters on
699
  * `_may_open`), so an edge that is not in this answer is also an edge that cannot be pinned.
700
  * There is deliberately no second, laxer resolution on this side.
701
+ *
702
+ * ⭐ R12 CAPS THE TRAVERSAL AT TWO, so `depth` is typed `1 | 2` rather than `number`: depth 3 is
703
+ * a refusal the server has to author (it names the missing hop), and this client cannot even
704
+ * spell the request that would earn it. MEASURED 2026-09-05 on this branch: `?depth=2` is
705
+ * ACCEPTED AND IGNORED — 200, the same six entries, no `hops` and no `path` on any of them —
706
+ * so sending it today changes nothing and is what makes the consumer ready the day D lands.
707
  */
708
+ export async function fetchRelated(table: string, depth: 1 | 2 = 2): Promise<RelatedListing> {
709
  try {
710
  const res = await fetch(
711
+ `${API_V1}/grid/${encodeURIComponent(table)}/related?depth=${depth}`,
712
  { credentials: CREDENTIALS }
713
  );
714
+ if (handledSession(res) || !res.ok) return EMPTY_LISTING;
715
+ const body = await readJson(res);
716
+ return { entries: relatedEntries(body), refusals: relatedRefusals(body) };
717
  } catch {
718
+ return EMPTY_LISTING;
719
  }
720
  }
721
 
 
736
  * such edge today (`ut_odoo_invoices` is materialised and absent from `GRID_SOURCES`), and a
737
  * link whose target is an ordinary user table is the same shape for a different reason: that
738
  * door (`routes_tables.table_rows`) takes no predicate at all.
739
+ *
740
+ * ⭐⭐ W53-T24 · R13 — IT NOW RETURNS THE **CODE** BESIDE THE SENTENCE, AND THAT IS NOT A SECOND
741
+ * OPINION ABOUT THE WORDS. R13 asks for three refusals to be TOLD APART; a bare string can be
742
+ * printed but it cannot be branched on without the client re-reading the server's prose, which
743
+ * is the same "second author of one contract" mistake wearing a regular expression. The code
744
+ * picks the TREATMENT (which voice, which `role`, which emphasis); the sentence stays the
745
+ * server's, verbatim, in every one of the three.
746
+ * ⚠ Read from `body.error.code` — the X2 envelope, the same one `refusalMessage` documents 400
747
+ * lines above. `""` when the body carries no code, which is honest rather than a guess.
748
  */
749
  export async function probeRelatedRead(
750
  tableKey: string,
751
  related: RelatedPin
752
+ ): Promise<RelatedRead | null> {
753
  const path = windowRowsPath(tableKey, { offset: 0, limit: 1, related });
754
  let res: Response;
755
  try {
756
  res = await fetch(`${API_V1}/${path}`, { credentials: CREDENTIALS });
757
  } catch {
758
+ return {
759
+ // ⚠ NO CODE. The server never answered, so there is no code to report and no state to
760
+ // treat specially; the caller falls through to printing this sentence plainly.
761
+ code: "",
762
+ reason: "The server could not be reached, so these related records cannot be shown yet. "
763
+ + "Check the connection and open this tab again.",
764
+ };
765
  }
766
  if (handledSession(res)) return null;
767
  if (res.ok) return null;
768
+ const body = await readJson(res);
769
+ const err = (body as { error?: { code?: unknown; table?: unknown; hop?: unknown } } | null)
770
+ ?.error;
771
+ const out: RelatedRead = {
772
+ code: typeof err?.code === "string" ? err.code : "",
773
+ reason: refusalMessage(body, res.status),
774
+ };
775
+ if (typeof err?.table === "string" && err.table) out.table = err.table;
776
+ if (typeof err?.hop === "string" && err.hop) out.hop = err.hop;
777
+ return out;
778
  }
779
 
780
  /**
web/src/customer-grid/types.ts CHANGED
@@ -4135,15 +4135,50 @@ export const PIVOT_PATH = "grid/pivot";
4135
  /** The three ways one database is related to another. Mirrors `relations.DIRECTIONS`. */
4136
  export type RelatedDirection = "forward" | "reverse" | "bridge";
4137
 
4138
- /** `relations._entry`'s `via` bag, echoed back to the pinned read UNCHANGED. */
4139
- export interface RelatedVia {
4140
- direction: RelatedDirection;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4141
  key: string;
4142
  field?: string;
4143
  on?: string;
4144
  from?: string;
4145
  }
4146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4147
  /**
4148
  * ONE entry of `GET /api/v1/grid/{table}/related`.
4149
  *
@@ -4157,10 +4192,71 @@ export interface RelatedEntry {
4157
  label: string;
4158
  target: string;
4159
  served: boolean;
4160
- via: RelatedVia;
4161
  where?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4162
  }
4163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4164
  /**
4165
  * C6's pinned-read payload — `{table, record, via}` — identical on both Odoo doors.
4166
  *
@@ -4177,10 +4273,17 @@ export interface RelatedPin {
4177
  /** One TAB of the record view: the edge, plus the two lines of chrome clause 2 asks for. */
4178
  export interface RelatedTab {
4179
  entry: RelatedEntry;
4180
- /** The TARGET DATABASE's own name, never the edge's label. */
4181
  label: string;
4182
- /** The FIELD, and ONLY when two edges share one target. Empty string otherwise. */
4183
  subtitle: string;
 
 
 
 
 
 
 
4184
  }
4185
 
4186
  /**
@@ -4194,14 +4297,37 @@ export function relatedEntries(body: unknown): RelatedEntry[] {
4194
  for (const raw of b.related as Record<string, unknown>[]) {
4195
  const via = raw?.via as Record<string, unknown> | undefined;
4196
  const direction = String(via?.direction ?? "");
4197
- if (direction !== "forward" && direction !== "reverse" && direction !== "bridge") continue;
 
 
 
 
 
 
 
 
4198
  const target = String(raw?.target ?? "");
4199
  const key = String(raw?.key ?? "");
4200
  if (!target || !key) continue;
4201
- const bag: RelatedVia = { direction, key: String(via?.key ?? key) };
4202
  if (via?.field) bag.field = String(via.field);
4203
  if (via?.on) bag.on = String(via.on);
4204
  if (via?.from) bag.from = String(via.from);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4205
  const entry: RelatedEntry = {
4206
  key,
4207
  label: String(raw?.label ?? target),
@@ -4210,42 +4336,104 @@ export function relatedEntries(body: unknown): RelatedEntry[] {
4210
  // not turn every tab into a refusal; the pinned read is the thing that answers for real.
4211
  served: raw?.served !== false,
4212
  via: bag,
 
 
4213
  };
4214
  if (raw?.where) entry.where = String(raw.where);
 
 
 
 
 
4215
  out.push(entry);
4216
  }
4217
  return out;
4218
  }
4219
 
4220
  /**
4221
- * ⭐ CLAUSE 2 — a tab is labelled by the TARGET DATABASE, and SUBTITLED BY THE FIELD only when
4222
- * two edges share that target.
4223
- *
4224
- * ⛔ THE ENTRY'S OWN `label` IS NOT THE DATABASE'S NAME, and this is measured rather than
4225
- * assumed: `relations.forward_links` labels an entry with the FIELD's label, `reverse_links`
4226
- * with the source definition's label, `bridge_entries` with the bridge's. So the display name
4227
- * comes from `labelFor` (the link-target roster, which is the one producer of a database's name
4228
- * in this product) and the entry's own label falls back only when the roster cannot answer.
4229
- *
4230
- * ⛔ THE SUBTITLE IS CONDITIONAL, NOT DECORATIVE. R2 gives two tabs to two links between the
4231
- * same pair; printing the field under a target that has only ONE edge would be a second line
4232
- * that answers a question nobody asked (DESIGN section 4, never over-explain).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4233
  */
4234
  export function relatedTabs(
4235
  entries: readonly RelatedEntry[],
4236
  labelFor: (target: string) => string,
4237
  ): RelatedTab[] {
4238
- const perTarget = new Map<string, number>();
4239
- for (const entry of entries)
4240
- perTarget.set(entry.target, (perTarget.get(entry.target) ?? 0) + 1);
4241
- return entries.map((entry) => ({
4242
- entry,
4243
- label: labelFor(entry.target) || entry.label || entry.target,
4244
- subtitle:
4245
- (perTarget.get(entry.target) ?? 0) > 1
4246
- ? entry.via.field || entry.label || entry.key
4247
- : "",
4248
- }));
 
 
 
 
 
 
 
 
4249
  }
4250
 
4251
  /** C10's request, verbatim. */
 
4135
  /** The three ways one database is related to another. Mirrors `relations.DIRECTIONS`. */
4136
  export type RelatedDirection = "forward" | "reverse" | "bridge";
4137
 
4138
+ /**
4139
+ * ⭐⭐ W53-T24 · RULING R12 · CONTRACT C3 — **THE FOURTH LITERAL, AND WHY IT IS NOT ONE OF THE
4140
+ * THREE.** A TWO-HOP entry comes back wearing `direction: "path"`, deliberately OUTSIDE the
4141
+ * `forward | reverse | bridge` union, so that any resolver still pattern-matching on those three
4142
+ * fails CLOSED rather than picking a hop at random.
4143
+ *
4144
+ * ⛔⛔ AND THAT IS EXACTLY HOW THIS FEATURE WOULD HAVE SHIPPED ABSENT. `relatedEntries` below
4145
+ * used to read `if (direction !== "forward" && ... ) continue;`, so every two-hop entry the
4146
+ * server sent was DROPPED here in silence: nothing thrown, nothing logged, no tab, and a wave
4147
+ * closing green over a feature that does not exist. Widening this union is the line that makes
4148
+ * the second jump real; narrowing it again deletes the feature without reddening anything.
4149
+ */
4150
+ export type RelatedPathDirection = RelatedDirection | "path";
4151
+
4152
+ /**
4153
+ * `relations._entry`'s `via` bag, echoed back to the pinned read UNCHANGED.
4154
+ *
4155
+ * ⚠ This is the ONE-HOP shape and it keeps its own name because a `RelatedEntry` always carries
4156
+ * a bag, never an array: the array is how a two-hop pin is ASKED FOR, not how an edge is
4157
+ * DESCRIBED. See `RelatedVia` immediately below for the pin's wider vocabulary.
4158
+ */
4159
+ export interface RelatedViaBag {
4160
+ direction: RelatedPathDirection;
4161
  key: string;
4162
  field?: string;
4163
  on?: string;
4164
  from?: string;
4165
  }
4166
 
4167
+ /**
4168
+ * ⭐⭐ W53-T24 · R12 · C3 — WHAT A **PIN** MAY CARRY: the bag for one hop, an ARRAY OF EDGE KEYS
4169
+ * for two (`via = ["orders", "order_lines"]`).
4170
+ *
4171
+ * ⛔ R12 IS "NAME EVERY HOP", NEVER "SEARCH FOR A PATH". The array is the client pinning a
4172
+ * traversal it has been HANDED by the listing (`RelatedEntry.path`), never one it assembled: a
4173
+ * client that stitched two edge keys together itself would be doing the path search R12 forbids,
4174
+ * and depth 3 is refused by the server rather than by a length check written here.
4175
+ *
4176
+ * ⚠ MEASURED, 2026-09-05, against the server on this branch: a pinned read with `via` as an
4177
+ * ARRAY answers 400 `bad_relation` until lane D's route lands, so the ARRAY IS SENT ONLY WHEN
4178
+ * `hops === 2` and today's one-hop reads keep sending the bag byte for byte as before.
4179
+ */
4180
+ export type RelatedVia = RelatedViaBag | string[];
4181
+
4182
  /**
4183
  * ONE entry of `GET /api/v1/grid/{table}/related`.
4184
  *
 
4192
  label: string;
4193
  target: string;
4194
  served: boolean;
4195
+ via: RelatedViaBag;
4196
  where?: string;
4197
+ /**
4198
+ * ⭐⭐ C3 — THE EDGE KEYS OF THIS TRAVERSAL, IN ORDER, AND THE THING A TWO-HOP PIN IS SENT
4199
+ * WITH. One key for a one-hop entry, two for a second jump. It is the SERVER's array; this
4200
+ * client never re-derives it, exactly as `PivotResponse.path` above is never re-derived.
4201
+ *
4202
+ * ⛔⛔ REQUIRED, NOT OPTIONAL, AND THAT IS DELIBERATE ON A MEMBER THE SERVER MAY OMIT. An
4203
+ * optional member degrades to "the feature does not exist", which is indistinguishable from
4204
+ * never built and is precisely how this seam went unmounted in four consecutive waves; a
4205
+ * required one puts `tsc` on the wire's side. It is honest because the PARSER is the
4206
+ * boundary: `relatedEntries` fills `[key]` when the body carries no `path` (measured
4207
+ * 2026-09-05 — `?depth=2` still answers with the same six entries and no `path` on any of
4208
+ * them), and `[key]` is the literal truth of a one-hop edge rather than a placeholder.
4209
+ */
4210
+ path: string[];
4211
+ /** 1 or 2, and REQUIRED for the same reason `path` is. `relatedEntries` settles it once. */
4212
+ hops: 1 | 2;
4213
+ /**
4214
+ * `connector_spec.CARDINALITIES`: `many_to_one` | `one_to_many` | `one_to_one` |
4215
+ * `many_to_many`. ⛔ TYPED AS A PLAIN STRING ON PURPOSE. Two of the four are legal and
4216
+ * nothing declares them yet, so an unrecognised value is an UNKNOWN cardinality that renders
4217
+ * as nothing, never a throw that takes the rail down with it.
4218
+ */
4219
+ cardinality?: string;
4220
+ }
4221
+
4222
+ /**
4223
+ * ⭐⭐ W53-T24 · RULING R13 · C3 — **ONE REFUSAL FROM THE LISTING, AND THE REASON THERE ARE
4224
+ * THREE CODES RATHER THAN ONE EMPTY LIST.**
4225
+ *
4226
+ * R13, verbatim in effect: "no related rows", "you may not see this table" and "this hop was
4227
+ * filtered" are THREE DIFFERENT ANSWERS. They are three different codes on the wire so they can
4228
+ * be three different states on screen; collapsing them loses the only thing that tells a reader
4229
+ * whether to go looking for the records or to go ask for access.
4230
+ *
4231
+ * ⚠ `table` MAY NAME THE INTERMEDIATE of a two-hop path, and that is the case R13 exists for:
4232
+ * a reader may hold read on both ends and be walled out of the middle. `hop` names the edge key
4233
+ * the wall took, and rides only on `hop_filtered`. `refusals` is `[]` when nothing was filtered.
4234
+ */
4235
+ export interface RelatedRefusal {
4236
+ code: string;
4237
+ message: string;
4238
+ path: string[];
4239
+ table?: string;
4240
+ hop?: string;
4241
  }
4242
 
4243
+ /**
4244
+ * ⭐⭐ W53-T24 · RULING R13 · C3 — **THE THREE CODES, SPELLED EXACTLY ONCE IN THIS CLIENT.**
4245
+ *
4246
+ * ⛔ A CONSTANT RATHER THAN THREE STRING LITERALS SCATTERED THROUGH A RENDER, because R13's
4247
+ * whole content is that these three are DIFFERENT ANSWERS: a typo in one literal at one call
4248
+ * site silently collapses that answer back into the default treatment, which is the empty-grid
4249
+ * failure wearing a new disguise, and no gate on either side of the wire would see it. Imported
4250
+ * where the states are chosen, so `tsc` binds the declaration to its consumer.
4251
+ * ⚠ `no_related_rows` IS A LISTING ANSWER ONLY. C3: a path that resolves is a path that exists,
4252
+ * so a PIN never answers it, and nothing here renders a pin-time `no_related_rows`.
4253
+ */
4254
+ export const RELATED_REFUSAL = {
4255
+ noRelatedRows: "no_related_rows",
4256
+ forbiddenTable: "forbidden_table",
4257
+ hopFiltered: "hop_filtered",
4258
+ } as const;
4259
+
4260
  /**
4261
  * C6's pinned-read payload — `{table, record, via}` — identical on both Odoo doors.
4262
  *
 
4273
  /** One TAB of the record view: the edge, plus the two lines of chrome clause 2 asks for. */
4274
  export interface RelatedTab {
4275
  entry: RelatedEntry;
4276
+ /** The EDGE's own name, which is what one tab has and its neighbour does not. */
4277
  label: string;
4278
+ /** The TARGET DATABASE's name, and only when it does not merely repeat the label. */
4279
  subtitle: string;
4280
+ /**
4281
+ * ⭐ W53-T24 — HOW MANY JUMPS THIS TAB IS AWAY, CARRIED ON THE TAB RATHER THAN AS A NEW RAIL
4282
+ * PROP. `verify_wiring.py` and `verify_record_layout.py` both assert the rail's mount as the
4283
+ * exact string `<RecordRail tabs={tabs} activeTab={activeTab} onSelect={setTab} />`, so a
4284
+ * fourth prop would redden two gates for a mark that belongs to one row anyway.
4285
+ */
4286
+ hops: 1 | 2;
4287
  }
4288
 
4289
  /**
 
4297
  for (const raw of b.related as Record<string, unknown>[]) {
4298
  const via = raw?.via as Record<string, unknown> | undefined;
4299
  const direction = String(via?.direction ?? "");
4300
+ /* ⭐⭐ W53-T24 · C3 — `"path"` IS THE FOURTH ACCEPTED LITERAL, and admitting it here is the
4301
+ whole of what makes a second jump reachable. See `RelatedPathDirection`: every two-hop
4302
+ entry the server sends wears it, and the three-literal guard that stood here dropped all
4303
+ of them without a sound. Anything OUTSIDE the four is still skipped, which is the
4304
+ fail-closed half of the same rule. */
4305
+ if (
4306
+ direction !== "forward" && direction !== "reverse"
4307
+ && direction !== "bridge" && direction !== "path"
4308
+ ) continue;
4309
  const target = String(raw?.target ?? "");
4310
  const key = String(raw?.key ?? "");
4311
  if (!target || !key) continue;
4312
+ const bag: RelatedViaBag = { direction, key: String(via?.key ?? key) };
4313
  if (via?.field) bag.field = String(via.field);
4314
  if (via?.on) bag.on = String(via.on);
4315
  if (via?.from) bag.from = String(via.from);
4316
+ /* ⚠ MEASURED FALLBACKS, NOT DEFENSIVE HABIT. The server on this branch answers `?depth=2`
4317
+ with the same six one-hop entries and NO `path` and NO `hops` on any of them, so these
4318
+ two lines are what keeps the rail identical until lane D's route lands: a missing `path`
4319
+ is `[key]`, which is the literal truth of a one-hop edge, and a missing `hops` is 1. */
4320
+ const rawPath = Array.isArray(raw?.path)
4321
+ ? (raw.path as unknown[]).map((step) => String(step)).filter((step) => step !== "")
4322
+ : [];
4323
+ const path = rawPath.length ? rawPath : [key];
4324
+ const askedHops = Number(raw?.hops);
4325
+ /* ⛔ `direction === "path"` COUNTS AS TWO EVEN IF `hops` IS MISSING. The direction and the
4326
+ hop count are two spellings of one fact, and trusting only the number would send a bag to
4327
+ a door that was handed a path. */
4328
+ const hops: 1 | 2 = askedHops === 1 || askedHops === 2
4329
+ ? (askedHops as 1 | 2)
4330
+ : (path.length > 1 || direction === "path" ? 2 : 1);
4331
  const entry: RelatedEntry = {
4332
  key,
4333
  label: String(raw?.label ?? target),
 
4336
  // not turn every tab into a refusal; the pinned read is the thing that answers for real.
4337
  served: raw?.served !== false,
4338
  via: bag,
4339
+ path,
4340
+ hops,
4341
  };
4342
  if (raw?.where) entry.where = String(raw.where);
4343
+ // ⚠ Carried as the server spelled it. Two of the four legal values are declared by nothing
4344
+ // yet, so an unknown one is simply unknown here rather than a value this file rejects.
4345
+ if (typeof raw?.cardinality === "string" && raw.cardinality) {
4346
+ entry.cardinality = raw.cardinality;
4347
+ }
4348
  out.push(entry);
4349
  }
4350
  return out;
4351
  }
4352
 
4353
  /**
4354
+ * ⭐⭐ W53-T24 · R13 · C3 — THE LISTING'S `refusals`, READ THE SAME DEFENSIVE WAY THE ENTRIES
4355
+ * ARE, and for the same reason: a rail that cannot be listed still has to open its Fields tab.
4356
+ *
4357
+ * ⛔ A REFUSAL NEVER WIDENS THE ENTRY LIST, and this function cannot make it: it reads a
4358
+ * different key and returns a different list. Lane D holds a gate leg proving `related` is
4359
+ * identical with and without `refusals`; nothing here may quietly turn a refusal into a tab.
4360
+ * ⚠ `[]` IS THE NORMAL ANSWER. `refusals` fires when something was actually filtered, so an
4361
+ * empty list is "nothing was walled off", never "the server forgot to tell us".
4362
+ */
4363
+ export function relatedRefusals(body: unknown): RelatedRefusal[] {
4364
+ const b = body as { refusals?: unknown } | null;
4365
+ if (!b || !Array.isArray(b.refusals)) return [];
4366
+ const out: RelatedRefusal[] = [];
4367
+ for (const raw of b.refusals as Record<string, unknown>[]) {
4368
+ const code = String(raw?.code ?? "");
4369
+ if (!code) continue;
4370
+ const refusal: RelatedRefusal = {
4371
+ code,
4372
+ message: String(raw?.message ?? ""),
4373
+ // ⚠ ALWAYS PRESENT ON THE WIRE, `[]` for `no_related_rows` on an empty side. Read
4374
+ // defensively anyway: an absent array here must not become `undefined.length` on screen.
4375
+ path: Array.isArray(raw?.path)
4376
+ ? (raw.path as unknown[]).map((step) => String(step)).filter((step) => step !== "")
4377
+ : [],
4378
+ };
4379
+ if (typeof raw?.table === "string" && raw.table) refusal.table = raw.table;
4380
+ if (typeof raw?.hop === "string" && raw.hop) refusal.hop = raw.hop;
4381
+ out.push(refusal);
4382
+ }
4383
+ return out;
4384
+ }
4385
+
4386
+ /**
4387
+ * ⭐ CLAUSE 2, CORRECTED BY W53-T23 — A TAB IS NAMED AFTER **ITS EDGE**, AND SUBTITLED WITH
4388
+ * THE TARGET DATABASE.
4389
+ *
4390
+ * ⛔ THE PRECEDENCE IS THIS WAY ROUND BECAUSE THE REAL CASE IS **MANY EDGES TO ONE TARGET**,
4391
+ * and that is measured rather than assumed: on tenant royal-imports `customer_data` carries
4392
+ * THREE edges to `ut_odoo_invoices` — the forward `invoices` field, the reverse `customer_link`,
4393
+ * and the `open_invoices` bridge, whose `where` predicate asks a genuinely different question and
4394
+ * is why `relations.edge_identity` keeps it through dedupe. Naming each tab after its target
4395
+ * printed "Odoo open invoices" three times in one rail and left a reader unable to tell the three
4396
+ * apart; that rail is the owner's ERROR 21. The entry's OWN label already differs per edge
4397
+ * (`relations.forward_links` labels with the FIELD's label, `reverse_links` with the source
4398
+ * table's, `bridge_entries` with the bridge's), so it leads, and the database's name from
4399
+ * `labelFor` sits underneath so a reader still learns where the tab lands.
4400
+ *
4401
+ * ⛔ THE SUBTITLE IS SUPPRESSED WHEN IT WOULD ONLY REPEAT THE LABEL. A reverse entry is labelled
4402
+ * with its SOURCE table's name, which for this pair is word for word its target's name too;
4403
+ * printing both would say one thing twice (DESIGN section 4, never over-explain).
4404
+ *
4405
+ * ⛔ AND DISTINCTNESS IS STRUCTURAL, NOT A PROPERTY OF TODAY'S DATA. Two edges CAN carry the
4406
+ * same label: R2 gives two tabs to two links between one pair, and every reverse entry is named
4407
+ * after its source table, so two reverse edges out of one table would collide. When two or more
4408
+ * would render the same words, each is qualified by its OWN column, using the house pattern that
4409
+ * already exists for exactly this collision in `api/amazon_relational.py:241`
4410
+ * (`f"{LABELS[target]} by {_label(col)}"`), lower-cased in the qualifier because DESIGN asks for
4411
+ * sentence case. On today's six edges it does not fire at all, and that is right: it is a
4412
+ * guarantee against a rail with two identical rows, not decoration.
4413
  */
4414
  export function relatedTabs(
4415
  entries: readonly RelatedEntry[],
4416
  labelFor: (target: string) => string,
4417
  ): RelatedTab[] {
4418
+ const named = entries.map((entry) => entry.label || labelFor(entry.target) || entry.target);
4419
+ const perLabel = new Map<string, number>();
4420
+ for (const name of named) perLabel.set(name, (perLabel.get(name) ?? 0) + 1);
4421
+ return entries.map((entry, index) => {
4422
+ const name = named[index];
4423
+ const column = entry.via.field || entry.via.on || entry.key;
4424
+ const target = labelFor(entry.target);
4425
+ return {
4426
+ entry,
4427
+ label:
4428
+ (perLabel.get(name) ?? 0) > 1
4429
+ ? `${name} by ${column.replace(/_/g, " ").trim().toLowerCase()}`
4430
+ : name,
4431
+ subtitle: target && target !== name ? target : "",
4432
+ // ⭐ W53-T24 — the entry's own hop count, travelling to the rail on the tab. Never
4433
+ // re-derived from the label or the path length here; `relatedEntries` settled it once.
4434
+ hops: entry.hops,
4435
+ };
4436
+ });
4437
  }
4438
 
4439
  /** C10's request, verbatim. */
web/src/filter-kit/SheetFilterPopup.tsx ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit/SheetFilterPopup.tsx — W53-T15, ruling R8.
3
+ //
4
+ // ⭐⭐ R8, VERBATIM: "The filter builder becomes a centred popup in the SHEET ONLY. The Data
5
+ // module keeps its inline filter unchanged." `FilterBuilderPanel` in this same directory is the
6
+ // SHARED component the Data module's toolbar also mounts, and it is left byte-for-byte unchanged:
7
+ // this file only WRAPS it in a centred dialog, and the Sheet's `BindingEditor` is the only caller.
8
+ //
9
+ // ⛔ WHY A POPUP AT ALL, AS A MEASUREMENT RATHER THAN A PREFERENCE. The builder's own width is
10
+ // derived in `index.css` beside `.cg-pop--wide`: 620px, because `.cg-cond-op` is a fixed 176px at
11
+ // every nesting level and the level-3 value box needs what is left. The Sheet mounted the same
12
+ // component inside `.sheet-binding-panel`, which is `flex: 0 0 380px` with 14px of padding on
13
+ // `.sheet-binding-scroll` — about 352px of usable width. A condition row's intrinsic minimum at
14
+ // the ROOT level alone is 52 (prefix) + 6 + 112 (`.cg-cond-field` min) + 6 + 176 (`.cg-cond-op`)
15
+ // + 6 + 48 (`.cg-cond-val` min) + the remove mark, i.e. more than 400px before any nesting. The
16
+ // row could not fit, and `.sheet-binding-scroll` carries `overflow-y: auto`, which per CSS
17
+ // overflow rules makes its `overflow-x` compute to `auto` as well: a horizontal scrollbar.
18
+ // THE FIX IS THE CONTAINER, NOT THE ROW — `.cg-cond-row` is already `min-width: 0`.
19
+ //
20
+ // ⭐ THE SURFACE IS THE BASE KIT'S DIALOG, NOT A NEW ONE. `.lp-dialog-scrim` / `.lp-dialog` in
21
+ // `styles/wave51/kit.css` already are a centred, token-only, portal-safe modal (every selector in
22
+ // that file is top-level precisely because it renders through `BodyPortal`), and `kit.css` is
23
+ // imported from `index.css` rather than from a lazy chunk, so this paints wherever it is opened.
24
+ // Re-declaring that surface inline would have been a second dialog to keep in step with the first.
25
+ // ⚠ ONE inline override, and it is the whole ticket: `.lp-dialog` is `min(420px, …)`, which is
26
+ // NARROWER than the 380px column this popup exists to escape. The width below is the only
27
+ // geometry this file states, because `styles/wave53/**` belongs to another lane this wave.
28
+ //
29
+ // ⛔⛔ NO DRAFT STATE, ON PURPOSE. `onChange` is the SAME `setTree` the inline mount was handed,
30
+ // so every edit is committed to the binding the instant it is made. Escape, an outside click and
31
+ // Done are therefore the same event with three names, and there is nothing left to save.
32
+ //
33
+ // ⛔⛔ THE PROVIDER AROUND THE DIALOG IS LOAD-BEARING, AND IT IS NOT DECORATION.
34
+ // `FilterBuilderPanel` opens its own value picker as a SECOND body-level overlay
35
+ // (`AnchoredOverlay`, class `cg-fsel-pop`), which is not a DOM descendant of this dialog. The
36
+ // shared dismissal contract in `useOverlayLayer` defers to a higher layer only when it can SEE
37
+ // one: `if (!dismissOnOutside || (stack && !stack.isTop(id))) return;` — and `stack` is
38
+ // `useContext(OverlayStackContext)`, which is `null` unless an `OverlayProvider` is above it.
39
+ // The Data module gets one from `shell/dbFrame.tsx`; the SHEET ROUTE HAS NONE (`App.tsx` mounts
40
+ // `OverlayProvider` only on the hosted-grid branch, and `SheetPage` is not under it). Without the
41
+ // provider below, ticking a value in that picker is an "outside" pointerdown for this dialog and
42
+ // closes the whole filter. React context crosses `createPortal`, so wrapping the dialog is enough
43
+ // to put both layers on one stack, exactly as the Data module already does.
44
+ // ---------------------------------------------------------------------------
45
+
46
+ import { useId, useRef } from "react";
47
+ import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
48
+ import type { Field, FilterTree } from "../customer-grid/types";
49
+ import { filterTreeNodes } from "../customer-grid/types";
50
+ // Through the barrel, which is how every other consumer of this kit imports the panel.
51
+ import { FilterBuilderPanel, countConditions } from "./index";
52
+
53
+ export interface SheetFilterPopupProps {
54
+ /** The cell this filter belongs to, e.g. `B4`. Named in the title so the dialog says which
55
+ * cell it is about, the way the binding panel behind it does. */
56
+ addr: string;
57
+ /** Escape, an outside pointerdown, the close mark, or Done. There is no second, cancelling
58
+ * door: see the note about draft state at the top of this file. */
59
+ onClose: () => void;
60
+ fields: Field[];
61
+ filters: FilterTree;
62
+ onChange: (next: FilterTree) => void;
63
+ statusValues?: Record<string, string[]>;
64
+ }
65
+
66
+ /** Sentence-case count for the dialog's caption. Zero reads as a sentence rather than a bare
67
+ * "0 conditions", which looks like a value that failed to load. */
68
+ export function conditionCountLabel(filters: FilterTree): string {
69
+ const n = countConditions(filterTreeNodes(filters));
70
+ if (n === 0) return "No conditions yet";
71
+ return n === 1 ? "1 condition" : `${n} conditions`;
72
+ }
73
+
74
+ /** The dialog itself. Split from the export ONLY so that `useOverlayLayer` runs BELOW the
75
+ * provider and therefore joins the same stack the value picker will join. */
76
+ function SheetFilterDialog({
77
+ addr, onClose, fields, filters, onChange, statusValues,
78
+ }: SheetFilterPopupProps) {
79
+ const panelRef = useRef<HTMLDivElement>(null);
80
+ const titleId = useId();
81
+
82
+ // ⛔⛔ NO `open` PROP, AND THE CALLER MOUNTS THIS CONDITIONALLY. `useOverlayLayer` has no
83
+ // active flag: it claims Escape the moment it runs, and `ui/useEscapeClose` hands the key to
84
+ // the LAST entry pushed (`escapeTargets` returns `entries[entries.length - 1]` and nothing
85
+ // else). An `open` prop checked after the hook would still push that entry, so the claim would
86
+ // exist while the dialog did not. MOUNTING LATE IS WHAT PUTS THIS ABOVE THE BINDING EDITOR:
87
+ // the editor's own `useEscapeClose` entry was pushed when the editor mounted, this one is
88
+ // pushed when the popup opens, and popping it on close hands Escape straight back to the
89
+ // editor. ⚠ The `container` option on those entries does NOT arbitrate between them — it only
90
+ // decides whether the focused element counts as inside the topmost overlay (`insideTop`, used
91
+ // for cancel-edit and for the blur before close). Push ORDER is the whole ranking.
92
+ useOverlayLayer({
93
+ panelRef,
94
+ onDismiss: onClose,
95
+ dismissOnOutside: true,
96
+ initialFocus: "first",
97
+ restoreFocus: true,
98
+ trapFocus: true,
99
+ });
100
+
101
+ return (
102
+ <BodyPortal>
103
+ <div className="lp-dialog-scrim">
104
+ <div
105
+ ref={panelRef}
106
+ // `sheet-filter-popup` carries NO rule anywhere and is not meant to: it is the name a
107
+ // gate, a screenshot or a person in the inspector can point at. The paint is all
108
+ // `.lp-dialog`.
109
+ className="lp-dialog sheet-filter-popup"
110
+ style={{ width: "min(760px, calc(100vw - 32px))" }}
111
+ role="dialog"
112
+ aria-modal="true"
113
+ aria-labelledby={titleId}
114
+ data-overlay-kind="sheet-filter"
115
+ >
116
+ <div className="lp-dialog-head">
117
+ <h2 className="lp-dialog-title" id={titleId}>{`The filter for ${addr}`}</h2>
118
+ <button
119
+ type="button"
120
+ className="lp-dialog-x"
121
+ aria-label={`Close the filter for ${addr}`}
122
+ onClick={onClose}
123
+ >
124
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
125
+ <path
126
+ d="M4 4l8 8M12 4l-8 8"
127
+ stroke="currentColor"
128
+ strokeWidth="1.5"
129
+ strokeLinecap="round"
130
+ />
131
+ </svg>
132
+ </button>
133
+ </div>
134
+ {/* Says the thing the missing Save button would otherwise have to be asked about. */}
135
+ <p className="lp-dialog-body">
136
+ {`${conditionCountLabel(filters)}. Every change is kept as you make it, so close this `
137
+ + "when you are done."}
138
+ </p>
139
+ {/* `min-width: 0` so the builder's rows may shrink inside this flex column instead of
140
+ pushing the dialog wider than the viewport on a small screen. */}
141
+ <div className="sheet-filter-popup-body" style={{ minWidth: 0 }}>
142
+ <FilterBuilderPanel
143
+ fields={fields}
144
+ filters={filters}
145
+ onChange={onChange}
146
+ statusValues={statusValues}
147
+ />
148
+ </div>
149
+ <div className="lp-dialog-actions">
150
+ {/* ⛔ NOT "Save", AND DELIBERATELY QUIET. Nothing is held back, so a Save button would
151
+ imply a discard door that cannot exist without a draft copy of the tree, and the
152
+ filled `lp-dialog-btn-primary` (`--lp-primary`, a violet) would give a control that
153
+ merely closes the weight of a commit, in a palette the Sheet does not otherwise
154
+ wear. `lp-dialog-btn-quiet` is a hairline on the dialog's own surface. */}
155
+ <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" onClick={onClose}>
156
+ Done
157
+ </button>
158
+ </div>
159
+ </div>
160
+ </div>
161
+ </BodyPortal>
162
+ );
163
+ }
164
+
165
+ export function SheetFilterPopup(props: SheetFilterPopupProps) {
166
+ return (
167
+ <OverlayProvider>
168
+ <SheetFilterDialog {...props} />
169
+ </OverlayProvider>
170
+ );
171
+ }
web/src/sheet/BindingEditor.tsx CHANGED
@@ -42,8 +42,12 @@ import type { SurfaceScope } from "../customer-grid/apiBridge";
42
  import { FieldTypeIcon } from "../customer-grid/icons";
43
  import type { Field, FilterTree, Row } from "../customer-grid/types";
44
  import { choiceVocabulary, topicForScope } from "../customer-grid/types";
45
- import { FilterBuilderPanel } from "../filter-kit";
46
- import { isNumericType } from "../filter-kit/ops";
 
 
 
 
47
  import { useEscapeClose } from "../ui/useEscapeClose";
48
  import { previewCell } from "./sheetApi";
49
 
@@ -55,6 +59,44 @@ const AGGREGATES = [
55
  { fn: "max", label: "Maximum" },
56
  ] as const;
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  /** A Sheet names a DATABASE KEY; the workspace door speaks `SurfaceScope`. Same pair as DrillModal. */
59
  const scopeOf = (database: string): SurfaceScope | null => {
60
  if (database === "customer_data") return "customer";
@@ -133,13 +175,10 @@ export function shiftPeriodStart(unit: PeriodUnit, ym: string, steps: number): s
133
  return joinYm(Math.floor(total / 12), (total % 12) + 1);
134
  }
135
 
136
- /** The period a person reads: "July 2026", "Q3 2026", "2026". */
137
- export function periodLabel(unit: PeriodUnit, ym: string): string {
138
- const { y, m } = splitYm(normalizePeriodStart(unit, ym));
139
- if (unit === "year") return String(y);
140
- if (unit === "quarter") return `Q${Math.floor((m - 1) / 3) + 1} ${y}`;
141
- return `${MONTH_NAMES[m - 1]} ${y}`;
142
- }
143
 
144
  const todayYm = () => {
145
  const now = new Date();
@@ -157,6 +196,13 @@ const todayYm = () => {
157
  * ⛔ SO A `ref`-ONLY PERIOD BECOMES LOCKED. `unit` and `start` are non-optional in C2 and have to
158
  * carry something, but on a ref-driven period they are INERT: the referenced cell decides the
159
  * period, and `locked: true` is what stops the drag rule from touching it either way.
 
 
 
 
 
 
 
160
  */
161
  export function migratePeriod(raw: unknown): PeriodBinding | null {
162
  if (!raw || typeof raw !== "object") return null;
@@ -169,9 +215,10 @@ export function migratePeriod(raw: unknown): PeriodBinding | null {
169
  return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref };
170
  }
171
  const unit = p.unit as PeriodUnit;
172
- const start = normalizePeriodStart(
173
- unit, typeof p.start === "string" ? p.start : todayYm(),
174
- );
 
175
  const locked = p.locked === true;
176
  return ref ? { unit, start, locked, ref } : { unit, start, locked };
177
  }
@@ -222,6 +269,70 @@ function adoptedFromOf(initial: Record<string, unknown> | null | undefined): str
222
  return typeof name === "string" ? name : "";
223
  }
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  export interface BindingEditorProps {
226
  workbookId: string;
227
  addr: string;
@@ -238,13 +349,31 @@ export default function BindingEditor({
238
  const [database, setDatabase] = useState<string>(
239
  String((initial?.database as string) ?? databases[0]?.key ?? ""),
240
  );
241
- const [fn, setFn] = useState<string>("sum");
242
- const [field, setField] = useState<string>("");
243
- const [scopeKind, setScopeKind] = useState<"view" | "filter">("view");
244
- const [viewId, setViewId] = useState<string>("");
245
- const [tree, setTree] = useState<FilterTree>({ conj: "and", nodes: [] });
 
 
 
 
 
 
 
 
 
 
246
  const [fields, setFields] = useState<Field[]>([]);
247
  const [views, setViews] = useState<{ id: string; name: string }[]>([]);
 
 
 
 
 
 
 
 
248
  // ⭐⭐ W52-T14 (instruction 11) — THE FILTER'S VALUE VOCABULARY NEEDS ROWS, NOT ONLY FIELDS.
249
  // A declared select/status carries its own list on `field.options`, which the filter kit
250
  // already falls back to with no `statusValues` at all. A SERVER-COMPUTED one (a `select` whose
@@ -278,10 +407,17 @@ export default function BindingEditor({
278
  // with no saved period (`migrated === null`, an all-time sum) seeds `unit`/`start`/`locked` with
279
  // DEFAULTS purely so the controls have something to display; those defaults are not a decision
280
  // anybody made. Saving them unconditionally is exactly the bug: Save stamps `{unit:"month",
281
- // start:<this month>}` over an all-time binding the person never touched. `periodTouched` starts
282
- // TRUE only when a period was already on the binding (re-saving it unchanged must keep saving it),
283
- // and every explicit interaction with a period control below flips it true from then on.
284
- const [periodTouched, setPeriodTouched] = useState<boolean>(Boolean(migrated));
 
 
 
 
 
 
 
285
  const [across, setAcross] = useState<DragAcross>(savedDrag.across);
286
  const [downField, setDownField] = useState<string>(savedDrag.down);
287
 
@@ -298,9 +434,21 @@ export default function BindingEditor({
298
 
299
  // The field and view lists come from the SAME door the grid uses, so a cell can never offer a
300
  // column the grid does not have.
 
 
 
 
 
 
 
 
 
 
 
301
  useEffect(() => {
302
  let live = true;
303
  const scope = scopeOf(database);
 
304
  if (!scope) {
305
  setFields([]);
306
  setViews([]);
@@ -318,15 +466,45 @@ export default function BindingEditor({
318
  if (!live) return;
319
  if (ws) {
320
  setFields((ws.fields ?? []) as Field[]);
321
- setViews(((ws.views ?? []) as { id: string; name: string }[])
322
- .map((v) => ({ id: v.id, name: v.name })));
323
  }
324
  setRawRows(rowsPayload?.rows ?? []);
325
  setUserOptions(rowsPayload?.userOptions ?? ws?.userOptions ?? []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  })();
327
  return () => { live = false; };
328
  }, [database]);
329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  /** The same rule `Toolbar.tsx` computes for the grid (owner item 24): the declared list when a
331
  * field has one, the values seen in the rows when it does not. `choiceVocabulary` is pure and
332
  * already gated, so this is not a second definition of the rule, only a second caller of it. */
@@ -348,11 +526,31 @@ export default function BindingEditor({
348
  // are exactly the ones the filter engine treats as numbers. A local list would drift, and it was
349
  // wrong on its first attempt: the numeric family is `int` / `currency` / `pct`, and there is no
350
  // `"number"` in `FieldType` at all - tsc caught that before it could ship as an empty picker.
 
 
 
 
351
  const numericFields = useMemo(
352
- () => fields.filter((f) => isNumericType(f.type)),
353
  [fields],
354
  );
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  /** R10's list, and a DIFFERENT predicate from the one above. See `isDragDownField`. */
357
  const dragDownFields = useMemo(
358
  () => fields.filter(isDragDownField),
@@ -400,10 +598,11 @@ export default function BindingEditor({
400
  // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
401
  // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
402
  // replacing them, because the pair still names what the cell falls back to.
403
- // ⛔⛔ D-660 - ONLY WRITE `period` WHEN `periodTouched` SAYS SOMEBODY CHOSE ONE. See the state
404
- // declaration above: an all-time binding re-saved without touching the period control must stay
405
- // all-time, not get silently stamped to this month's default.
406
- if (periodTouched) {
 
407
  const period: Record<string, unknown> = { unit, start, locked };
408
  if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
409
  out.period = period;
@@ -411,7 +610,7 @@ export default function BindingEditor({
411
  out.onDrag = { across, down: downField ? { field: downField } : "none" };
412
  return out;
413
  }, [database, fn, field, scopeKind, viewId, views, tree, initial,
414
- unit, start, locked, refOpen, periodRef, periodTouched, across, downField]);
415
 
416
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
417
  // which is what lets someone see whether they picked the right thing while they can still change
@@ -437,16 +636,11 @@ export default function BindingEditor({
437
  if (!years.includes(startYear)) years.push(startYear);
438
  years.sort((a, b) => a - b);
439
 
440
- const setYear = (y: number) => {
441
- setStart(normalizePeriodStart(unit, joinYm(y, startMonth)));
442
- setPeriodTouched(true);
443
- };
444
- const setMonthOfYear = (m: number) => {
445
- setStart(normalizePeriodStart(unit, joinYm(startYear, m)));
446
- setPeriodTouched(true);
447
- };
448
-
449
- const downLabel = dragDownFields.find((f) => f.key === downField)?.label ?? "";
450
 
451
  return (
452
  <section
@@ -521,19 +715,58 @@ export default function BindingEditor({
521
  >
522
  {/* ⭐ THE ICON COMES BEFORE THE NAME, which is owner instruction 24 and also
523
  what the Fields panel and the grid header already do. One glyph vocabulary,
524
- one source: `iconShapes.ts::TYPE_SHAPES`. */}
525
- <FieldTypeIcon type={f.type} title={f.type} />
 
 
 
 
 
 
 
 
 
526
  <span className="cg-type-label">{f.label}</span>
 
 
 
 
 
 
 
 
527
  </button>
528
  ))}
529
  </div>
530
  {/* ⛔ AN EMPTY LIST SAYS WHY (R16), because a blank box reads as a broken picker and
531
- the two causes need different acts from the reader. */}
 
 
532
  {shownFields.length === 0 && (
533
  <p className="sheet-pick-empty">
534
- {numericFields.length === 0
535
- ? "This database has no number column to total."
536
- : "No column matches that search."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  </p>
538
  )}
539
  </div>
@@ -553,18 +786,58 @@ export default function BindingEditor({
553
  {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
554
  </select>
555
  )}
 
 
 
 
 
 
 
 
 
556
  <label className="sheet-radio">
557
  <input type="radio" checked={scopeKind === "filter"}
558
  onChange={() => setScopeKind("filter")} />
559
  <span>A filter I build here</span>
560
  </label>
 
 
 
 
 
561
  {scopeKind === "filter" && (
562
- <FilterBuilderPanel
563
- fields={fields}
564
- filters={tree}
565
- onChange={setTree}
566
- statusValues={statusValues}
567
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
  )}
569
  </fieldset>
570
 
@@ -572,140 +845,151 @@ export default function BindingEditor({
572
  <fieldset className="sheet-scope sheet-period">
573
  <legend>Period</legend>
574
 
575
- <label className="sheet-field">
576
- <span>Unit</span>
577
- <select
578
- value={unit}
579
- aria-label="Period unit"
580
- onChange={(e) => {
581
- const next = e.target.value as PeriodUnit;
582
- setUnit(next);
583
- // Re-seat the start on the new unit's first month, or the pair stops naming one
584
- // period: `2026-08` under `quarter` is not a quarter anybody can compile.
585
- setStart(normalizePeriodStart(next, start));
586
- setPeriodTouched(true);
587
- }}
588
- >
589
- {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
590
- </select>
591
- </label>
592
-
593
- <div className="sheet-field-row">
594
- <label className="sheet-field">
595
- <span>Year</span>
596
- <select
597
- value={String(startYear)}
598
- aria-label="Period year"
599
- onChange={(e) => setYear(Number(e.target.value))}
600
- >
601
- {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
602
- </select>
603
- </label>
604
- {unit === "month" && (
605
- <label className="sheet-field">
606
- <span>Month</span>
607
- <select
608
- value={String(startMonth)}
609
- aria-label="Period month"
610
- onChange={(e) => setMonthOfYear(Number(e.target.value))}
611
- >
612
- {MONTH_NAMES.map((name, i) => (
613
- <option key={name} value={String(i + 1)}>{name}</option>
614
- ))}
615
- </select>
616
- </label>
617
- )}
618
- {unit === "quarter" && (
619
- <label className="sheet-field">
620
- <span>Quarter</span>
621
- <select
622
- value={String(Math.floor((startMonth - 1) / 3) + 1)}
623
- aria-label="Period quarter"
624
- onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
625
- >
626
- {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
627
- </select>
628
- </label>
629
- )}
630
- </div>
631
-
632
- {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This
633
- never stamps today's month under a quarter or a year. */}
634
- <div className="sheet-period-quick">
635
- <button
636
- type="button"
637
- className="sheet-period-pick"
638
- onClick={() => {
639
- setStart(normalizePeriodStart(unit, todayYm()));
640
- setPeriodTouched(true);
641
- }}
642
- >
643
- This {UNIT_NOUN[unit]}
644
- </button>
645
- <button
646
- type="button"
647
- className="sheet-period-pick"
648
- onClick={() => {
649
- setStart(shiftPeriodStart(unit, todayYm(), -1));
650
- setPeriodTouched(true);
651
- }}
652
- >
653
- Last {UNIT_NOUN[unit]}
654
- </button>
655
- </div>
656
-
657
- {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
658
- sentence under it says what each one costs when the cell is copied. */}
659
  <div className="sheet-period-lock">
660
  <button
661
  type="button"
662
  role="switch"
663
- aria-checked={locked}
664
- className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
665
- onClick={() => {
666
- setLocked((v) => !v);
667
- setPeriodTouched(true);
668
- }}
669
  >
670
  <span className="sheet-lock-dot" aria-hidden />
671
- <span>Lock this period</span>
672
  </button>
673
  <p className="sheet-period-note">
674
- {locked
675
- ? "Locked, so any copy of this cell keeps this period."
676
- : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} `
677
- + "per column, and copying up or down keeps it."}
678
  </p>
679
  </div>
680
 
681
- {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
682
- picker, so the ordinary reader never meets a cell reference and the person who wants
683
- one is one click away from it. */}
684
- {!refOpen && (
685
- <button
686
- type="button"
687
- className="sheet-period-link"
688
- onClick={() => {
689
- setRefOpen(true);
690
- setPeriodTouched(true);
691
- }}
692
- >
693
- Use a cell
694
- </button>
695
- )}
696
- {refOpen && (
697
- <label className="sheet-field">
698
- <span>Period from a cell</span>
699
- <input
700
- type="text"
701
- value={periodRef}
702
- onChange={(e) => {
703
- setPeriodRef(e.target.value);
704
- setPeriodTouched(true);
705
- }}
706
- placeholder="$B$1"
707
- />
708
- </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  )}
710
  </fieldset>
711
 
@@ -747,36 +1031,17 @@ export default function BindingEditor({
747
  )}
748
  </fieldset>
749
 
750
- {/* ══ WHAT THIS CELL POINTS AT, IN SENTENCES ══════════════════════════════════════════
751
- The panel's whole reason for being a panel: the period, the lock, the two drag rules
752
- and, when the view behind it was purged, where its filter came from. */}
753
- <div className="sheet-binding-summary">
754
- <p className="sheet-binding-line">
755
- {refOpen && periodRef.trim()
756
- ? `Period: taken from cell ${periodRef.trim()}.`
757
- : `Period: ${periodLabel(unit, start)}.`}
758
- </p>
759
- <p className="sheet-binding-line">
760
- {locked
761
- ? "The period is locked, so a copy keeps it."
762
- : `The period is not locked, so it shifts by one ${UNIT_NOUN[unit]} per column.`}
763
- </p>
764
- <p className="sheet-binding-line">
765
- {across === "period"
766
- ? `Dragged across: the period moves forward one ${UNIT_NOUN[unit]} per column.`
767
- : "Dragged across: nothing changes."}
768
- </p>
769
- <p className="sheet-binding-line">
770
- {downField
771
- ? `Dragged down: the next value of ${downLabel}.`
772
- : "Dragged down: nothing changes."}
773
  </p>
774
- {adoptedFrom && (
775
- <p className="sheet-binding-line sheet-binding-adopted">
776
- {`Filter adopted from the deleted view ${adoptedFrom}`}
777
- </p>
778
- )}
779
- </div>
780
 
781
  {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
782
  {notice && <p className="sheet-notice" role="alert">{notice}</p>}
 
42
  import { FieldTypeIcon } from "../customer-grid/icons";
43
  import type { Field, FilterTree, Row } from "../customer-grid/types";
44
  import { choiceVocabulary, topicForScope } from "../customer-grid/types";
45
+ // ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
46
+ // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
47
+ // base kit's centred dialog so its condition rows have room, and only the Sheet mounts that
48
+ // wrapper. This file therefore stops importing the panel itself.
49
+ import { countConditions, isNumericType } from "../filter-kit/ops";
50
+ import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
51
  import { useEscapeClose } from "../ui/useEscapeClose";
52
  import { previewCell } from "./sheetApi";
53
 
 
59
  { fn: "max", label: "Maximum" },
60
  ] as const;
61
 
62
+ // ══ W53-T13: WHICH COLUMNS THE SERVER CAN ACTUALLY TOTAL (R7, standing rule 9) ═══════════════
63
+ //
64
+ // ⭐⭐ THE PICKER MUST NOT OFFER A COLUMN THAT WILL REFUSE. `isNumericType` answers "does this
65
+ // column behave like a number", which is the right question for the filter builder and the wrong
66
+ // one here: a `formula` column is numeric to the filter kit and has NO SERVER VALUE AT ALL (it is
67
+ // worked out in the browser for each row by `formulaEngine.ts`), so totalling it would ask the
68
+ // database to add up a column it does not hold. `modules/sheet.py::aggregate_refusal` refuses it
69
+ // by name at bind time; this predicate is what stops the person being sent there in the first
70
+ // place, and the two have to agree or the picker offers a dead end.
71
+ //
72
+ // ⚠ IT IS A SECOND OPINION ABOUT THE SAME RULE, WHICH IS ACCEPTED HERE FOR ONE REASON: the server
73
+ // is still the one that decides, and it refuses by name if this list is ever wrong. The client's
74
+ // job is to keep a person out of a refusal, never to be the only thing checking.
75
+
76
+ /** The rollup folds that produce a number. Mirrors `core/user_tables.py::ROLLUP_FNS`, minus the
77
+ * folds that produce text or a boolean (`latest`, `and`/`or`/`xor`, `concatenate`, `arrayjoin`,
78
+ * `arraycompact`, `arrayunique`). */
79
+ const NUMERIC_ROLLUP_FNS = [
80
+ "sum", "average", "stdev", "min", "max", "count", "counta", "countall",
81
+ ];
82
+
83
+ /** A METRIC column: a business number measured over a window, rather than a value stored on the
84
+ * record. The test is the `measure` bag, exactly as `aios_grid.measure_fields_of` tests it, never
85
+ * the field's `type` (the two live ones on `customer_data` are typed `currency` and `int`). */
86
+ const isMetricField = (f: Field): boolean => Boolean(f.measure);
87
+
88
+ /** Can this database add this column up? Mirrors `modules/sheet.py::aggregate_refusal`. */
89
+ const canTotal = (f: Field): boolean => {
90
+ if (f.type === "formula") return false;
91
+ if (f.type === "rollup") {
92
+ const bag = f.rollup;
93
+ if (!bag) return false;
94
+ if (bag.source) return true;
95
+ return NUMERIC_ROLLUP_FNS.includes(String(bag.fn ?? ""));
96
+ }
97
+ return true;
98
+ };
99
+
100
  /** A Sheet names a DATABASE KEY; the workspace door speaks `SurfaceScope`. Same pair as DrillModal. */
101
  const scopeOf = (database: string): SurfaceScope | null => {
102
  if (database === "customer_data") return "customer";
 
175
  return joinYm(Math.floor(total / 12), (total % 12) + 1);
176
  }
177
 
178
+ // ⚠ W53-T16 (instruction 13) - `periodLabel` LIVED HERE and is gone with the summary block that
179
+ // was its only caller. The period a person reads is now the Year / Month / Quarter pickers
180
+ // themselves, which is where they set it, so a second rendering of the same value had nothing left
181
+ // to tell them.
 
 
 
182
 
183
  const todayYm = () => {
184
  const now = new Date();
 
196
  * ⛔ SO A `ref`-ONLY PERIOD BECOMES LOCKED. `unit` and `start` are non-optional in C2 and have to
197
  * carry something, but on a ref-driven period they are INERT: the referenced cell decides the
198
  * period, and `locked: true` is what stops the drag rule from touching it either way.
199
+ *
200
+ * ⛔⛔ W53-T16 / D-660 - A STORED PERIOD THAT NAMES NO WINDOW READS BACK AS NO PERIOD, and this is
201
+ * the READ half of the fix whose write half is `platform/modules/sheet.py::clean_period`. A period
202
+ * carrying a unit but no usable `start` and no `ref` used to have TODAY'S MONTH filled in for it
203
+ * here, so an all-time cell opened as "September 2026" and the next save narrowed it to one month
204
+ * with nobody told. Filling a missing start is only legitimate when a `ref` decides the period
205
+ * anyway, which is the inert case the paragraph above describes.
206
  */
207
  export function migratePeriod(raw: unknown): PeriodBinding | null {
208
  if (!raw || typeof raw !== "object") return null;
 
215
  return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref };
216
  }
217
  const unit = p.unit as PeriodUnit;
218
+ const stored = typeof p.start === "string" ? p.start.trim() : "";
219
+ // D-660: no window named, and no cell to take one from, so there is no period to read.
220
+ if (!/^\d{4}-\d{2}$/.test(stored) && !ref) return null;
221
+ const start = normalizePeriodStart(unit, stored || todayYm());
222
  const locked = p.locked === true;
223
  return ref ? { unit, start, locked, ref } : { unit, start, locked };
224
  }
 
269
  return typeof name === "string" ? name : "";
270
  }
271
 
272
+ /**
273
+ * ⭐⭐ W53-T12 — THE PANEL READS BACK WHAT WAS SAVED, WHICH IT DID NOT DO BEFORE.
274
+ *
275
+ * `database`, `period` and `onDrag` were hydrated from `initial`; `fn`, `field`, the scope kind,
276
+ * the view id and the filter tree were NOT, so opening an already bound cell showed Sum, no
277
+ * column and "Choose a view" no matter what the cell actually pointed at, and pressing Save wrote
278
+ * those defaults over the real binding. Nothing could tell a person their saved view had gone
279
+ * missing while the editor never showed which view they had saved.
280
+ *
281
+ * ⚠ AN AGGREGATE MAY CARRY `metric_key` INSTEAD OF `fn` (the server's normalizer accepts it and no
282
+ * control here speaks it yet), so an unrecognised aggregate falls back to the panel's own defaults
283
+ * rather than seeding a `<select>` with a value it has no option for.
284
+ */
285
+ export function readAggregate(raw: unknown): { fn: string; field: string } {
286
+ const a = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
287
+ const named = typeof a.fn === "string" ? a.fn : "";
288
+ const known = AGGREGATES.some((x) => x.fn === named);
289
+ return {
290
+ fn: known ? named : "sum",
291
+ field: known && typeof a.field === "string" ? a.field : "",
292
+ };
293
+ }
294
+
295
+ /** The saved scope: a view id, or a filter tree built in this panel. Neither means an empty view. */
296
+ export function readScope(raw: unknown): {
297
+ kind: "view" | "filter"; viewId: string; tree: FilterTree;
298
+ } {
299
+ const empty: FilterTree = { conj: "and", nodes: [] };
300
+ const s = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
301
+ const viewId = typeof s.view_id === "string" ? s.view_id.trim() : "";
302
+ if (viewId) return { kind: "view", viewId, tree: empty };
303
+ const f = s.filter;
304
+ if (f && typeof f === "object") {
305
+ const t = f as Record<string, unknown>;
306
+ return {
307
+ kind: "filter",
308
+ viewId: "",
309
+ tree: {
310
+ conj: t.conj === "or" ? "or" : "and",
311
+ nodes: Array.isArray(t.nodes) ? (t.nodes as FilterTree["nodes"]) : [],
312
+ },
313
+ };
314
+ }
315
+ return { kind: "view", viewId: "", tree: empty };
316
+ }
317
+
318
+ /** The view the binding NAMES, kept even after the id is cleared, so the notice can still say it. */
319
+ function savedViewOf(initial: Record<string, unknown> | null | undefined): {
320
+ database: string; id: string; name: string;
321
+ } {
322
+ const scope = (initial?.scope ?? {}) as Record<string, unknown>;
323
+ return {
324
+ database: typeof initial?.database === "string" ? initial.database : "",
325
+ id: typeof scope.view_id === "string" ? scope.view_id.trim() : "",
326
+ name: typeof scope.view_name === "string" ? scope.view_name : "",
327
+ };
328
+ }
329
+
330
+ /** The `{id, name}` pairs a workspace payload offers, and nothing else off it. */
331
+ function viewList(raw: unknown): { id: string; name: string }[] {
332
+ if (!Array.isArray(raw)) return [];
333
+ return (raw as { id: string; name: string }[]).map((v) => ({ id: v.id, name: v.name }));
334
+ }
335
+
336
  export interface BindingEditorProps {
337
  workbookId: string;
338
  addr: string;
 
349
  const [database, setDatabase] = useState<string>(
350
  String((initial?.database as string) ?? databases[0]?.key ?? ""),
351
  );
352
+ // ⚠ SEEDED ONCE, AT MOUNT, the same way `migratePeriod` and `readOnDrag` below already are. A
353
+ // `useEffect` that re-read `initial` would clobber a live edit the next time the parent
354
+ // re-rendered for an unrelated reason, which is the failure the period note already describes.
355
+ const savedAgg = useState(() => readAggregate(initial?.aggregate))[0];
356
+ const savedScope = useState(() => readScope(initial?.scope))[0];
357
+ const savedView = useState(() => savedViewOf(initial))[0];
358
+
359
+ const [fn, setFn] = useState<string>(savedAgg.fn);
360
+ const [field, setField] = useState<string>(savedAgg.field);
361
+ const [scopeKind, setScopeKind] = useState<"view" | "filter">(savedScope.kind);
362
+ const [viewId, setViewId] = useState<string>(savedScope.viewId);
363
+ const [tree, setTree] = useState<FilterTree>(savedScope.tree);
364
+ // W53-T15 — what the door below reports. `countConditions` walks nested groups too, so a filter
365
+ // built out of groups is not undercounted into reading as empty.
366
+ const conditionCount = useMemo(() => countConditions(tree.nodes ?? []), [tree]);
367
  const [fields, setFields] = useState<Field[]>([]);
368
  const [views, setViews] = useState<{ id: string; name: string }[]>([]);
369
+ // ⛔ THE NOTICE BELOW IS GATED ON THIS FLAG AND NOT ON `views.length`. Before the first answer
370
+ // arrives the list is legitimately empty, and a notice keyed on emptiness would flash "that view
371
+ // is gone" at every perfectly valid binding for as long as the fetch took.
372
+ const [viewsLoaded, setViewsLoaded] = useState(false);
373
+ // ⭐⭐ W53-T15 (ruling R8) — WHETHER THE CENTRED FILTER DIALOG IS ON SCREEN, and the ONLY state
374
+ // this ticket adds. The tree itself stays in `tree`/`setTree` below and the dialog writes
375
+ // straight into that setter, so there is no draft to reconcile when it closes.
376
+ const [filterPopupOpen, setFilterPopupOpen] = useState(false);
377
  // ⭐⭐ W52-T14 (instruction 11) — THE FILTER'S VALUE VOCABULARY NEEDS ROWS, NOT ONLY FIELDS.
378
  // A declared select/status carries its own list on `field.options`, which the filter kit
379
  // already falls back to with no `statusValues` at all. A SERVER-COMPUTED one (a `select` whose
 
407
  // with no saved period (`migrated === null`, an all-time sum) seeds `unit`/`start`/`locked` with
408
  // DEFAULTS purely so the controls have something to display; those defaults are not a decision
409
  // anybody made. Saving them unconditionally is exactly the bug: Save stamps `{unit:"month",
410
+ // start:<this month>}` over an all-time binding the person never touched. So this flag starts
411
+ // TRUE only when a period was already on the binding, and re-saving that binding unchanged keeps
412
+ // saving it.
413
+ //
414
+ // ⭐⭐ W53-T16 - AND IT IS NOW A CONTROL SOMEBODY CAN SEE AND TURN OFF, not a hidden flag. Before
415
+ // this ticket the flag was raised by any touch of any period control and could never be lowered:
416
+ // an all-time cell LOOKED like it was set to this month (the pickers show a default they are not
417
+ // applying) and a cell narrowed to a period could not be widened back to all time from this panel
418
+ // at all, which is standing rule 1's second sentence - a limit nobody was told about. The switch
419
+ // below states which of the two a cell is, and either answer is one click from the other.
420
+ const [periodOn, setPeriodOn] = useState<boolean>(Boolean(migrated));
421
  const [across, setAcross] = useState<DragAcross>(savedDrag.across);
422
  const [downField, setDownField] = useState<string>(savedDrag.down);
423
 
 
434
 
435
  // The field and view lists come from the SAME door the grid uses, so a cell can never offer a
436
  // column the grid does not have.
437
+ //
438
+ // ⭐⭐ W53-T12 — CACHED FIRST FOR SPEED, THEN REVALIDATED, AND THE SECOND READ IS THE POINT.
439
+ // `fetchWorkspace(scope, {allowCached: true})` is served from `wsCache` inside its freshness
440
+ // window, so a view deleted or renamed in another tab minutes ago is still offered here as a
441
+ // choice somebody can save. The uncached call that follows it (no options, which always goes to
442
+ // the server) is the one that knows what exists NOW, and the list is rebuilt from whichever
443
+ // answer arrived last.
444
+ //
445
+ // ⛔ A NULL REVALIDATE LEAVES THE CACHED LIST STANDING. `fetchWorkspace` answers null when the
446
+ // call fails, and blanking a working dropdown because the network blinked would refuse a person
447
+ // their own saved views for a reason that has nothing to do with the views.
448
  useEffect(() => {
449
  let live = true;
450
  const scope = scopeOf(database);
451
+ setViewsLoaded(false);
452
  if (!scope) {
453
  setFields([]);
454
  setViews([]);
 
466
  if (!live) return;
467
  if (ws) {
468
  setFields((ws.fields ?? []) as Field[]);
469
+ setViews(viewList(ws.views));
 
470
  }
471
  setRawRows(rowsPayload?.rows ?? []);
472
  setUserOptions(rowsPayload?.userOptions ?? ws?.userOptions ?? []);
473
+
474
+ const fresh = await fetchWorkspace(scope);
475
+ if (!live) return;
476
+ if (!fresh) {
477
+ // Offline or refused. Only claim the list is settled if the cached read produced one.
478
+ if (ws) setViewsLoaded(true);
479
+ return;
480
+ }
481
+ const list = viewList(fresh.views);
482
+ setFields((fresh.fields ?? []) as Field[]);
483
+ setViews(list);
484
+ setViewsLoaded(true);
485
+ // ⛔ A SELECTED VIEW THAT NO LONGER EXISTS IS CLEARED, so Save cannot store a dead id — that
486
+ // stored id is exactly the state this ticket was reported for. The notice in `Rows to
487
+ // include` is what explains the empty control; clearing without saying so would read as the
488
+ // panel losing the choice on its own.
489
+ setViewId((cur) => (cur && !list.some((v) => v.id === cur) ? "" : cur));
490
  })();
491
  return () => { live = false; };
492
  }, [database]);
493
 
494
+ /** The binding names a view the fresh list does not have. Said in the panel, not after a save.
495
+ *
496
+ * ⛔ IT STOPS BEING SAID THE MOMENT THE PERSON ANSWERS IT. The sentence asks for one of two acts,
497
+ * so it must clear when either is taken: choosing a live view fills `viewId`, and switching to
498
+ * "A filter I build here" moves `scopeKind`. Keying it on the SAVED id alone left the panel still
499
+ * demanding a fix after the fix had been made, which reads as a control that ignores you.
500
+ */
501
+ const savedViewMissing = viewsLoaded
502
+ && Boolean(savedView.id)
503
+ && savedView.database === database
504
+ && scopeKind === "view"
505
+ && !viewId
506
+ && !views.some((v) => v.id === savedView.id);
507
+
508
  /** The same rule `Toolbar.tsx` computes for the grid (owner item 24): the declared list when a
509
  * field has one, the values seen in the rows when it does not. `choiceVocabulary` is pure and
510
  * already gated, so this is not a second definition of the rule, only a second caller of it. */
 
526
  // are exactly the ones the filter engine treats as numbers. A local list would drift, and it was
527
  // wrong on its first attempt: the numeric family is `int` / `currency` / `pct`, and there is no
528
  // `"number"` in `FieldType` at all - tsc caught that before it could ship as an empty picker.
529
+ // ⭐ W53-T13 — `canTotal` IS THE SECOND HALF OF THE SAME QUESTION. `isNumericType` says the
530
+ // column behaves like a number; `canTotal` says this database holds a number to add up. Offering
531
+ // a column that fails the second one hands back a refusal instead of a value, which is the exact
532
+ // shape of the report this ticket answers.
533
  const numericFields = useMemo(
534
+ () => fields.filter((f) => isNumericType(f.type) && canTotal(f)),
535
  [fields],
536
  );
537
 
538
+ /** True when at least one Metric column is on offer, which is what the hint under the list is
539
+ * for: a Metric answers over the PERIOD chosen below, and no other column here does. */
540
+ const offersMetric = useMemo(() => numericFields.some(isMetricField), [numericFields]);
541
+
542
+ /** The saved binding names a column this database will not total. Said in the panel, where the
543
+ * choice is made, rather than as a refusal after a save.
544
+ *
545
+ * ⛔ IT IS GATED ON THE FIELD LIST HAVING ARRIVED, not on emptiness. Before the workspace door
546
+ * answers, every column is "missing" and a notice keyed on that would flash a sentence about a
547
+ * column that is perfectly fine, which is the failure `savedViewMissing` already records.
548
+ */
549
+ const savedFieldUnavailable = fields.length > 0
550
+ && fn !== "count"
551
+ && Boolean(field)
552
+ && !numericFields.some((f) => f.key === field);
553
+
554
  /** R10's list, and a DIFFERENT predicate from the one above. See `isDragDownField`. */
555
  const dragDownFields = useMemo(
556
  () => fields.filter(isDragDownField),
 
598
  // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
599
  // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
600
  // replacing them, because the pair still names what the cell falls back to.
601
+ // ⛔⛔ D-660 - ONLY WRITE `period` WHEN THE PERIOD SWITCH IS ON. See the state declaration
602
+ // above: an all-time binding re-saved with the switch off must stay all-time, not get silently
603
+ // stamped to this month's default, and turning the switch off drops the key rather than writing
604
+ // an empty period the server would have to guess about.
605
+ if (periodOn) {
606
  const period: Record<string, unknown> = { unit, start, locked };
607
  if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
608
  out.period = period;
 
610
  out.onDrag = { across, down: downField ? { field: downField } : "none" };
611
  return out;
612
  }, [database, fn, field, scopeKind, viewId, views, tree, initial,
613
+ unit, start, locked, refOpen, periodRef, periodOn, across, downField]);
614
 
615
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
616
  // which is what lets someone see whether they picked the right thing while they can still change
 
636
  if (!years.includes(startYear)) years.push(startYear);
637
  years.sort((a, b) => a - b);
638
 
639
+ // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every
640
+ // period control below is rendered only while `periodOn`, so reaching one of them is already the
641
+ // decision the flag used to have to infer.
642
+ const setYear = (y: number) => setStart(normalizePeriodStart(unit, joinYm(y, startMonth)));
643
+ const setMonthOfYear = (m: number) => setStart(normalizePeriodStart(unit, joinYm(startYear, m)));
 
 
 
 
 
644
 
645
  return (
646
  <section
 
715
  >
716
  {/* ⭐ THE ICON COMES BEFORE THE NAME, which is owner instruction 24 and also
717
  what the Fields panel and the grid header already do. One glyph vocabulary,
718
+ one source: `iconShapes.ts::TYPE_SHAPES`.
719
+ ⭐⭐ W53-T13 — A METRIC COLUMN WEARS THE MEASURE GLYPH, NOT ITS STORAGE
720
+ TYPE'S. The two live ones are typed `currency` and `int`, so the plain type
721
+ icon showed them as ordinary money and count columns and nothing on screen
722
+ said they are measured over a window. `measure` is a member of
723
+ `FieldTypeIcon`'s own type union and `TYPE_SHAPES` already carries its
724
+ shape, so this is the SAME glyph vocabulary rather than a new mark. */}
725
+ <FieldTypeIcon
726
+ type={isMetricField(f) ? "measure" : f.type}
727
+ title={isMetricField(f) ? "Metric" : f.type}
728
+ />
729
  <span className="cg-type-label">{f.label}</span>
730
+ {/* ⚠ THE WORD IS THERE TOO, because a glyph alone is only legible to somebody
731
+ who already knows the vocabulary, and the whole point is telling a person
732
+ what they are about to pick. `sheet-period-note` is this panel's existing
733
+ quiet muted note and is already used twice below; it carries no margin, so
734
+ it sits on the row's baseline without a rule of its own. */}
735
+ {isMetricField(f) && (
736
+ <span className="sheet-period-note">Metric</span>
737
+ )}
738
  </button>
739
  ))}
740
  </div>
741
  {/* ⛔ AN EMPTY LIST SAYS WHY (R16), because a blank box reads as a broken picker and
742
+ the causes need different acts from the reader. ⭐ W53-T13 adds the third one:
743
+ a database CAN carry number columns that this database cannot total, and "no
744
+ number column" would be a false sentence in front of somebody looking at one. */}
745
  {shownFields.length === 0 && (
746
  <p className="sheet-pick-empty">
747
+ {numericFields.length > 0
748
+ ? "No column matches that search."
749
+ : (fields.some((f) => isNumericType(f.type))
750
+ ? "The number columns on this database are worked out in the browser for "
751
+ + "each row, so there is nothing stored here to total."
752
+ : "This database has no number column to total.")}
753
+ </p>
754
+ )}
755
+ {/* ⭐ R7, said where the choice is made: a Metric is the one kind of column here
756
+ that answers over the period below, and that is why the period control matters. */}
757
+ {offersMetric && shownFields.length > 0 && (
758
+ <p className="sheet-pick-empty">
759
+ A Metric column is measured over the period you choose below. Every other column
760
+ holds one stored value per record.
761
+ </p>
762
+ )}
763
+ {/* ⭐⭐ THE BIND TIME REFUSAL, SURFACED WHERE THE PERSON CAN ACT ON IT. The server
764
+ refuses this column by name (`field_not_aggregable`), but only once a number is
765
+ asked for; saying it here means the choice is corrected before a save. */}
766
+ {savedFieldUnavailable && (
767
+ <p className="sheet-notice" role="alert">
768
+ {`The saved column ${field} cannot be totalled on this database. `
769
+ + "Pick a column from the list, or count the records instead."}
770
  </p>
771
  )}
772
  </div>
 
786
  {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
787
  </select>
788
  )}
789
+ {/* ⭐ W53-T12 — SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after
790
+ a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established
791
+ inline shape, so the sentence lands where the choice is made. */}
792
+ {savedViewMissing && (
793
+ <p className="sheet-notice" role="alert">
794
+ {`The saved view ${savedView.name || savedView.id} is not available any more. `
795
+ + "Pick a view that still exists, or build a filter here."}
796
+ </p>
797
+ )}
798
  <label className="sheet-radio">
799
  <input type="radio" checked={scopeKind === "filter"}
800
  onChange={() => setScopeKind("filter")} />
801
  <span>A filter I build here</span>
802
  </label>
803
+ {/* ⭐⭐ W53-T15 (ruling R8) — A DOOR, NOT THE BUILDER. The same shared panel now opens
804
+ in a centred dialog: this column is `flex: 0 0 380px` and a condition row cannot fit
805
+ in it, so four conditions could only be reached by scrolling sideways. The button
806
+ says how many conditions the cell already carries, because the builder that used to
807
+ say so is now behind it. */}
808
  {scopeKind === "filter" && (
809
+ <>
810
+ <button
811
+ type="button"
812
+ className="sheet-action"
813
+ style={{ alignSelf: "flex-start" }}
814
+ aria-haspopup="dialog"
815
+ aria-expanded={filterPopupOpen}
816
+ onClick={() => setFilterPopupOpen(true)}
817
+ >
818
+ {conditionCount === 0
819
+ ? "Build a filter"
820
+ : `Edit filter (${conditionCount === 1
821
+ ? "1 condition" : `${conditionCount} conditions`})`}
822
+ </button>
823
+ {/* ⛔⛔ MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather
824
+ than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it
825
+ runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a
826
+ dialog mounted with the panel would have claimed Escape from the moment this
827
+ editor opened. Mounting it here, later in time, puts it ABOVE this panel's own
828
+ claim (pushed at mount, a few hundred lines up) and unmounting it hands Escape
829
+ straight back, so one press closes the filter and the next closes the panel. */}
830
+ {filterPopupOpen && (
831
+ <SheetFilterPopup
832
+ addr={addr}
833
+ fields={fields}
834
+ filters={tree}
835
+ onChange={setTree}
836
+ statusValues={statusValues}
837
+ onClose={() => setFilterPopupOpen(false)}
838
+ />
839
+ )}
840
+ </>
841
  )}
842
  </fieldset>
843
 
 
845
  <fieldset className="sheet-scope sheet-period">
846
  <legend>Period</legend>
847
 
848
+ {/* ⭐⭐ W53-T16 / D-660 - WHETHER THIS CELL HAS A PERIOD AT ALL, said out loud. The
849
+ pickers below show a unit and a month whether or not the cell is using them, so
850
+ without this switch an all-time total read as "September 2026" on screen and the next
851
+ save made that true. It is also the only way back to all time once a period is set. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852
  <div className="sheet-period-lock">
853
  <button
854
  type="button"
855
  role="switch"
856
+ aria-checked={periodOn}
857
+ className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")}
858
+ onClick={() => setPeriodOn((v) => !v)}
 
 
 
859
  >
860
  <span className="sheet-lock-dot" aria-hidden />
861
+ <span>Limit this cell to a period</span>
862
  </button>
863
  <p className="sheet-period-note">
864
+ {periodOn
865
+ ? "Only rows dated inside the period below are counted."
866
+ : "All time, so every row this cell's filter matches is counted whatever its date. "
867
+ + "Saving leaves it that way."}
868
  </p>
869
  </div>
870
 
871
+ {periodOn && (
872
+ <>
873
+ <label className="sheet-field">
874
+ <span>Unit</span>
875
+ <select
876
+ value={unit}
877
+ aria-label="Period unit"
878
+ onChange={(e) => {
879
+ const next = e.target.value as PeriodUnit;
880
+ setUnit(next);
881
+ // Re-seat the start on the new unit's first month, or the pair stops naming one
882
+ // period: `2026-08` under `quarter` is not a quarter anybody can compile.
883
+ setStart(normalizePeriodStart(next, start));
884
+ }}
885
+ >
886
+ {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
887
+ </select>
888
+ </label>
889
+
890
+ <div className="sheet-field-row">
891
+ <label className="sheet-field">
892
+ <span>Year</span>
893
+ <select
894
+ value={String(startYear)}
895
+ aria-label="Period year"
896
+ onChange={(e) => setYear(Number(e.target.value))}
897
+ >
898
+ {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
899
+ </select>
900
+ </label>
901
+ {unit === "month" && (
902
+ <label className="sheet-field">
903
+ <span>Month</span>
904
+ <select
905
+ value={String(startMonth)}
906
+ aria-label="Period month"
907
+ onChange={(e) => setMonthOfYear(Number(e.target.value))}
908
+ >
909
+ {MONTH_NAMES.map((name, i) => (
910
+ <option key={name} value={String(i + 1)}>{name}</option>
911
+ ))}
912
+ </select>
913
+ </label>
914
+ )}
915
+ {unit === "quarter" && (
916
+ <label className="sheet-field">
917
+ <span>Quarter</span>
918
+ <select
919
+ value={String(Math.floor((startMonth - 1) / 3) + 1)}
920
+ aria-label="Period quarter"
921
+ onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
922
+ >
923
+ {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
924
+ </select>
925
+ </label>
926
+ )}
927
+ </div>
928
+
929
+ {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This
930
+ never stamps today's month under a quarter or a year. */}
931
+ <div className="sheet-period-quick">
932
+ <button
933
+ type="button"
934
+ className="sheet-period-pick"
935
+ onClick={() => setStart(normalizePeriodStart(unit, todayYm()))}
936
+ >
937
+ This {UNIT_NOUN[unit]}
938
+ </button>
939
+ <button
940
+ type="button"
941
+ className="sheet-period-pick"
942
+ onClick={() => setStart(shiftPeriodStart(unit, todayYm(), -1))}
943
+ >
944
+ Last {UNIT_NOUN[unit]}
945
+ </button>
946
+ </div>
947
+
948
+ {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
949
+ sentence under it says what each one costs when the cell is copied. */}
950
+ <div className="sheet-period-lock">
951
+ <button
952
+ type="button"
953
+ role="switch"
954
+ aria-checked={locked}
955
+ className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
956
+ onClick={() => setLocked((v) => !v)}
957
+ >
958
+ <span className="sheet-lock-dot" aria-hidden />
959
+ <span>Lock this period</span>
960
+ </button>
961
+ <p className="sheet-period-note">
962
+ {locked
963
+ ? "Locked, so any copy of this cell keeps this period."
964
+ : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} `
965
+ + "per column, and copying up or down keeps it."}
966
+ </p>
967
+ </div>
968
+
969
+ {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
970
+ picker, so the ordinary reader never meets a cell reference and the person who wants
971
+ one is one click away from it. */}
972
+ {!refOpen && (
973
+ <button
974
+ type="button"
975
+ className="sheet-period-link"
976
+ onClick={() => setRefOpen(true)}
977
+ >
978
+ Use a cell
979
+ </button>
980
+ )}
981
+ {refOpen && (
982
+ <label className="sheet-field">
983
+ <span>Period from a cell</span>
984
+ <input
985
+ type="text"
986
+ value={periodRef}
987
+ onChange={(e) => setPeriodRef(e.target.value)}
988
+ placeholder="$B$1"
989
+ />
990
+ </label>
991
+ )}
992
+ </>
993
  )}
994
  </fieldset>
995
 
 
1031
  )}
1032
  </fieldset>
1033
 
1034
+ {/* ⛔⛔ W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN.
1035
+ It restated the period, the lock and the two drag rules that the controls immediately
1036
+ above already say, in a panel 380px wide where every line it took pushed Save further
1037
+ off screen. The one line kept is R11's, because it is the only sentence here that names
1038
+ something NO control shows: the filter in this cell was copied out of a view that has
1039
+ since been deleted, and nothing else remembers that. */}
1040
+ {adoptedFrom && (
1041
+ <p className="sheet-binding-line sheet-binding-adopted">
1042
+ {`Filter adopted from the deleted view ${adoptedFrom}`}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1043
  </p>
1044
+ )}
 
 
 
 
 
1045
 
1046
  {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
1047
  {notice && <p className="sheet-notice" role="alert">{notice}</p>}
web/src/sheet/KeyTips.tsx CHANGED
@@ -78,7 +78,15 @@ function getTargets(container: HTMLElement | null, depth: Depth): Target[] {
78
  return collect(container.querySelectorAll<HTMLButtonElement>('[data-ribbon="tab-home"][data-kt]'));
79
  }
80
  if (depth === "gallery") {
81
- const openPop = container.querySelector<HTMLElement>(".sheet-ribbon-pop");
 
 
 
 
 
 
 
 
82
  return openPop ? collect(openPop.querySelectorAll<HTMLButtonElement>("[data-kt]")) : [];
83
  }
84
  return collect(container.querySelectorAll<HTMLButtonElement>('[data-kt]:not([data-ribbon="tab-home"])'));
@@ -104,7 +112,15 @@ function pickTargets(container: HTMLElement | null, depth: Depth, prefix: string
104
  * generic arrow/Enter navigation among its own menu items. */
105
  function navFallback(container: HTMLElement | null, depth: Depth): HTMLButtonElement[] {
106
  if (!container || depth !== "gallery") return [];
107
- const openPop = container.querySelector<HTMLElement>(".sheet-ribbon-pop");
 
 
 
 
 
 
 
 
108
  return openPop ? Array.from(openPop.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")) : [];
109
  }
110
 
 
78
  return collect(container.querySelectorAll<HTMLButtonElement>('[data-ribbon="tab-home"][data-kt]'));
79
  }
80
  if (depth === "gallery") {
81
+ const openPop = (container.querySelector<HTMLElement>(".sheet-ribbon-pop")
82
+ // ⭐⭐ W53-T07 (instruction 25) — THE OPEN POPOVER IS A CHILD OF `<body>` NOW. Every
83
+ // ribbon menu renders through `AnchoredOverlay`, which portals, so it is no longer a
84
+ // descendant of `Ribbon.tsx`'s `rootRef` and this container query returns null. Without
85
+ // this fallback the THIRD key-tip depth (Alt, then the group letter, then the letters
86
+ // inside the open gallery) dies silently: no error, no gate, just badges that stop
87
+ // appearing. ⚠ `document` is safe as the wider scope because exactly one popover is ever
88
+ // open - `Ribbon.tsx::open` is a single `Popover` value, not a set.
89
+ ?? document.querySelector<HTMLElement>(".sheet-ribbon-pop"));
90
  return openPop ? collect(openPop.querySelectorAll<HTMLButtonElement>("[data-kt]")) : [];
91
  }
92
  return collect(container.querySelectorAll<HTMLButtonElement>('[data-kt]:not([data-ribbon="tab-home"])'));
 
112
  * generic arrow/Enter navigation among its own menu items. */
113
  function navFallback(container: HTMLElement | null, depth: Depth): HTMLButtonElement[] {
114
  if (!container || depth !== "gallery") return [];
115
+ const openPop = (container.querySelector<HTMLElement>(".sheet-ribbon-pop")
116
+ // ⭐⭐ W53-T07 (instruction 25) — THE OPEN POPOVER IS A CHILD OF `<body>` NOW. Every
117
+ // ribbon menu renders through `AnchoredOverlay`, which portals, so it is no longer a
118
+ // descendant of `Ribbon.tsx`'s `rootRef` and this container query returns null. Without
119
+ // this fallback the THIRD key-tip depth (Alt, then the group letter, then the letters
120
+ // inside the open gallery) dies silently: no error, no gate, just badges that stop
121
+ // appearing. ⚠ `document` is safe as the wider scope because exactly one popover is ever
122
+ // open - `Ribbon.tsx::open` is a single `Popover` value, not a set.
123
+ ?? document.querySelector<HTMLElement>(".sheet-ribbon-pop"));
124
  return openPop ? Array.from(openPop.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")) : [];
125
  }
126
 
web/src/sheet/Ribbon.tsx CHANGED
@@ -39,7 +39,7 @@
39
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
40
 
41
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
42
- import type { KeyboardEvent, ReactNode } from "react";
43
  import { CELL_FORMAT_KINDS } from "./types";
44
  import type { CellFormatKind, CellStyle, CellStylePatch } from "./types";
45
  // ⭐ W52-T15 — a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s
@@ -58,6 +58,10 @@ import {
58
  // threading new props through 30+ `control()` call sites. See that file's own header for the
59
  // contract (C5) and the depth model (tabs -> Home controls -> one opened gallery).
60
  import KeyTips from "./KeyTips";
 
 
 
 
61
 
62
  /**
63
  * ⭐⭐ THE ACT VOCABULARY, CLOSED. W51-T16 builds against this union and nothing else; adding a
@@ -128,8 +132,14 @@ export interface RibbonProps {
128
  const STRIP = ["tab-home", "import", "refresh", "fullscreen", "collapse"] as const;
129
  const CLIPBOARD = ["paste", "cut", "copy", "painter"] as const;
130
  const FONT = ["bold", "italic", "underline", "border", "fill", "color", "size"] as const;
 
 
 
 
 
 
131
  const ALIGNMENT = [
132
- "top", "middle", "bottom", "left", "center", "right", "wrap", "outdent", "indent",
133
  ] as const;
134
  const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"] as const;
135
  const STYLES = ["conditional"] as const;
@@ -362,6 +372,16 @@ export default function Ribbon({
362
  }: RibbonProps) {
363
  const [focus, setFocus] = useState<ControlKey>("tab-home");
364
  const [open, setOpen] = useState<Popover>("");
 
 
 
 
 
 
 
 
 
 
365
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
366
  const rootRef = useRef<HTMLDivElement | null>(null);
367
 
@@ -428,25 +448,26 @@ export default function Ribbon({
428
  });
429
  }, []);
430
 
431
- // ⛔ A POPOVER CLOSES ON AN OUTSIDE PRESS, AND ON `mousedown` RATHER THAN `click`. A click
432
- // listener fires after the grid canvas has already taken focus and dropped its selection, so
433
- // the menu would close having applied nothing to a cell that is no longer selected.
434
- useEffect(() => {
435
- if (!open) return undefined;
436
- const away = (event: MouseEvent) => {
437
- if (!rootRef.current?.contains(event.target as Node)) setOpen("");
438
- };
439
- document.addEventListener("mousedown", away, true);
440
- return () => document.removeEventListener("mousedown", away, true);
441
- }, [open]);
 
 
 
442
 
443
  const onKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {
444
- if (event.key === "Escape" && open) {
445
- event.preventDefault();
446
- setOpen("");
447
- focusControl(focus);
448
- return;
449
- }
450
  // The toolbar's arrows belong to the toolbar only while nothing is open above it.
451
  if (open) return;
452
  const at = Math.max(0, reachable.indexOf(focus));
@@ -475,6 +496,31 @@ export default function Ribbon({
475
  onAction({ kind, arg });
476
  }, [onAction]);
477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  /**
479
  * One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part.
480
  *
@@ -490,7 +536,10 @@ export default function Ribbon({
490
  key: ControlKey,
491
  label: string,
492
  body: ReactNode,
493
- onClick: () => void,
 
 
 
494
  pressed?: boolean,
495
  expanded?: boolean,
496
  kt?: string,
@@ -558,7 +607,14 @@ export default function Ribbon({
558
  which: "color" | "fill",
559
  list: { token: string; label: string }[],
560
  ) => (
561
- <div className="sheet-ribbon-pop" role="menu" aria-label={which === "color" ? "Text colour" : "Fill colour"}>
 
 
 
 
 
 
 
562
  <div className="sheet-ribbon-swatches">
563
  {list.map((entry) => (
564
  <button
@@ -584,7 +640,7 @@ export default function Ribbon({
584
  >
585
  {which === "color" ? "Reset the text colour" : "No fill"}
586
  </button>
587
- </div>
588
  );
589
 
590
  const format = style?.format;
@@ -682,13 +738,26 @@ export default function Ribbon({
682
  {control("paste", "Paste", <>{<IconPaste />}{word("Paste")}</>,
683
  () => act("paste"), false, undefined, "V")}
684
  </span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
  <div className="sheet-ribbon-clip-stack">
686
- {control("cut", "Cut", <><IconCut />{word("Cut")}</>, () => act("cut"),
687
  false, undefined, "X")}
688
- {control("copy", "Copy", <><IconCopy />{word("Copy")}</>, () => act("copy"),
689
  false, undefined, "C")}
690
- {control("painter", "Format painter",
691
- <><IconFormatPainter />{word("Format painter")}</>,
692
  () => act("format-painter"), false, undefined, "FP")}
693
  </div>
694
  </div>
@@ -708,16 +777,23 @@ export default function Ribbon({
708
 
709
  <span className="sheet-ribbon-slot">
710
  {control("border", "Borders", <><IconBorder /><IconCaret /></>,
711
- () => setOpen(open === "border" ? "" : "border"),
712
  Object.values(style?.border ?? {}).some(Boolean), open === "border",
713
  "B", "gallery")}
714
  {open === "border" && (
715
- <div className="sheet-ribbon-pop" role="menu" aria-label="Borders">
 
 
 
 
 
 
 
716
  {BORDERS.map((entry) => item(
717
  entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt,
718
  ))}
719
  {item("No border", () => apply({ border: null }), false, "menuitem", "N")}
720
- </div>
721
  )}
722
  </span>
723
 
@@ -729,59 +805,94 @@ export default function Ribbon({
729
  <span className="sheet-ribbon-slot">
730
  {control("fill", "Fill colour",
731
  <><IconFill /><IconCaret /></>,
732
- () => setOpen(open === "fill" ? "" : "fill"), !!style?.fill, open === "fill",
733
  "H", "gallery")}
734
  {open === "fill" && swatches("fill", FILLS)}
735
  </span>
736
  <span className="sheet-ribbon-slot">
737
  {control("color", "Text colour",
738
  <><IconInk /><IconCaret /></>,
739
- () => setOpen(open === "color" ? "" : "color"), !!style?.color,
740
  open === "color", "FC", "gallery")}
741
  {open === "color" && swatches("color", INKS)}
742
  </span>
743
 
744
  <span className="sheet-ribbon-slot">
745
  {control("size", "Font size", <>{word("Size")}<IconCaret /></>,
746
- () => setOpen(open === "size" ? "" : "size"), false, open === "size",
747
  "FS", "gallery")}
748
  {open === "size" && (
749
- <div className="sheet-ribbon-pop" role="menu" aria-label="Font size">
 
 
 
 
 
 
 
750
  {SIZE_STEPS.map((step) => item(step.label, () => act("font-size", step.id)))}
751
- </div>
752
  )}
753
  </span>
754
  </>
755
  ))}
756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
757
  {group("Alignment", (
758
- <>
759
- {/* ⚠ TOP/MIDDLE/BOTTOM VERTICAL ALIGN HAS NO ROW IN THE TICKET'S OWN INLINE
760
- KeyTip LIST (it names align top/middle/bottom as one of the examples with no
761
- row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's real
762
- Excel sequences use for the horizontal three (`AL`/`AC`/`AR`), non-colliding. */}
763
- {control("top", "Align top", <IconVAlign to="top" />, () => act("align-top"),
764
- false, undefined, "AT")}
765
- {control("middle", "Align middle", <IconVAlign to="middle" />,
766
- () => act("align-middle"), false, undefined, "AM")}
767
- {control("bottom", "Align bottom", <IconVAlign to="bottom" />,
768
- () => act("align-bottom"), false, undefined, "AB")}
769
- {(["left", "center", "right"] as const).map((to) => control(
770
- to,
771
- to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
772
- <IconAlign to={to} />,
773
- () => apply({ align: style?.align === to ? null : to }),
774
- style?.align === to,
775
- undefined,
776
- to === "left" ? "AL" : to === "center" ? "AC" : "AR",
777
- ))}
778
- {control("wrap", "Wrap text", <IconWrap />, () => act("wrap-text"),
779
- false, undefined, "W")}
780
- {control("outdent", "Decrease indent", <IconIndent out />,
781
- () => act("indent-decrease"), false, undefined, "5")}
782
- {control("indent", "Increase indent", <IconIndent out={false} />,
783
- () => act("indent-increase"), false, undefined, "6")}
784
- </>
 
 
 
 
 
 
 
 
 
785
  ))}
786
 
787
  {group("Number", (
@@ -789,10 +900,17 @@ export default function Ribbon({
789
  <span className="sheet-ribbon-slot">
790
  {control("format", "Number format",
791
  <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
792
- () => setOpen(open === "format" ? "" : "format"), kind !== "general",
793
  open === "format", "N", "gallery")}
794
  {open === "format" && (
795
- <div className="sheet-ribbon-pop" role="menu" aria-label="Number format">
 
 
 
 
 
 
 
796
  {CELL_FORMAT_KINDS.map((entry) => (
797
  <button
798
  key={entry}
@@ -862,7 +980,7 @@ export default function Ribbon({
862
  Thousands separator
863
  </button>
864
  )}
865
- </div>
866
  )}
867
  </span>
868
 
@@ -891,10 +1009,20 @@ export default function Ribbon({
891
  </>
892
  ))}
893
 
 
 
 
 
 
 
 
 
 
 
894
  {group("Styles", (
895
  <>
896
  {control("conditional", "Conditional formatting",
897
- <><IconConditional />{word("Conditional formatting")}</>,
898
  () => act("conditional-formatting"), false, undefined, "L")}
899
  </>
900
  ))}
@@ -905,36 +1033,57 @@ export default function Ribbon({
905
  {group("Cells", (
906
  <>
907
  <span className="sheet-ribbon-slot">
908
- {control("insert", "Insert", <>{<IconInsert />}{word("Insert")}<IconCaret /></>,
909
- () => setOpen(open === "insert" ? "" : "insert"), false, open === "insert",
910
  "I", "gallery")}
911
  {open === "insert" && (
912
- <div className="sheet-ribbon-pop" role="menu" aria-label="Insert">
 
 
 
 
 
 
 
913
  {item("Insert row above", () => act("insert-row"))}
914
  {item("Insert column left", () => act("insert-column"))}
915
  {item("Add rows", () => act("add-rows"))}
916
  {item("Add columns", () => act("add-columns"))}
917
- </div>
918
  )}
919
  </span>
920
  <span className="sheet-ribbon-slot">
921
- {control("delete", "Delete", <>{<IconDelete />}{word("Delete")}<IconCaret /></>,
922
- () => setOpen(open === "delete" ? "" : "delete"), false, open === "delete",
923
  "D", "gallery")}
924
  {open === "delete" && (
925
- <div className="sheet-ribbon-pop" role="menu" aria-label="Delete">
 
 
 
 
 
 
 
926
  {item("Delete row", () => act("delete-row"))}
927
  {item("Delete column", () => act("delete-column"))}
928
- </div>
929
  )}
930
  </span>
931
  <span className="sheet-ribbon-slot">
932
  {control("cellformat", "Format",
933
- <>{<IconCellFormat />}{word("Format")}<IconCaret /></>,
934
- () => setOpen(open === "cellformat" ? "" : "cellformat"), false,
935
  open === "cellformat", "O", "gallery")}
936
  {open === "cellformat" && (
937
- <div className="sheet-ribbon-pop" role="menu" aria-label="Format">
 
 
 
 
 
 
 
938
  {item("Row height", () => act("row-height"))}
939
  {item("Column width", () => act("column-width"))}
940
  {item("Hide rows", () => act("hide-rows"))}
@@ -951,7 +1100,7 @@ export default function Ribbon({
951
  ticket that never touched this file. */}
952
  {item("Freeze panes", () => act("freeze"), frozen,
953
  "menuitemcheckbox")}
954
- </div>
955
  )}
956
  </span>
957
  </>
@@ -959,25 +1108,32 @@ export default function Ribbon({
959
 
960
  {group("Editing", (
961
  <>
962
- {control("autosum", "AutoSum", <><IconAutoSum />{word("AutoSum")}</>,
963
  () => act("autosum"), false, undefined, "U")}
964
  {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST.
965
  `FD`/`FR` are invented, non-colliding with `FP` (Format painter), `FS` (Font
966
  size) or `FC` (Font colour). */}
967
- {control("filldown", "Fill down", <><IconFillDown />{word("Fill down")}</>,
968
  () => act("fill-down"), false, undefined, "FD")}
969
- {control("fillright", "Fill right", <><IconFillRight />{word("Fill right")}</>,
970
  () => act("fill-right"), false, undefined, "FR")}
971
  <span className="sheet-ribbon-slot">
972
- {control("clear", "Clear", <>{<IconClear />}{word("Clear")}<IconCaret /></>,
973
- () => setOpen(open === "clear" ? "" : "clear"), false, open === "clear",
974
  "E", "gallery")}
975
  {open === "clear" && (
976
- <div className="sheet-ribbon-pop" role="menu" aria-label="Clear">
 
 
 
 
 
 
 
977
  {item("Clear contents", () => act("clear-contents"))}
978
  {item("Clear formats", () => act("clear-formats"))}
979
  {item("Clear all", () => act("clear-all"))}
980
- </div>
981
  )}
982
  </span>
983
  </>
 
39
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
40
 
41
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
42
+ import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
43
  import { CELL_FORMAT_KINDS } from "./types";
44
  import type { CellFormatKind, CellStyle, CellStylePatch } from "./types";
45
  // ⭐ W52-T15 — a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s
 
58
  // threading new props through 30+ `control()` call sites. See that file's own header for the
59
  // contract (C5) and the depth model (tabs -> Home controls -> one opened gallery).
60
  import KeyTips from "./KeyTips";
61
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
62
+ // W53-T07 (instr 25): the portalled popover's own surface. A body-level node keeps no
63
+ // ancestor rule, so its background, edge and shadow travel with it. See the file header.
64
+ import "../styles/wave53/ribbon-pop.css";
65
 
66
  /**
67
  * ⭐⭐ THE ACT VOCABULARY, CLOSED. W51-T16 builds against this union and nothing else; adding a
 
132
  const STRIP = ["tab-home", "import", "refresh", "fullscreen", "collapse"] as const;
133
  const CLIPBOARD = ["paste", "cut", "copy", "painter"] as const;
134
  const FONT = ["bold", "italic", "underline", "border", "fill", "color", "size"] as const;
135
+ // ⭐⭐ W53-T05 (instruction 16) — TWO VISUAL ROWS, ONE ROVING ORDER, AND THE ORDER IS THE READING
136
+ // ORDER. Excel lays Alignment out as two rows, so this array is re-sequenced to match what the eye
137
+ // walks: top row (vertical align, then Wrap text), then bottom row (horizontal align, then the two
138
+ // indents). ⛔ THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no
139
+ // `control(...)` call rendering it makes ArrowRight land on nothing, with every gate still green,
140
+ // so the two are changed together or not at all.
141
  const ALIGNMENT = [
142
+ "top", "middle", "bottom", "wrap", "left", "center", "right", "outdent", "indent",
143
  ] as const;
144
  const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"] as const;
145
  const STYLES = ["conditional"] as const;
 
372
  }: RibbonProps) {
373
  const [focus, setFocus] = useState<ControlKey>("tab-home");
374
  const [open, setOpen] = useState<Popover>("");
375
+ /**
376
+ * ⭐⭐ W53-T07 (instruction 25) — THE TRIGGER ELEMENT, CAPTURED ON CLICK, because a portalled
377
+ * menu has no DOM parent to position against. `AnchoredOverlay` takes this as its `anchor` and
378
+ * also puts it in its own `outsideElements`, so a pointerdown on the trigger does NOT count as
379
+ * an outside press: the plain toggle below still closes an open menu, and clicking a DIFFERENT
380
+ * trigger dismisses the first and opens the second, with no `stopPropagation` anywhere.
381
+ * ⚠ Nullable by declaration in `AnchoredOverlayProps`, so a null anchor is safe rather than a
382
+ * render-time TypeError.
383
+ */
384
+ const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
385
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
386
  const rootRef = useRef<HTMLDivElement | null>(null);
387
 
 
448
  });
449
  }, []);
450
 
451
+ // ⭐⭐ W53-T07 — THE HAND-ROLLED OUTSIDE-PRESS LISTENER IS GONE, AND ITS REASON SURVIVED THE
452
+ // DELETION. It read: *"a popover closes on an outside press, and on `mousedown` rather than
453
+ // `click`, because a click listener fires after the grid canvas has already taken focus and
454
+ // dropped its selection."* That hazard is real and it is now handled EARLIER, not dropped:
455
+ // `AnchoredOverlay` calls `useOverlayLayer`, which dismisses on capture-phase **`pointerdown`**
456
+ // (`customer-grid/OverlaySurface.tsx`), and `pointerdown` fires before `mousedown`, which fires
457
+ // before `click`. The shared door is strictly earlier than the listener it replaces.
458
+ // ⛔ DO NOT REINSTATE ONE. `DESIGN.md` section 4's Overlays paragraph names the three legal
459
+ // doors (`ui/useEscapeClose.ts`, `AnchoredOverlay`, `useOverlayLayer`) and says in terms that a
460
+ // local `keydown` listener is the defect, not the shortcut: a menu opened inside a dialog used
461
+ // to race that dialog, and the winner depended on listener registration order rather than on
462
+ // what the person was looking at. A second listener under a registered layer restores the race.
463
+ // ⚠ `rootRef.contains(target)` would also now be WRONG on its own terms: the menu is a child of
464
+ // `<body>`, so a press inside the menu reads as "outside my own UI".
465
 
466
  const onKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {
467
+ // ⭐ W53-T07 — NO `Escape` BRANCH HERE ANY MORE. `useEscapeClose`, reached through
468
+ // `AnchoredOverlay`, owns Escape for whichever overlay is topmost and resolves it to exactly
469
+ // one surface; `closePop` below is what returns focus to the trigger afterwards. A branch here
470
+ // would be a second claimant on the same key.
 
 
471
  // The toolbar's arrows belong to the toolbar only while nothing is open above it.
472
  if (open) return;
473
  const at = Math.max(0, reachable.indexOf(focus));
 
496
  onAction({ kind, arg });
497
  }, [onAction]);
498
 
499
+ /**
500
+ * ⭐⭐ W53-T07 — CLOSING A MENU RETURNS FOCUS TO THE CONTROL THAT OWNS IT, and that is the
501
+ * `done-when`'s third clause. Every `Popover` value is also a `ControlKey` by construction, so
502
+ * the trigger is named by the state itself and no second map can drift out of step.
503
+ * ⛔ `restoreFocus` CANNOT DO THIS JOB HERE, and the reason is worth keeping: every ribbon
504
+ * button carries `onMouseDown={(e) => e.preventDefault()}` so that pressing it never blurs the
505
+ * grid canvas, which means the trigger NEVER RECEIVES FOCUS on a mouse open. `useOverlayLayer`
506
+ * snapshots `document.activeElement` at mount and restores that, so it would faithfully restore
507
+ * the canvas. Focusing the trigger on OPEN instead would blur the canvas for the whole life of
508
+ * the menu, which is precisely the state the `preventDefault` above exists to avoid. Returning
509
+ * focus on CLOSE gets both: the canvas keeps the keyboard while the menu is deciding, and the
510
+ * toolbar gets it back when the menu is gone. This is also exactly what the retired `Escape`
511
+ * branch used to do.
512
+ */
513
+ const closePop = () => {
514
+ if (open) focusControl(open as ControlKey);
515
+ setOpen("");
516
+ };
517
+
518
+ /** Open (or toggle) one popover, remembering the button it hangs from. */
519
+ const openPop = (which: Popover) => (event: ReactMouseEvent<HTMLButtonElement>) => {
520
+ setAnchorEl(event.currentTarget);
521
+ setOpen((was) => (was === which ? "" : which));
522
+ };
523
+
524
  /**
525
  * One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part.
526
  *
 
536
  key: ControlKey,
537
  label: string,
538
  body: ReactNode,
539
+ // ⚠ W53-T07 widened this from `() => void`. A zero-argument lambda is assignable to a
540
+ // one-argument function type, so every existing call site compiles unchanged; only the
541
+ // nine popover triggers actually read the event, for `event.currentTarget` as the anchor.
542
+ onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void,
543
  pressed?: boolean,
544
  expanded?: boolean,
545
  kt?: string,
 
607
  which: "color" | "fill",
608
  list: { token: string; label: string }[],
609
  ) => (
610
+ <AnchoredOverlay
611
+ anchor={anchorEl}
612
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
613
+ onDismiss={closePop}
614
+ role="menu"
615
+ ariaLabel={which === "color" ? "Text colour" : "Fill colour"}
616
+ initialFocus="none"
617
+ >
618
  <div className="sheet-ribbon-swatches">
619
  {list.map((entry) => (
620
  <button
 
640
  >
641
  {which === "color" ? "Reset the text colour" : "No fill"}
642
  </button>
643
+ </AnchoredOverlay>
644
  );
645
 
646
  const format = style?.format;
 
738
  {control("paste", "Paste", <>{<IconPaste />}{word("Paste")}</>,
739
  () => act("paste"), false, undefined, "V")}
740
  </span>
741
+ {/* ⭐⭐ W53-T06 (owner instruction 17) — CUT, COPY AND FORMAT PAINTER ARE ICONS,
742
+ WITH NO WORD BESIDE THEM. Excel's Clipboard group is one large captioned Paste
743
+ and three small icon-only controls; a caption beside a 26px button is the one
744
+ thing its Home ribbon never does. Paste KEEPS its caption, and that is the
745
+ faithful reading rather than an inconsistency: the researched convention is
746
+ that only a wide combo box or a TALL two-row-spanning button carries text, and
747
+ the large Paste is exactly that.
748
+ ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` writes its
749
+ `label` argument into BOTH `aria-label` and `title`, so a screen reader still
750
+ announces "Format painter" and a hover still says it. That matters twice over:
751
+ `verify_api.py`'s `_RIBBON_GROUPS` pins the literals `"Cut"`, `"Copy"` and
752
+ `"Format painter"` as the proof this group still offers what R8 names, and an
753
+ icon-only control with no accessible name is a regression no gate in this repo
754
+ would catch. */}
755
  <div className="sheet-ribbon-clip-stack">
756
+ {control("cut", "Cut", <IconCut />, () => act("cut"),
757
  false, undefined, "X")}
758
+ {control("copy", "Copy", <IconCopy />, () => act("copy"),
759
  false, undefined, "C")}
760
+ {control("painter", "Format painter", <IconFormatPainter />,
 
761
  () => act("format-painter"), false, undefined, "FP")}
762
  </div>
763
  </div>
 
777
 
778
  <span className="sheet-ribbon-slot">
779
  {control("border", "Borders", <><IconBorder /><IconCaret /></>,
780
+ openPop("border"),
781
  Object.values(style?.border ?? {}).some(Boolean), open === "border",
782
  "B", "gallery")}
783
  {open === "border" && (
784
+ <AnchoredOverlay
785
+ anchor={anchorEl}
786
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
787
+ onDismiss={closePop}
788
+ role="menu"
789
+ ariaLabel="Borders"
790
+ initialFocus="none"
791
+ >
792
  {BORDERS.map((entry) => item(
793
  entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt,
794
  ))}
795
  {item("No border", () => apply({ border: null }), false, "menuitem", "N")}
796
+ </AnchoredOverlay>
797
  )}
798
  </span>
799
 
 
805
  <span className="sheet-ribbon-slot">
806
  {control("fill", "Fill colour",
807
  <><IconFill /><IconCaret /></>,
808
+ openPop("fill"), !!style?.fill, open === "fill",
809
  "H", "gallery")}
810
  {open === "fill" && swatches("fill", FILLS)}
811
  </span>
812
  <span className="sheet-ribbon-slot">
813
  {control("color", "Text colour",
814
  <><IconInk /><IconCaret /></>,
815
+ openPop("color"), !!style?.color,
816
  open === "color", "FC", "gallery")}
817
  {open === "color" && swatches("color", INKS)}
818
  </span>
819
 
820
  <span className="sheet-ribbon-slot">
821
  {control("size", "Font size", <>{word("Size")}<IconCaret /></>,
822
+ openPop("size"), false, open === "size",
823
  "FS", "gallery")}
824
  {open === "size" && (
825
+ <AnchoredOverlay
826
+ anchor={anchorEl}
827
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
828
+ onDismiss={closePop}
829
+ role="menu"
830
+ ariaLabel="Font size"
831
+ initialFocus="none"
832
+ >
833
  {SIZE_STEPS.map((step) => item(step.label, () => act("font-size", step.id)))}
834
+ </AnchoredOverlay>
835
  )}
836
  </span>
837
  </>
838
  ))}
839
 
840
+ {/* ⭐⭐ W53-T05 (instruction 16) — ALIGNMENT IS TWO ROWS, NOT ONE LINE. Excel stacks
841
+ the vertical three over the horizontal three and hangs the rest to their right;
842
+ one long line was this group's only real departure from it. The mechanism is the
843
+ one `.sheet-ribbon-clip-stack` already established for Clipboard: a COLUMN wrapper
844
+ inside `.sheet-ribbon-group-controls`, which is itself a row flex, with each row a
845
+ plain row flex of the SAME `control()` buttons. No new control shape, no new
846
+ button size, and the two rows total 52px, which is exactly the height Clipboard's
847
+ large Paste already sets, so the ribbon does not grow by a pixel.
848
+ ⚠ THE SIX ALIGNMENT BUTTONS STAY ICON ONLY, and so does Wrap text: the researched
849
+ Excel convention is that only a WIDE combo box or a TALL two-row-spanning button
850
+ carries a caption, and none of these is either. `control()` writes the label into
851
+ both `aria-label` and `title`, so every one of them keeps its accessible name.
852
+ ⛔ ORIENTATION AND MERGE AND CENTER, which the ticket also names, are NOT here.
853
+ Both need a new `RibbonActionKind`, and `SheetGrid.tsx::onRibbonAction` closes its
854
+ switch with `const _exhaustive: never = action.kind`, so a new member is a type
855
+ error in a file this lane does not own; Merge additionally needs a merged-cell
856
+ model that `sheet/types.ts` does not have. A control rendered anyway, wired to
857
+ nothing, is the fake affordance `RibbonProps` refuses by name. Raised in the
858
+ HANDOFF as a PRD amendment instead. */}
859
  {group("Alignment", (
860
+ <div className="sheet-ribbon-align">
861
+ <div className="sheet-ribbon-align-row">
862
+ {/* ⚠ TOP/MIDDLE/BOTTOM VERTICAL ALIGN HAS NO ROW IN THE TICKET'S OWN INLINE
863
+ KeyTip LIST (it names align top/middle/bottom as one of the examples with no
864
+ row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's
865
+ real Excel sequences use for the horizontal three (`AL`/`AC`/`AR`). */}
866
+ {control("top", "Align top", <IconVAlign to="top" />, () => act("align-top"),
867
+ false, undefined, "AT")}
868
+ {control("middle", "Align middle", <IconVAlign to="middle" />,
869
+ () => act("align-middle"), false, undefined, "AM")}
870
+ {control("bottom", "Align bottom", <IconVAlign to="bottom" />,
871
+ () => act("align-bottom"), false, undefined, "AB")}
872
+ {control("wrap", "Wrap text", <IconWrap />, () => act("wrap-text"),
873
+ false, undefined, "W")}
874
+ </div>
875
+ <div className="sheet-ribbon-align-row">
876
+ {/* ⛔ THIS `.map` STAYS A MAP. Unrolling it into three literal `control("left",
877
+ ...)` calls would delete the `to === "left" ? "AL" : ...` ternary that
878
+ `verify_ui.py::_RIBBON_ALIGN_H_TERNARY` pins byte for byte — the horizontal
879
+ three are the one trio whose key is a variable, which is why their key-tips
880
+ are checked as that one expression rather than per call. */}
881
+ {(["left", "center", "right"] as const).map((to) => control(
882
+ to,
883
+ to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
884
+ <IconAlign to={to} />,
885
+ () => apply({ align: style?.align === to ? null : to }),
886
+ style?.align === to,
887
+ undefined,
888
+ to === "left" ? "AL" : to === "center" ? "AC" : "AR",
889
+ ))}
890
+ {control("outdent", "Decrease indent", <IconIndent out />,
891
+ () => act("indent-decrease"), false, undefined, "5")}
892
+ {control("indent", "Increase indent", <IconIndent out={false} />,
893
+ () => act("indent-increase"), false, undefined, "6")}
894
+ </div>
895
+ </div>
896
  ))}
897
 
898
  {group("Number", (
 
900
  <span className="sheet-ribbon-slot">
901
  {control("format", "Number format",
902
  <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
903
+ openPop("format"), kind !== "general",
904
  open === "format", "N", "gallery")}
905
  {open === "format" && (
906
+ <AnchoredOverlay
907
+ anchor={anchorEl}
908
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
909
+ onDismiss={closePop}
910
+ role="menu"
911
+ ariaLabel="Number format"
912
+ initialFocus="none"
913
+ >
914
  {CELL_FORMAT_KINDS.map((entry) => (
915
  <button
916
  key={entry}
 
980
  Thousands separator
981
  </button>
982
  )}
983
+ </AnchoredOverlay>
984
  )}
985
  </span>
986
 
 
1009
  </>
1010
  ))}
1011
 
1012
+ {/* ⭐⭐ W53-T05 (D-663) — STYLES, CELLS AND EDITING ARE ICON ONLY FROM HERE. Measured
1013
+ at the contract viewport, the seven groups wanted about 1,680px of the 864px the
1014
+ ribbon actually has, so Styles, Cells and Editing were off the right edge entirely
1015
+ and the owner could not see that AutoSum, Insert, Delete and Clear already exist.
1016
+ A caption beside a small same-size button is also the one thing Excel's Home ribbon
1017
+ never does: only a wide combo box or a tall two-row-spanning button carries text.
1018
+ ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` passes its `label`
1019
+ into BOTH `aria-label` and `title`, so a screen reader still announces "Conditional
1020
+ formatting" and a hover still says it. `verify_api.py`'s `_RIBBON_GROUPS` pins each
1021
+ of those label literals, and they are all still right there in the call. */}
1022
  {group("Styles", (
1023
  <>
1024
  {control("conditional", "Conditional formatting",
1025
+ <IconConditional />,
1026
  () => act("conditional-formatting"), false, undefined, "L")}
1027
  </>
1028
  ))}
 
1033
  {group("Cells", (
1034
  <>
1035
  <span className="sheet-ribbon-slot">
1036
+ {control("insert", "Insert", <>{<IconInsert />}<IconCaret /></>,
1037
+ openPop("insert"), false, open === "insert",
1038
  "I", "gallery")}
1039
  {open === "insert" && (
1040
+ <AnchoredOverlay
1041
+ anchor={anchorEl}
1042
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1043
+ onDismiss={closePop}
1044
+ role="menu"
1045
+ ariaLabel="Insert"
1046
+ initialFocus="none"
1047
+ >
1048
  {item("Insert row above", () => act("insert-row"))}
1049
  {item("Insert column left", () => act("insert-column"))}
1050
  {item("Add rows", () => act("add-rows"))}
1051
  {item("Add columns", () => act("add-columns"))}
1052
+ </AnchoredOverlay>
1053
  )}
1054
  </span>
1055
  <span className="sheet-ribbon-slot">
1056
+ {control("delete", "Delete", <>{<IconDelete />}<IconCaret /></>,
1057
+ openPop("delete"), false, open === "delete",
1058
  "D", "gallery")}
1059
  {open === "delete" && (
1060
+ <AnchoredOverlay
1061
+ anchor={anchorEl}
1062
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1063
+ onDismiss={closePop}
1064
+ role="menu"
1065
+ ariaLabel="Delete"
1066
+ initialFocus="none"
1067
+ >
1068
  {item("Delete row", () => act("delete-row"))}
1069
  {item("Delete column", () => act("delete-column"))}
1070
+ </AnchoredOverlay>
1071
  )}
1072
  </span>
1073
  <span className="sheet-ribbon-slot">
1074
  {control("cellformat", "Format",
1075
+ <>{<IconCellFormat />}<IconCaret /></>,
1076
+ openPop("cellformat"), false,
1077
  open === "cellformat", "O", "gallery")}
1078
  {open === "cellformat" && (
1079
+ <AnchoredOverlay
1080
+ anchor={anchorEl}
1081
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1082
+ onDismiss={closePop}
1083
+ role="menu"
1084
+ ariaLabel="Format"
1085
+ initialFocus="none"
1086
+ >
1087
  {item("Row height", () => act("row-height"))}
1088
  {item("Column width", () => act("column-width"))}
1089
  {item("Hide rows", () => act("hide-rows"))}
 
1100
  ticket that never touched this file. */}
1101
  {item("Freeze panes", () => act("freeze"), frozen,
1102
  "menuitemcheckbox")}
1103
+ </AnchoredOverlay>
1104
  )}
1105
  </span>
1106
  </>
 
1108
 
1109
  {group("Editing", (
1110
  <>
1111
+ {control("autosum", "AutoSum", <IconAutoSum />,
1112
  () => act("autosum"), false, undefined, "U")}
1113
  {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST.
1114
  `FD`/`FR` are invented, non-colliding with `FP` (Format painter), `FS` (Font
1115
  size) or `FC` (Font colour). */}
1116
+ {control("filldown", "Fill down", <IconFillDown />,
1117
  () => act("fill-down"), false, undefined, "FD")}
1118
+ {control("fillright", "Fill right", <IconFillRight />,
1119
  () => act("fill-right"), false, undefined, "FR")}
1120
  <span className="sheet-ribbon-slot">
1121
+ {control("clear", "Clear", <>{<IconClear />}<IconCaret /></>,
1122
+ openPop("clear"), false, open === "clear",
1123
  "E", "gallery")}
1124
  {open === "clear" && (
1125
+ <AnchoredOverlay
1126
+ anchor={anchorEl}
1127
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1128
+ onDismiss={closePop}
1129
+ role="menu"
1130
+ ariaLabel="Clear"
1131
+ initialFocus="none"
1132
+ >
1133
  {item("Clear contents", () => act("clear-contents"))}
1134
  {item("Clear formats", () => act("clear-formats"))}
1135
  {item("Clear all", () => act("clear-all"))}
1136
+ </AnchoredOverlay>
1137
  )}
1138
  </span>
1139
  </>
web/src/sheet/SheetGrid.tsx CHANGED
@@ -149,7 +149,7 @@ import type {
149
  } from "./types";
150
  import {
151
  addressOf, appendLineBreak, autoSumFormula, boundDragLabel, cellAt,
152
- cellShiftLabel, clearAll,
153
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
154
  editableText, fillCells, fillDown, fillRight, findMatches,
155
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
@@ -585,6 +585,44 @@ export default function SheetGrid({
585
  /** W52-T06 — the floating formula editor. `null` means no formula is being authored right now. */
586
  const [formulaEdit, setFormulaEdit] = useState<FormulaEditState | null>(null);
587
  const formulaInputRef = useRef<HTMLInputElement | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
588
 
589
  const extent = sheetExtent(tab);
590
  const widths = tab.colWidths ?? {};
@@ -745,6 +783,61 @@ export default function SheetGrid({
745
 
746
  const cells = tab.cells ?? {};
747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748
  const getCellContent = useCallback(
749
  ([col, row]: Item): GridCell => {
750
  const cell = cells[addrAt(col, row)] ?? null;
@@ -905,14 +998,36 @@ export default function SheetGrid({
905
  });
906
  }, [bandRows, fromBand, onSelectionChange]);
907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
  /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
909
  const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
910
  const addr = addrAt(item[0], item[1]);
911
- onCommit({ [addr]: commitTyped(cellAt(tab, addr), typedText(value)) });
912
  // ⭐ W52-T07: an edit is a stronger "moved on" signal than a selection change; the paste
913
  // highlight retires here too, same reasoning as `onSelectionChange`.
914
  setPasteHighlight(null);
915
- }, [addrAt, onCommit, tab]);
916
 
917
  /**
918
  * The batch door glide uses for a paste it applies itself and for its own fill. Returning
@@ -927,12 +1042,12 @@ export default function SheetGrid({
927
  const cell = cellAt(tab, addr);
928
  // ⭐ R5 (W52-T09): a bound cell is no longer skipped here - `commitTyped` clears its
929
  // binding exactly as it does for the single-cell door above.
930
- edits[addr] = commitTyped(cell, typedText(item.value));
931
  }
932
- onCommit(edits);
933
  return true;
934
  },
935
- [addrAt, onCommit, tab],
936
  );
937
 
938
  /**
@@ -984,8 +1099,14 @@ export default function SheetGrid({
984
  const commitFormulaEditor = useCallback(() => {
985
  if (!formulaEdit) return;
986
  const { addr, draft, inBand, viewCell } = formulaEdit;
987
- onCommit({ [addr]: commitTyped(cellAt(tab, addr), draft) });
 
 
 
 
 
988
  setFormulaEdit(null);
 
989
  // Mirrors glide's own default Enter-commit: the selection moves down one row, so the custom
990
  // editor does not feel like a different control from editing any other cell.
991
  // ⚠ NOT `applySelection` -- that helper is declared FURTHER DOWN this component (it is the
@@ -1000,7 +1121,7 @@ export default function SheetGrid({
1000
  });
1001
  gridRef.current?.scrollTo(next[0], next[1]);
1002
  }
1003
- }, [formulaEdit, onCommit, onSelectionChange, tab]);
1004
 
1005
  /**
1006
  * PM-4/PM-5/PM-7/PM-8: every point-mode proposal, arrived at from either the anchor (a fresh
@@ -1198,11 +1319,22 @@ export default function SheetGrid({
1198
  * ⚠ EACH CELL OF A RANGE GETS ITS OWN BORDER, not one rectangle traced around the range's outer
1199
  * edge. Simpler, and still says "these cells" unambiguously; tracing only the outer edge is the
1200
  * tidy follow up.
 
 
 
 
 
 
 
 
1201
  */
1202
  const formulaRefCells = useMemo(() => {
1203
  const out = new Map<string, string>();
1204
- if (!formulaEdit) return out;
1205
- for (const ref of refsIn(formulaEdit.draft)) {
 
 
 
1206
  const c0 = colToIndex(ref.start.col);
1207
  const c1 = colToIndex(ref.end.col);
1208
  const r0 = ref.start.row;
@@ -1217,8 +1349,105 @@ export default function SheetGrid({
1217
  }
1218
  }
1219
  return out;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1220
  }, [formulaEdit]);
1221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1222
  /**
1223
  * ⭐⭐ W51-T19 — THE SHEET'S OWN MEMORY OF WHAT WAS COPIED, AND WHY IT HAS TO EXIST.
1224
  *
@@ -1271,6 +1500,85 @@ export default function SheetGrid({
1271
  setPasteHighlight(null);
1272
  });
1273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1274
  /** The drag rules for a paste of `values`, or `undefined` when this block is not ours. */
1275
  const copiedBlock = useCallback(
1276
  (values: readonly (readonly string[])[]): DragContext | undefined => {
@@ -1331,13 +1639,15 @@ export default function SheetGrid({
1331
  ? screenEdits(tab, plain)
1332
  : { edits: plain, refusals: [] as { addr: string; message: string }[] };
1333
  const edits = { ...dragged, ...screened.edits };
1334
- if (Object.keys(edits).length > 0) onCommit(edits);
 
 
1335
  const said = [
1336
  screened.refusals.length > 0 ? refusalLabel(screened.refusals) : "",
1337
  boundDragLabel(out),
1338
  ].filter(Boolean).join(" ");
1339
  if (said) onNotice(said);
1340
- }, [onCommit, onNotice, tab]);
1341
 
1342
  /**
1343
  * ⭐ THE PASTE IS OURS, NOT GLIDE'S, AND IT RETURNS `false` DELIBERATELY. glide has already
@@ -1361,8 +1671,22 @@ export default function SheetGrid({
1361
  // ⚠ THE TARGET IS TRANSLATED, THE BLOCK IS NOT. A paste lands as a rectangle in the SHEET,
1362
  // which is Excel's own behaviour: it fills hidden rows too rather than skipping them and
1363
  // silently landing a person's forty values on the wrong forty cells.
 
 
 
 
1364
  const out = pasteCells(tab, realCol(target[0]), realRow(target[1]), values,
1365
- { cols: extent.cols, rows: extent.rows }, copiedBlock(values));
 
 
 
 
 
 
 
 
 
 
1366
  // ⛔⛔ W51-T18 / C2 — A PASTE IS ONE OF THE TWO DOORS THAT CAN LAND A VALUE OUTSIDE A CELL'S
1367
  // LIST, and it is the one that gets forgotten because the dropdown looks like the whole
1368
  // feature. The block is screened against the validation the TARGET already carries, the
@@ -1374,8 +1698,8 @@ export default function SheetGrid({
1374
  cols: values[0]?.length ?? 0, rows: values.length });
1375
  return false;
1376
  },
1377
- [copiedBlock, extent.cols, extent.rows, isRecognizedCopy, landFill, onNotice, realCol, realRow,
1378
- tab],
1379
  );
1380
 
1381
  /**
@@ -1404,22 +1728,16 @@ export default function SheetGrid({
1404
  // the paste door all reach that same arithmetic, which is what makes "a locked period
1405
  // copies verbatim through every door" one fact instead of four that agree today.
1406
  { catalogue: options },
 
 
1407
  );
1408
  // ⛔ W51-T18 / C2 — AND THE FILL IS THE SECOND DOOR. Dragging a value down a column lands
1409
  // it on every cell it passes, list or no list, so it is screened exactly as the paste is.
1410
  landFill(out, true);
1411
  },
1412
- [landFill, options, realCol, realRow, tab],
1413
  );
1414
 
1415
- /** The selected rectangle in glide's own VIEW coordinates, or `null` when nothing is selected. */
1416
- const viewRange = useCallback((): CellRange | null => {
1417
- const current = selection?.current;
1418
- if (!current) return null;
1419
- const r = current.range;
1420
- return { col0: r.x, row0: r.y, col1: r.x + r.width - 1, row1: r.y + r.height - 1 };
1421
- }, [selection]);
1422
-
1423
  /** Every address the selection covers, translated. `[]` when nothing is selected. */
1424
  const selectedAddrs = useCallback((): string[] => {
1425
  const range = viewRange();
@@ -1470,8 +1788,12 @@ export default function SheetGrid({
1470
  return;
1471
  }
1472
  const out = clearCells(tab, addrs);
1473
- if (Object.keys(out.edits).length > 0) onCommit(out.edits);
1474
- }, [onCommit, onNotice, selectedAddrs, tab]);
 
 
 
 
1475
 
1476
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1477
  // ⭐⭐ W51-T17 — WHAT A SHORTCUT AND A HEADER CLICK BOTH NEED: ONE WAY TO SET THE SELECTION.
@@ -1613,9 +1935,11 @@ export default function SheetGrid({
1613
  // ⭐ R5 (W52-T09): `shiftCells` no longer declines the whole act over a bound cell in range -
1614
  // it drops out with everything else the shift moves.
1615
  const out = shiftCells(tab, real, insert, { rows: extent.rows });
1616
- if (Object.keys(out.edits).length > 0) onCommit(out.edits);
 
 
1617
  onNotice(cellShiftLabel(insert, out.dropped));
1618
- }, [extent.rows, onCommit, onNotice, onStructure, realCol, realRow, tab, viewRange,
1619
  visCols.length, visRows.length]);
1620
 
1621
  /**
@@ -1684,9 +2008,8 @@ export default function SheetGrid({
1684
  * ⛔ THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED. A browser that refuses clipboard access on a
1685
  * cut would otherwise delete a person's cells with nothing on the clipboard to paste back.
1686
  *
1687
- * ⭐ IT WRITES WHAT THE CELL READS, not what it stores: `formatCellText` over `displayText`, so
1688
- * a currency cell arrives in Excel as the currency somebody chose. That is the same string
1689
- * `displayData` carries, which is what makes glide's own Ctrl+C agree with this button.
1690
  */
1691
  const copySelection = useCallback((cut: boolean) => {
1692
  const range = viewRange();
@@ -1694,33 +2017,16 @@ export default function SheetGrid({
1694
  onNotice(cut ? "Select a cell first, then cut it." : "Select a cell first, then copy it.");
1695
  return;
1696
  }
1697
- const lines: string[] = [];
1698
- // ⭐ W51-T19: the CELLS are kept beside the text, so a bound cell pasted back into the sheet
1699
- // can take its drag rules. See `copiedRef` for why the text alone cannot carry a binding.
1700
- const block: (Cell | null)[][] = [];
1701
- for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) {
1702
- const line: string[] = [];
1703
- const row: (Cell | null)[] = [];
1704
- for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
1705
- c += 1) {
1706
- const cell = cells[addrAt(c, r)] ?? null;
1707
- line.push(formatCellText(cell, displayText(cell)));
1708
- row.push(cell);
1709
- }
1710
- lines.push(line.join("\t"));
1711
- block.push(row);
1712
- }
1713
- const text = lines.join("\n");
1714
  // ⛔ RECORDED ONLY ON A SUCCESSFUL WRITE, so the sheet never believes it holds a block the
1715
  // clipboard does not. It is a SEPARATE `then` so that the clear stays the one line a
1716
  // W51-T17 gate leg pins: a cut clears the source only after the copy landed, and folding
1717
  // the two together would have moved that leg's anchor for no reason at all.
1718
- const held = {
1719
- text,
1720
- col: realCol(Math.min(range.col0, range.col1)),
1721
- row: realRow(Math.min(range.row0, range.row1)),
1722
- cells: block,
1723
- };
1724
  navigator.clipboard.writeText(text)
1725
  .then(() => {
1726
  copiedRef.current = held;
@@ -1732,7 +2038,7 @@ export default function SheetGrid({
1732
  .then(() => { if (cut) clearSelection(); })
1733
  .catch(() => onNotice("This browser did not let the sheet write to the clipboard. "
1734
  + "Press Ctrl+C instead."));
1735
- }, [addrAt, cells, clearSelection, onNotice, realCol, realRow, viewRange]);
1736
 
1737
  /**
1738
  * PASTE. glide already handles Ctrl+V through `onPaste`; this is the ribbon's own door, which
@@ -1754,16 +2060,25 @@ export default function SheetGrid({
1754
  }
1755
  const values = text.replace(/\r\n/g, "\n").replace(/\n+$/, "")
1756
  .split("\n").map((line) => line.split("\t"));
 
 
1757
  const out = pasteCells(tab, realCol(range.col0), realRow(range.row0), values,
1758
- { cols: extent.cols, rows: extent.rows }, copiedBlock(values));
 
 
 
 
 
 
 
1759
  landFill(out, false);
1760
  // ⭐ W52-T07: same highlight the glide door sets, from the ribbon's own paste path.
1761
  setPasteHighlight({ col: realCol(range.col0), row: realRow(range.row0),
1762
  cols: values[0]?.length ?? 0, rows: values.length });
1763
  }).catch(() => onNotice("This browser did not let the sheet read the clipboard. "
1764
  + "Press Ctrl+V instead."));
1765
- }, [copiedBlock, extent.cols, extent.rows, isRecognizedCopy, landFill, onNotice, realCol,
1766
- realRow, tab, viewRange]);
1767
 
1768
  /**
1769
  * THE FORMAT PAINTER, WHICH IS TWO GESTURES AND NOT ONE. Pressing it picks the anchor cell's
@@ -1815,8 +2130,8 @@ export default function SheetGrid({
1815
  const cell = cellAt(tab, addr);
1816
  // ⭐ R5 (W52-T09): AutoSum on a bound cell writes over it exactly like any other cell -
1817
  // `setFormula` already drops a binding on its own.
1818
- onCommit({ [addr]: setFormula(cell, formula) });
1819
- }, [onCommit, onNotice, realCol, realRow, selection, tab]);
1820
 
1821
  /** Fill down and fill right, through the same door the fill HANDLE uses. */
1822
  const fillSelection = useCallback((axis: "down" | "right") => {
@@ -1853,8 +2168,13 @@ export default function SheetGrid({
1853
  return;
1854
  }
1855
  const out = which === "formats" ? clearFormats(tab, addrs) : clearAll(tab, addrs);
1856
- if (Object.keys(out.edits).length > 0) onCommit(out.edits);
1857
- }, [onCommit, onNotice, selectedAddrs, tab]);
 
 
 
 
 
1858
 
1859
  /** Hide the rows or the columns the selection covers, and remember them on the tab. */
1860
  const hideBand = useCallback((axis: "row" | "col") => {
@@ -2011,14 +2331,16 @@ export default function SheetGrid({
2011
  }
2012
  const cell = cellAt(tab, dropdown.addr);
2013
  const next = commitTyped(cell, canonicalEntry(list, text));
2014
- onCommit({
 
 
2015
  // ⚠ THE LIST SURVIVES THE CHOICE. `commitTyped` builds a fresh literal, so handing back its
2016
  // result unchanged would delete the very validation that produced the value.
2017
  [dropdown.addr]: next ? { ...next, validation: { list: [...list] } }
2018
  : { kind: "empty", state: "fresh", validation: { list: [...list] } },
2019
  });
2020
  setDropdown(null);
2021
- }, [dropdown, onCommit, onNotice, tab]);
2022
 
2023
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2024
  // ⭐⭐ W51-T15 DECLARED THE VOCABULARY, W51-T16 ANSWERS EVERY WORD OF IT.
@@ -2250,6 +2572,7 @@ export default function SheetGrid({
2250
  // bound cell by a different rule from the one beside it, which is exactly the split
2251
  // "one primitive, every door" exists to prevent.
2252
  { catalogue: options },
 
2253
  );
2254
  if (Object.keys(out.edits).length === 0) {
2255
  onNotice("Select the cell to copy and the cells to fill, then press Ctrl+Enter.");
@@ -2263,7 +2586,7 @@ export default function SheetGrid({
2263
  // ⭐ R5 (W52-T09): a bound cell is no longer walled off here - `appendLineBreak`
2264
  // writes through `commitTyped`, which drops its binding on its own.
2265
  const out = appendLineBreak(tab, addrAt(cur.cell[0], cur.cell[1]));
2266
- if (Object.keys(out.edits).length > 0) onCommit(out.edits);
2267
  return;
2268
  }
2269
  case "today": {
@@ -2271,7 +2594,7 @@ export default function SheetGrid({
2271
  const addr = addrAt(cur.cell[0], cur.cell[1]);
2272
  const cell = cellAt(tab, addr);
2273
  // ⭐ R5 (W52-T09): Ctrl+; on a bound cell writes over it exactly like any other cell.
2274
- onCommit({ [addr]: commitTyped(cell, dateStamp(new Date())) });
2275
  return;
2276
  }
2277
 
@@ -2314,7 +2637,7 @@ export default function SheetGrid({
2314
  }
2315
  const next = cycleAnchors(cell.formula ?? "");
2316
  if (!next || next === cell.formula) return;
2317
- onCommit({ [addr]: setFormula(cell, next) });
2318
  return;
2319
  }
2320
  case "find": setFind((was) => was ?? { query: "", at: -1 }); return;
@@ -2326,7 +2649,8 @@ export default function SheetGrid({
2326
  }
2327
  }
2328
  },
2329
- [addrAt, anchorStyle, applySelection, applyStyle, bandRows, extent.cols, extent.rows,
 
2330
  onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor,
2331
  openNumberFormat, realCol, realRow, selection, structureForSelection, switchTab, tab,
2332
  viewRange, viewRowOf, visCols, visRows],
@@ -2499,13 +2823,23 @@ export default function SheetGrid({
2499
  // `!cell` early return, for the same reason `ruleStyle` is (W51-T18's own note two lines up):
2500
  // a formula can reference a perfectly BLANK cell, and that cell still has to wear the border,
2501
  // not be treated as nothing to paint.
2502
- const refColor = formulaRefCells.get(`${realCol(col) + 1},${realRow(row) + 1}`);
 
 
 
 
 
 
 
 
2503
  const paintRefBorder = () => {
2504
  if (!refColor) return;
2505
  ctx.save();
2506
  ctx.strokeStyle = refColor;
2507
  ctx.lineWidth = 2;
 
2508
  ctx.strokeRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
 
2509
  ctx.restore();
2510
  };
2511
 
@@ -2547,6 +2881,34 @@ export default function SheetGrid({
2547
  ctx.restore();
2548
  }
2549
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2550
  if (!cell && !ruleStyle) { drawContent(); paintRefBorder(); paintMarquee(); return; }
2551
 
2552
  const mark = cell ? MARK_STYLE[markOf(cell)] : undefined;
@@ -2600,6 +2962,7 @@ export default function SheetGrid({
2600
  // ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so
2601
  // the mark sits on top of the value rather than under it.
2602
  drawContent();
 
2603
  paintMark();
2604
  paintRefBorder();
2605
  paintMarquee();
@@ -2703,6 +3066,7 @@ export default function SheetGrid({
2703
  ctx.restore();
2704
  }
2705
 
 
2706
  paintMark();
2707
  paintRefBorder();
2708
  paintMarquee();
@@ -2712,7 +3076,8 @@ export default function SheetGrid({
2712
  // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's
2713
  // territory for a line that was never wrong, only no longer load bearing.
2714
  return true;
2715
- }, [addrAt, cells, copyMarquee, formulaRefCells, pasteHighlight, realCol, realRow, rules]);
 
2716
 
2717
  /**
2718
  * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not
 
149
  } from "./types";
150
  import {
151
  addressOf, appendLineBreak, autoSumFormula, boundDragLabel, cellAt,
152
+ cellShiftLabel, cellToValue, clearAll, recalcDependents,
153
  clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
154
  editableText, fillCells, fillDown, fillRight, findMatches,
155
  isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
 
585
  /** W52-T06 — the floating formula editor. `null` means no formula is being authored right now. */
586
  const [formulaEdit, setFormulaEdit] = useState<FormulaEditState | null>(null);
587
  const formulaInputRef = useRef<HTMLInputElement | null>(null);
588
+ /**
589
+ * ⭐⭐ W53-T02 / INSTRUCTION 11 — EVERY EXIT PATH RETURNS TO READY, AND THE KEYBOARD HAS TO
590
+ * COME WITH IT. Excel's four cell modes (Ready/Enter/Edit/Point) all fall back to Ready on any
591
+ * commit, and in Ready the ARROW KEYS MOVE THE GRID SELECTION. Here that only happens while
592
+ * the grid's own accessibility element holds the keyboard.
593
+ *
594
+ * ⛔ MEASURED, NOT ASSUMED. Driving the real app: while editing, `document.activeElement` is
595
+ * this file's floating `<input class="sheet-formula-editor-input">`; one Enter later it is
596
+ * `BODY`, and the very next ArrowRight moves nothing (E7 stayed E7). Clicking the canvas put
597
+ * focus back on glide's own `TD` and the same ArrowRight then moved C10 to D10. So the defect
598
+ * was never a swallowed keydown: the floating editor is NOT glide's own cell overlay (the
599
+ * block below the render says why), so when it unmounts nothing hands the keyboard back and
600
+ * the browser parks focus on `<body>`.
601
+ *
602
+ * ⛔ IT RUNS OFF `formulaEdit` GOING NON-NULL -> NULL, NOT OFF ANY ONE KEY. That is what covers
603
+ * Enter, Tab, blur, click-away, Escape and a throw mid-commit THE SAME WAY, with no per-path
604
+ * duplication: every one of them ends in `setFormulaEdit(null)`, so this is the one place their
605
+ * effects converge. The ref remembers which grid was in use, because by the time the effect
606
+ * sees `null` the state that said so is gone.
607
+ *
608
+ * ⚠ AND IT NEVER STEALS. It acts only when nothing else took the focus (`<body>` is the
609
+ * browser's own "the focused node was removed" answer), so clicking a ribbon button or the
610
+ * formula bar mid-edit still commits and still leaves that control focused.
611
+ */
612
+ const formulaGridWasBand = useRef(false);
613
+ const formulaWasOpen = useRef(false);
614
+ useEffect(() => {
615
+ if (formulaEdit) {
616
+ formulaWasOpen.current = true;
617
+ formulaGridWasBand.current = formulaEdit.inBand;
618
+ return;
619
+ }
620
+ if (!formulaWasOpen.current) return;
621
+ formulaWasOpen.current = false;
622
+ const active = document.activeElement;
623
+ if (active !== null && active !== document.body) return;
624
+ (formulaGridWasBand.current ? bandGridRef : gridRef).current?.focus();
625
+ }, [formulaEdit]);
626
 
627
  const extent = sheetExtent(tab);
628
  const widths = tab.colWidths ?? {};
 
783
 
784
  const cells = tab.cells ?? {};
785
 
786
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
787
+ // ⭐⭐ W53-T01 / RULING R2 / INSTRUCTION 19 — THE IN-CELL SHIMMER, AND WHY IT IS DRIVEN RATHER
788
+ // THAN DECLARED.
789
+ //
790
+ // R2 splits the sheet's calculation in two: a formula over other cells lands INSTANTLY (there
791
+ // is no round trip left to wait for), and only a DATABASE-BOUND cell still goes to the server.
792
+ // Instruction 19 is about what the reader sees during that second half: "show visually that the
793
+ // formula was refreshed first, quickly, before the database cell gets refreshed". So the wait
794
+ // is shown where the wait actually is — inside the one cell that is waiting — instead of in a
795
+ // global status strip that made every cell look busy while most of them were already done.
796
+ //
797
+ // ⛔ A CANVAS DOES NOT ANIMATE ITSELF. glide paints on demand, so a moving band needs somebody
798
+ // to ask for the repaint: this ticks a phase and damages ONLY the pending cells, which is why
799
+ // the phase is a ref rather than state (state would rebuild `paintCell` and repaint the whole
800
+ // viewport twelve times a second for a band crossing four cells).
801
+ //
802
+ // ⛔⛔ AND IT STOPS. `pendingBoundCells` empty means no interval at all: a permanent animation
803
+ // promising a number that never arrives is exactly the defect `customer-grid/CustomerGrid.tsx`
804
+ // already carries a warning about, and it is worse than no animation, because it teaches the
805
+ // reader that motion means nothing.
806
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
807
+ const shimmerPhase = useRef(0);
808
+ const pendingBoundCells = useMemo(
809
+ () => Object.entries(cells)
810
+ .filter(([, cell]) => cell && cell.kind === "bound" && cell.state === "stale")
811
+ .map(([addr]) => addr),
812
+ [cells],
813
+ );
814
+ const pendingBoundKey = pendingBoundCells.join(",");
815
+ useEffect(() => {
816
+ if (!pendingBoundKey) {
817
+ shimmerPhase.current = 0;
818
+ return undefined;
819
+ }
820
+ const addrs = pendingBoundKey.split(",");
821
+ const id = window.setInterval(() => {
822
+ shimmerPhase.current = (shimmerPhase.current + 0.06) % 1;
823
+ const main: { cell: Item }[] = [];
824
+ const band: { cell: Item }[] = [];
825
+ for (const addr of addrs) {
826
+ const at = splitAddress(addr);
827
+ if (!at) continue;
828
+ const viewCol = viewIndexOf(visCols, at.col - 1);
829
+ const viewRow = viewRowOf(at.row - 1);
830
+ // A NEGATIVE VIEW ROW IS THE FROZEN BAND, which is its own `DataEditor` counting from
831
+ // zero, so it is damaged through its own handle rather than the main grid's.
832
+ if (viewRow < 0) band.push({ cell: [viewCol, viewRow + bandRows] as Item });
833
+ else main.push({ cell: [viewCol, viewRow] as Item });
834
+ }
835
+ if (main.length > 0) gridRef.current?.updateCells(main);
836
+ if (band.length > 0) bandGridRef.current?.updateCells(band);
837
+ }, 90);
838
+ return () => window.clearInterval(id);
839
+ }, [bandRows, pendingBoundKey, viewRowOf, visCols]);
840
+
841
  const getCellContent = useCallback(
842
  ([col, row]: Item): GridCell => {
843
  const cell = cells[addrAt(col, row)] ?? null;
 
998
  });
999
  }, [bandRows, fromBand, onSelectionChange]);
1000
 
1001
+ /**
1002
+ * ⭐⭐ W53-T01 / RULING R2 — THE `get` CALLBACK THAT MAKES A COMMITTED FORMULA COMPUTE OFFLINE.
1003
+ * One closure over the CURRENT `tab`, handed to `commitTyped`/`setFormula` at every commit door
1004
+ * below: `evaluateFormula` never reads a `Cell` itself, so this is the one place that answers
1005
+ * its `get(addr)` question in terms of what this component already has in scope.
1006
+ */
1007
+ const cellValueGetter = useCallback((addr: string) => cellToValue(cellAt(tab, addr)), [tab]);
1008
+
1009
+ /**
1010
+ * ⭐⭐ W53-T01 / INSTRUCTION 11 — EVERY COMMIT DOOR IN THIS FILE LANDS THROUGH HERE, so a write
1011
+ * and the recalculation it forces are ONE commit: one history step, one queued save. A second
1012
+ * `onCommit` for the dependents would cost two Ctrl+Z presses to undo one edit and would race
1013
+ * itself for the document's `rev`.
1014
+ *
1015
+ * ⛔ IT IS A CALLBACK, NOT AN EFFECT, AND THAT IS THE WHOLE DIFFERENCE. `onCommit` is
1016
+ * `SheetPage.tsx::commitCells`, which pushes history and queues a save; an effect watching the
1017
+ * document would mutate a workbook nobody edited and write it back merely for opening a sheet.
1018
+ */
1019
+ const commitWithRecalc = useCallback((edits: Record<string, Cell | null>) => {
1020
+ onCommit({ ...edits, ...recalcDependents(tab, edits) });
1021
+ }, [onCommit, tab]);
1022
+
1023
  /** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
1024
  const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
1025
  const addr = addrAt(item[0], item[1]);
1026
+ commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), typedText(value), cellValueGetter) });
1027
  // ⭐ W52-T07: an edit is a stronger "moved on" signal than a selection change; the paste
1028
  // highlight retires here too, same reasoning as `onSelectionChange`.
1029
  setPasteHighlight(null);
1030
+ }, [addrAt, cellValueGetter, commitWithRecalc, tab]);
1031
 
1032
  /**
1033
  * The batch door glide uses for a paste it applies itself and for its own fill. Returning
 
1042
  const cell = cellAt(tab, addr);
1043
  // ⭐ R5 (W52-T09): a bound cell is no longer skipped here - `commitTyped` clears its
1044
  // binding exactly as it does for the single-cell door above.
1045
+ edits[addr] = commitTyped(cell, typedText(item.value), cellValueGetter);
1046
  }
1047
+ commitWithRecalc(edits);
1048
  return true;
1049
  },
1050
+ [addrAt, cellValueGetter, commitWithRecalc, tab],
1051
  );
1052
 
1053
  /**
 
1099
  const commitFormulaEditor = useCallback(() => {
1100
  if (!formulaEdit) return;
1101
  const { addr, draft, inBand, viewCell } = formulaEdit;
1102
+ // ⭐⭐ W53-T02 — READY IS RESTORED FIRST, THE WRITE SECOND, and the order is the whole point.
1103
+ // `commitWithRecalc` eventually reaches the caller's own save door and this component does
1104
+ // not know what it can throw; clearing the edit BEFORE calling it means a throw mid-commit
1105
+ // still leaves the sheet in Ready mode (arrows working, focus handed back by the effect
1106
+ // beside `formulaEdit`) instead of stranded in Enter or Point mode. Both updates land in the
1107
+ // same React batch, so nothing renders in between and the draft is already destructured.
1108
  setFormulaEdit(null);
1109
+ commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), draft, cellValueGetter) });
1110
  // Mirrors glide's own default Enter-commit: the selection moves down one row, so the custom
1111
  // editor does not feel like a different control from editing any other cell.
1112
  // ⚠ NOT `applySelection` -- that helper is declared FURTHER DOWN this component (it is the
 
1121
  });
1122
  gridRef.current?.scrollTo(next[0], next[1]);
1123
  }
1124
+ }, [cellValueGetter, commitWithRecalc, formulaEdit, onSelectionChange, tab]);
1125
 
1126
  /**
1127
  * PM-4/PM-5/PM-7/PM-8: every point-mode proposal, arrived at from either the anchor (a fresh
 
1319
  * ⚠ EACH CELL OF A RANGE GETS ITS OWN BORDER, not one rectangle traced around the range's outer
1320
  * edge. Simpler, and still says "these cells" unambiguously; tracing only the outer edge is the
1321
  * tidy follow up.
1322
+ *
1323
+ * ⭐⭐ W53-T02 / INSTRUCTION 18 — RANGE FINDER ALSO FIRES ON A BARE SELECTION. Microsoft's own
1324
+ * page documents only the edit-mode trigger ("double-click the cell ... Excel highlights each
1325
+ * cell or range of cells referenced by the formula with a different color"), and instruction 18
1326
+ * widens it in this app's own words: "Excel highlights EVERY cell a formula references when you
1327
+ * click a formula cell". So when no editor is open, the SELECTED cell's stored formula lends
1328
+ * its text to this same engine. One source string, one border map, one paint path
1329
+ * (`paintRefBorder` further down) - there is no second outline mechanism to keep in step.
1330
  */
1331
  const formulaRefCells = useMemo(() => {
1332
  const out = new Map<string, string>();
1333
+ const source = formulaEdit
1334
+ ? formulaEdit.draft
1335
+ : (selected?.cell?.kind === "formula" ? (selected.cell.formula ?? "") : "");
1336
+ if (!source) return out;
1337
+ for (const ref of refsIn(source)) {
1338
  const c0 = colToIndex(ref.start.col);
1339
  const c1 = colToIndex(ref.end.col);
1340
  const r0 = ref.start.row;
 
1349
  }
1350
  }
1351
  return out;
1352
+ }, [formulaEdit, selected]);
1353
+
1354
+ /**
1355
+ * ⭐⭐ W53-T02 / INSTRUCTION 18, VERBATIM — THE LIVE POINT-MODE PROPOSAL, AND IT IS THE ONE
1356
+ * THING DRAWN DASHED. "when navigating with arrow keys from the formula form say from =D7 to
1357
+ * =D6, the CELL of D6 should be dashed outlined in colour so the user knows which cell is
1358
+ * highlighted."
1359
+ *
1360
+ * ⛔ DASHED HERE, SOLID EVERYWHERE ELSE, and the two are not in conflict: they are different
1361
+ * states. `.claude/wiki/research/excel-formula-ux.md` §1 quotes Microsoft on a formula's
1362
+ * SETTLED references - "the cell range has a blue border with square corners" - so a reference
1363
+ * keeps the solid border it already had, in edit AND in select. What is dashed is only the
1364
+ * proposal still moving under the arrow keys, which is exactly the cell instruction 18 names.
1365
+ *
1366
+ * ⚠ AND IT IS NOT THE COPY MARQUEE. `paintMarquee` below also dashes, in `--lp-blue-deep`,
1367
+ * always the same colour; this one carries the REF_COLORS slot colour of the reference it is
1368
+ * building, which the marquee never does, so the two never read as the same event.
1369
+ *
1370
+ * ⭐ IT READS `pointCell`/`rangeAnchor` RATHER THAN RE-SCANNING THE DRAFT, because the draft
1371
+ * cannot say WHICH of its references is the live one: `=F6+F6` has two occurrences of the same
1372
+ * text and only one of them is under the arrow keys.
1373
+ */
1374
+ const formulaPointCells = useMemo(() => {
1375
+ const out = new Set<string>();
1376
+ if (!formulaEdit || formulaEdit.mode !== "point" || !formulaEdit.pointCell) return out;
1377
+ const a = formulaEdit.rangeAnchor ?? formulaEdit.pointCell;
1378
+ const b = formulaEdit.pointCell;
1379
+ // The same cap `formulaRefCells` uses: a pathological proposal must not stall a paint.
1380
+ if ((Math.abs(b.col - a.col) + 1) * (Math.abs(b.row - a.row) + 1) > 4000) return out;
1381
+ for (let c = Math.min(a.col, b.col); c <= Math.max(a.col, b.col); c += 1) {
1382
+ for (let r = Math.min(a.row, b.row); r <= Math.max(a.row, b.row); r += 1) {
1383
+ out.add(`${c},${r}`);
1384
+ }
1385
+ }
1386
+ return out;
1387
  }, [formulaEdit]);
1388
 
1389
+ /**
1390
+ * ⭐⭐ W53-T02 — THE OUTLINES EXISTED AND NOBODY ASKED FOR THE REPAINT, WHICH IS WHY THEY WERE
1391
+ * INVISIBLE. Measured in the real app before this ticket: with `=F6+G6` open in E6, a screen
1392
+ * scan found the coloured GLYPHS in the editor and nothing at all on F6 or G6; forcing a full
1393
+ * redraw by resizing the window, with no state change of any kind, made both borders appear
1394
+ * (blue 222px wide, red 316px). So `paintRefBorder` was correct all along and glide simply
1395
+ * never redrew the cells it would have painted: a canvas grid repaints DAMAGED cells, and a
1396
+ * new `drawCell` closure alone does not damage the cells whose paint it changes.
1397
+ *
1398
+ * ⛔ THE UNION OF BEFORE AND AFTER, NOT JUST AFTER. A reference that has just been deleted, or
1399
+ * a proposal that has just moved off a cell, has to be repainted to LOSE its border - damaging
1400
+ * only the current set would leave the old outline burnt into the canvas.
1401
+ *
1402
+ * ⭐ THE KEY CARRIES COLOUR AND DASH, not merely the address, so leaving point mode (same
1403
+ * cells, solid instead of dashed) still counts as a change worth a repaint. Same shape as the
1404
+ * shimmer's `pendingBoundKey` above, and a negative view row is the frozen band's own grid for
1405
+ * the same reason.
1406
+ */
1407
+ const refPaintKey = useMemo(() => {
1408
+ const parts: string[] = [];
1409
+ for (const [key, color] of formulaRefCells) {
1410
+ parts.push(`${key}:${color}:${formulaPointCells.has(key) ? "dash" : "solid"}`);
1411
+ }
1412
+ return parts.join("|");
1413
+ }, [formulaPointCells, formulaRefCells]);
1414
+ const paintedRefCells = useRef<string[]>([]);
1415
+ useEffect(() => {
1416
+ const now = refPaintKey ? refPaintKey.split("|").map((p) => p.slice(0, p.indexOf(":"))) : [];
1417
+ const union = new Set([...paintedRefCells.current, ...now]);
1418
+ paintedRefCells.current = now;
1419
+ if (union.size === 0) return;
1420
+ const main: { cell: Item }[] = [];
1421
+ const band: { cell: Item }[] = [];
1422
+ for (const key of union) {
1423
+ const comma = key.indexOf(",");
1424
+ const col = Number(key.slice(0, comma));
1425
+ const row = Number(key.slice(comma + 1));
1426
+ if (!Number.isFinite(col) || !Number.isFinite(row)) continue;
1427
+ const viewCol = viewIndexOf(visCols, col - 1);
1428
+ const viewRow = viewRowOf(row - 1);
1429
+ if (viewRow < 0) band.push({ cell: [viewCol, viewRow + bandRows] as Item });
1430
+ else main.push({ cell: [viewCol, viewRow] as Item });
1431
+ }
1432
+ if (main.length > 0) gridRef.current?.updateCells(main);
1433
+ if (band.length > 0) bandGridRef.current?.updateCells(band);
1434
+ }, [bandRows, refPaintKey, viewRowOf, visCols]);
1435
+
1436
+ /** The selected rectangle in glide's own VIEW coordinates, or `null` when nothing is selected. */
1437
+ const viewRange = useCallback((): CellRange | null => {
1438
+ const current = selection?.current;
1439
+ if (!current) return null;
1440
+ const r = current.range;
1441
+ return { col0: r.x, row0: r.y, col1: r.x + r.width - 1, row1: r.y + r.height - 1 };
1442
+ }, [selection]);
1443
+
1444
+ /**
1445
+ * ⛔ IT SITS HERE, ABOVE THE COPY AND PASTE DOORS, AND NOT BESIDE `selectedAddrs` WHERE IT USED
1446
+ * TO. `onPaste` now names `viewRange` in its dependency array (W53-T03), and a dependency array
1447
+ * is evaluated DURING the render that declares the callback: a `const` declared further down
1448
+ * the component body is still in its temporal dead zone at that moment, so the page throws on
1449
+ * first paint rather than on paste.
1450
+ */
1451
  /**
1452
  * ⭐⭐ W51-T19 — THE SHEET'S OWN MEMORY OF WHAT WAS COPIED, AND WHY IT HAS TO EXIST.
1453
  *
 
1500
  setPasteHighlight(null);
1501
  });
1502
 
1503
+ /**
1504
+ * WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THIS COMPONENT REMEMBERS ABOUT IT.
1505
+ *
1506
+ * ⭐ IT WRITES WHAT THE CELL READS, not what it stores: `formatCellText` over `displayText`, so
1507
+ * a currency cell arrives in Excel as the currency somebody chose. That is the same string
1508
+ * `displayData` carries, which is what makes glide's own Ctrl+C agree with the ribbon's button
1509
+ * — and it is why the two copy doors can share one builder at all.
1510
+ */
1511
+ const heldFor = useCallback((range: CellRange) => {
1512
+ const lines: string[] = [];
1513
+ // ⭐ W51-T19: the CELLS are kept beside the text, so a bound cell pasted back into the sheet
1514
+ // can take its drag rules. See `copiedRef` for why the text alone cannot carry a binding.
1515
+ const block: (Cell | null)[][] = [];
1516
+ for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) {
1517
+ const line: string[] = [];
1518
+ const row: (Cell | null)[] = [];
1519
+ for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
1520
+ c += 1) {
1521
+ const cell = cells[addrAt(c, r)] ?? null;
1522
+ line.push(formatCellText(cell, displayText(cell)));
1523
+ row.push(cell);
1524
+ }
1525
+ lines.push(line.join("\t"));
1526
+ block.push(row);
1527
+ }
1528
+ return {
1529
+ text: lines.join("\n"),
1530
+ col: realCol(Math.min(range.col0, range.col1)),
1531
+ row: realRow(Math.min(range.row0, range.row1)),
1532
+ cells: block,
1533
+ };
1534
+ }, [addrAt, cells, realCol, realRow]);
1535
+
1536
+ /**
1537
+ * ⭐⭐ W53-T03 / INSTRUCTION 24 — THE NATIVE Ctrl+C IS A COPY THIS COMPONENT KNOWS ABOUT NOW.
1538
+ *
1539
+ * ⛔ THE DEFECT IT ENDS: glide answers the browser's own copy through `getCellsForSelection`
1540
+ * and never told this component, so after a native Ctrl+C `copiedRef` still held whatever the
1541
+ * ribbon's button last copied, or nothing at all. Copying one BLANK cell that way then reads
1542
+ * back as an empty clipboard, and the paste was refused with "There is nothing on the clipboard
1543
+ * to paste." rather than blanking the selection.
1544
+ *
1545
+ * ⭐ SO THE FIX IS TO TELL THE TRUTH TO THE EXISTING TEST, NOT TO WEAKEN IT. `isRecognizedCopy`
1546
+ * keeps its exact question — is this text the text WE last copied — and simply stops being
1547
+ * asked about a copy nobody recorded. The two questions the ticket names stay separate: an
1548
+ * unset clipboard is still unset; a copied blank region is now a copy this component made.
1549
+ *
1550
+ * ⚠ CAPTURE PHASE, ON THE WRAP. glide listens on the WINDOW, so a bubbling listener here would
1551
+ * still see the event, but capture removes any dependence on what glide does with it. The
1552
+ * marquee is set from the same rectangle the ribbon's Copy sets it from, so the two doors can
1553
+ * never disagree about what is copied.
1554
+ *
1555
+ * ⚠ A COPY OUT OF A TEXT BOX IS NOT A COPY OF CELLS. An editor overlay inside the wrap copies
1556
+ * characters, and recording that as a block copy would leave the sheet believing it holds a
1557
+ * region somebody never selected.
1558
+ */
1559
+ useEffect(() => {
1560
+ const node = wrapRef.current;
1561
+ if (!node) return undefined;
1562
+ const record = (event: Event) => {
1563
+ const from = event.target;
1564
+ if (from instanceof Element && from.closest("input, textarea, [contenteditable=\"true\"]")) {
1565
+ return;
1566
+ }
1567
+ const range = viewRange();
1568
+ if (!range) return;
1569
+ const held = heldFor(range);
1570
+ copiedRef.current = held;
1571
+ setCopyMarquee({ col: held.col, row: held.row, cols: held.cells[0]?.length ?? 0,
1572
+ rows: held.cells.length });
1573
+ };
1574
+ node.addEventListener("copy", record, true);
1575
+ node.addEventListener("cut", record, true);
1576
+ return () => {
1577
+ node.removeEventListener("copy", record, true);
1578
+ node.removeEventListener("cut", record, true);
1579
+ };
1580
+ }, [heldFor, viewRange]);
1581
+
1582
  /** The drag rules for a paste of `values`, or `undefined` when this block is not ours. */
1583
  const copiedBlock = useCallback(
1584
  (values: readonly (readonly string[])[]): DragContext | undefined => {
 
1639
  ? screenEdits(tab, plain)
1640
  : { edits: plain, refusals: [] as { addr: string; message: string }[] };
1641
  const edits = { ...dragged, ...screened.edits };
1642
+ // ⭐ W53-T01: a fill or a paste can change a cell some OTHER formula reads, so the landing
1643
+ // door recalculates its dependents in the same commit every typed edit does.
1644
+ if (Object.keys(edits).length > 0) commitWithRecalc(edits);
1645
  const said = [
1646
  screened.refusals.length > 0 ? refusalLabel(screened.refusals) : "",
1647
  boundDragLabel(out),
1648
  ].filter(Boolean).join(" ");
1649
  if (said) onNotice(said);
1650
+ }, [commitWithRecalc, onNotice, tab]);
1651
 
1652
  /**
1653
  * ⭐ THE PASTE IS OURS, NOT GLIDE'S, AND IT RETURNS `false` DELIBERATELY. glide has already
 
1671
  // ⚠ THE TARGET IS TRANSLATED, THE BLOCK IS NOT. A paste lands as a rectangle in the SHEET,
1672
  // which is Excel's own behaviour: it fills hidden rows too rather than skipping them and
1673
  // silently landing a person's forty values on the wrong forty cells.
1674
+ // ⭐⭐ W53-T03 — GLIDE HANDS OVER THE ANCHOR, NEVER THE SELECTION, so this door reads the
1675
+ // dragged rectangle itself. That rectangle is what decides how many times the copied block
1676
+ // lands: one copied cell fills a selection of twenty, exactly as Excel does it.
1677
+ const range = viewRange();
1678
  const out = pasteCells(tab, realCol(target[0]), realRow(target[1]), values,
1679
+ { cols: extent.cols, rows: extent.rows }, copiedBlock(values),
1680
+ cellValueGetter,
1681
+ range ? { col0: realCol(range.col0), row0: realRow(range.row0),
1682
+ col1: realCol(range.col1), row1: realRow(range.row1) }
1683
+ : undefined);
1684
+ // ⛔ A SIZE REFUSAL WRITES NOTHING, so it is said and the door closes before anything is
1685
+ // landed or highlighted.
1686
+ if (out.sizeRefusal) {
1687
+ onNotice(out.sizeRefusal);
1688
+ return false;
1689
+ }
1690
  // ⛔⛔ W51-T18 / C2 — A PASTE IS ONE OF THE TWO DOORS THAT CAN LAND A VALUE OUTSIDE A CELL'S
1691
  // LIST, and it is the one that gets forgotten because the dropdown looks like the whole
1692
  // feature. The block is screened against the validation the TARGET already carries, the
 
1698
  cols: values[0]?.length ?? 0, rows: values.length });
1699
  return false;
1700
  },
1701
+ [cellValueGetter, copiedBlock, extent.cols, extent.rows, isRecognizedCopy, landFill, onNotice,
1702
+ realCol, realRow, tab, viewRange],
1703
  );
1704
 
1705
  /**
 
1728
  // the paste door all reach that same arithmetic, which is what makes "a locked period
1729
  // copies verbatim through every door" one fact instead of four that agree today.
1730
  { catalogue: options },
1731
+ // ⭐ W53-T01 / R2: a dragged formula shows its NUMBER when it lands, not its text.
1732
+ cellValueGetter,
1733
  );
1734
  // ⛔ W51-T18 / C2 — AND THE FILL IS THE SECOND DOOR. Dragging a value down a column lands
1735
  // it on every cell it passes, list or no list, so it is screened exactly as the paste is.
1736
  landFill(out, true);
1737
  },
1738
+ [cellValueGetter, landFill, options, realCol, realRow, tab],
1739
  );
1740
 
 
 
 
 
 
 
 
 
1741
  /** Every address the selection covers, translated. `[]` when nothing is selected. */
1742
  const selectedAddrs = useCallback((): string[] => {
1743
  const range = viewRange();
 
1788
  return;
1789
  }
1790
  const out = clearCells(tab, addrs);
1791
+ // ⭐⭐ W53-T01 / INSTRUCTION 11 — THE DELETE KEY IS A VALUE CHANGE, AND IT IS THE COMMONEST
1792
+ // ONE. Clearing F6 has to make `=F6+G6` recompute; leaving this on the plain commit would
1793
+ // leave the old sum on screen, which is the same defect the ticket names reached by a
1794
+ // different door.
1795
+ if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits);
1796
+ }, [commitWithRecalc, onNotice, selectedAddrs, tab]);
1797
 
1798
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1799
  // ⭐⭐ W51-T17 — WHAT A SHORTCUT AND A HEADER CLICK BOTH NEED: ONE WAY TO SET THE SELECTION.
 
1935
  // ⭐ R5 (W52-T09): `shiftCells` no longer declines the whole act over a bound cell in range -
1936
  // it drops out with everything else the shift moves.
1937
  const out = shiftCells(tab, real, insert, { rows: extent.rows });
1938
+ // ⭐ W53-T01: a shift moves VALUES under the formulas that read those addresses, so the
1939
+ // dependents recompute in the same commit rather than at the next Refresh.
1940
+ if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits);
1941
  onNotice(cellShiftLabel(insert, out.dropped));
1942
+ }, [commitWithRecalc, extent.rows, onNotice, onStructure, realCol, realRow, tab, viewRange,
1943
  visCols.length, visRows.length]);
1944
 
1945
  /**
 
2008
  * ⛔ THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED. A browser that refuses clipboard access on a
2009
  * cut would otherwise delete a person's cells with nothing on the clipboard to paste back.
2010
  *
2011
+ * ⭐ WHAT IT PUTS ON THE CLIPBOARD IS {@link heldFor}'s, which glide's own Ctrl+C now records
2012
+ * through the same builder.
 
2013
  */
2014
  const copySelection = useCallback((cut: boolean) => {
2015
  const range = viewRange();
 
2017
  onNotice(cut ? "Select a cell first, then cut it." : "Select a cell first, then copy it.");
2018
  return;
2019
  }
2020
+ // ⭐ W53-T03: the block and its text are built by `heldFor`, the ONE builder both copy doors
2021
+ // share, so a native Ctrl+C and this button can never record different things about the same
2022
+ // selection.
2023
+ const held = heldFor(range);
2024
+ const block = held.cells;
2025
+ const text = held.text;
 
 
 
 
 
 
 
 
 
 
 
2026
  // ⛔ RECORDED ONLY ON A SUCCESSFUL WRITE, so the sheet never believes it holds a block the
2027
  // clipboard does not. It is a SEPARATE `then` so that the clear stays the one line a
2028
  // W51-T17 gate leg pins: a cut clears the source only after the copy landed, and folding
2029
  // the two together would have moved that leg's anchor for no reason at all.
 
 
 
 
 
 
2030
  navigator.clipboard.writeText(text)
2031
  .then(() => {
2032
  copiedRef.current = held;
 
2038
  .then(() => { if (cut) clearSelection(); })
2039
  .catch(() => onNotice("This browser did not let the sheet write to the clipboard. "
2040
  + "Press Ctrl+C instead."));
2041
+ }, [clearSelection, heldFor, onNotice, viewRange]);
2042
 
2043
  /**
2044
  * PASTE. glide already handles Ctrl+V through `onPaste`; this is the ribbon's own door, which
 
2060
  }
2061
  const values = text.replace(/\r\n/g, "\n").replace(/\n+$/, "")
2062
  .split("\n").map((line) => line.split("\t"));
2063
+ // ⭐⭐ W53-T03: this door always had the dragged rectangle in hand; now it hands it on, so
2064
+ // the ribbon's Paste tiles a copied block across the selection exactly as Ctrl+V does.
2065
  const out = pasteCells(tab, realCol(range.col0), realRow(range.row0), values,
2066
+ { cols: extent.cols, rows: extent.rows }, copiedBlock(values),
2067
+ cellValueGetter,
2068
+ { col0: realCol(range.col0), row0: realRow(range.row0),
2069
+ col1: realCol(range.col1), row1: realRow(range.row1) });
2070
+ if (out.sizeRefusal) {
2071
+ onNotice(out.sizeRefusal);
2072
+ return;
2073
+ }
2074
  landFill(out, false);
2075
  // ⭐ W52-T07: same highlight the glide door sets, from the ribbon's own paste path.
2076
  setPasteHighlight({ col: realCol(range.col0), row: realRow(range.row0),
2077
  cols: values[0]?.length ?? 0, rows: values.length });
2078
  }).catch(() => onNotice("This browser did not let the sheet read the clipboard. "
2079
  + "Press Ctrl+V instead."));
2080
+ }, [cellValueGetter, copiedBlock, extent.cols, extent.rows, isRecognizedCopy, landFill,
2081
+ onNotice, realCol, realRow, tab, viewRange]);
2082
 
2083
  /**
2084
  * THE FORMAT PAINTER, WHICH IS TWO GESTURES AND NOT ONE. Pressing it picks the anchor cell's
 
2130
  const cell = cellAt(tab, addr);
2131
  // ⭐ R5 (W52-T09): AutoSum on a bound cell writes over it exactly like any other cell -
2132
  // `setFormula` already drops a binding on its own.
2133
+ commitWithRecalc({ [addr]: setFormula(cell, formula, cellValueGetter) });
2134
+ }, [cellValueGetter, commitWithRecalc, onNotice, realCol, realRow, selection, tab]);
2135
 
2136
  /** Fill down and fill right, through the same door the fill HANDLE uses. */
2137
  const fillSelection = useCallback((axis: "down" | "right") => {
 
2168
  return;
2169
  }
2170
  const out = which === "formats" ? clearFormats(tab, addrs) : clearAll(tab, addrs);
2171
+ // ⚠ ONLY THE `all` BRANCH RECALCULATES, AND THE ASYMMETRY IS THE POINT. Clear all removes
2172
+ // VALUES, so a formula reading one of them has to follow; clear formats removes only a bold
2173
+ // and an alignment, and recomputing the sheet for that would be noise with a history step.
2174
+ if (Object.keys(out.edits).length === 0) return;
2175
+ if (which === "formats") onCommit(out.edits);
2176
+ else commitWithRecalc(out.edits);
2177
+ }, [commitWithRecalc, onCommit, onNotice, selectedAddrs, tab]);
2178
 
2179
  /** Hide the rows or the columns the selection covers, and remember them on the tab. */
2180
  const hideBand = useCallback((axis: "row" | "col") => {
 
2331
  }
2332
  const cell = cellAt(tab, dropdown.addr);
2333
  const next = commitTyped(cell, canonicalEntry(list, text));
2334
+ // ⭐ W53-T01: choosing from the list WRITES A VALUE, so a formula reading this cell follows
2335
+ // it exactly as it follows a typed one.
2336
+ commitWithRecalc({
2337
  // ⚠ THE LIST SURVIVES THE CHOICE. `commitTyped` builds a fresh literal, so handing back its
2338
  // result unchanged would delete the very validation that produced the value.
2339
  [dropdown.addr]: next ? { ...next, validation: { list: [...list] } }
2340
  : { kind: "empty", state: "fresh", validation: { list: [...list] } },
2341
  });
2342
  setDropdown(null);
2343
+ }, [commitWithRecalc, dropdown, onNotice, tab]);
2344
 
2345
  // ═══════════════════════════════════════════════════════════════════════════════════════════
2346
  // ⭐⭐ W51-T15 DECLARED THE VOCABULARY, W51-T16 ANSWERS EVERY WORD OF IT.
 
2572
  // bound cell by a different rule from the one beside it, which is exactly the split
2573
  // "one primitive, every door" exists to prevent.
2574
  { catalogue: options },
2575
+ cellValueGetter,
2576
  );
2577
  if (Object.keys(out.edits).length === 0) {
2578
  onNotice("Select the cell to copy and the cells to fill, then press Ctrl+Enter.");
 
2586
  // ⭐ R5 (W52-T09): a bound cell is no longer walled off here - `appendLineBreak`
2587
  // writes through `commitTyped`, which drops its binding on its own.
2588
  const out = appendLineBreak(tab, addrAt(cur.cell[0], cur.cell[1]));
2589
+ if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits);
2590
  return;
2591
  }
2592
  case "today": {
 
2594
  const addr = addrAt(cur.cell[0], cur.cell[1]);
2595
  const cell = cellAt(tab, addr);
2596
  // ⭐ R5 (W52-T09): Ctrl+; on a bound cell writes over it exactly like any other cell.
2597
+ commitWithRecalc({ [addr]: commitTyped(cell, dateStamp(new Date()), cellValueGetter) });
2598
  return;
2599
  }
2600
 
 
2637
  }
2638
  const next = cycleAnchors(cell.formula ?? "");
2639
  if (!next || next === cell.formula) return;
2640
+ commitWithRecalc({ [addr]: setFormula(cell, next, cellValueGetter) });
2641
  return;
2642
  }
2643
  case "find": setFind((was) => was ?? { query: "", at: -1 }); return;
 
2649
  }
2650
  }
2651
  },
2652
+ [addrAt, anchorStyle, applySelection, applyStyle, bandRows, cellValueGetter, commitWithRecalc,
2653
+ extent.cols, extent.rows,
2654
  onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor,
2655
  openNumberFormat, realCol, realRow, selection, structureForSelection, switchTab, tab,
2656
  viewRange, viewRowOf, visCols, visRows],
 
2823
  // `!cell` early return, for the same reason `ruleStyle` is (W51-T18's own note two lines up):
2824
  // a formula can reference a perfectly BLANK cell, and that cell still has to wear the border,
2825
  // not be treated as nothing to paint.
2826
+ //
2827
+ // ⭐⭐ W53-T02 / INSTRUCTION 18 — ONE BORDER, TWO WEIGHTS OF CERTAINTY. A settled reference
2828
+ // keeps Microsoft's own "border with square corners" (solid), whether the formula is being
2829
+ // edited or merely selected; the cell the arrow keys are still moving over is DASHED in that
2830
+ // same reference's slot colour, which is the state instruction 18 describes. The colour is
2831
+ // what tells it apart from the copy marquee's own dash further down.
2832
+ const refKey = `${realCol(col) + 1},${realRow(row) + 1}`;
2833
+ const refColor = formulaRefCells.get(refKey);
2834
+ const refProposed = formulaPointCells.has(refKey);
2835
  const paintRefBorder = () => {
2836
  if (!refColor) return;
2837
  ctx.save();
2838
  ctx.strokeStyle = refColor;
2839
  ctx.lineWidth = 2;
2840
+ if (refProposed) ctx.setLineDash([4, 3]);
2841
  ctx.strokeRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
2842
+ ctx.setLineDash([]);
2843
  ctx.restore();
2844
  };
2845
 
 
2881
  ctx.restore();
2882
  }
2883
  };
2884
+ /**
2885
+ * ⭐⭐ W53-T01 / R2 / INSTRUCTION 19 — THE ONE CELL THAT IS STILL WAITING SAYS SO ITSELF.
2886
+ * A soft band crosses a database-bound cell that has not resolved yet, and nothing else on
2887
+ * the sheet moves: the formulas next to it already have their numbers.
2888
+ *
2889
+ * ⛔ SLICES RATHER THAN A CANVAS GRADIENT, and that is a colour rule and not a graphics
2890
+ * preference. A gradient stop needs a colour WITH an alpha channel, which would mean writing
2891
+ * an `rgba()` literal here; every colour in this file comes from a `--lp-*` token through
2892
+ * `tokenColour` (DESIGN.md), so the softness is made with `globalAlpha` instead.
2893
+ */
2894
+ const paintShimmer = () => {
2895
+ if (!cell || cell.kind !== "bound" || cell.state !== "stale") return;
2896
+ const bandWidth = Math.max(24, rect.width * 0.5);
2897
+ const head = rect.x - bandWidth + (rect.width + bandWidth) * shimmerPhase.current;
2898
+ const slices = 8;
2899
+ const slice = bandWidth / slices;
2900
+ ctx.save();
2901
+ ctx.beginPath();
2902
+ ctx.rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
2903
+ ctx.clip();
2904
+ ctx.fillStyle = tokenColour("--lp-blue-tint", "#edf3fd");
2905
+ for (let i = 0; i < slices; i += 1) {
2906
+ ctx.globalAlpha = 0.55 * Math.sin((Math.PI * (i + 0.5)) / slices);
2907
+ ctx.fillRect(head + slice * i, rect.y + 1, slice + 1, rect.height - 2);
2908
+ }
2909
+ ctx.globalAlpha = 1;
2910
+ ctx.restore();
2911
+ };
2912
  if (!cell && !ruleStyle) { drawContent(); paintRefBorder(); paintMarquee(); return; }
2913
 
2914
  const mark = cell ? MARK_STYLE[markOf(cell)] : undefined;
 
2962
  // ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so
2963
  // the mark sits on top of the value rather than under it.
2964
  drawContent();
2965
+ paintShimmer();
2966
  paintMark();
2967
  paintRefBorder();
2968
  paintMarquee();
 
3066
  ctx.restore();
3067
  }
3068
 
3069
+ paintShimmer();
3070
  paintMark();
3071
  paintRefBorder();
3072
  paintMarquee();
 
3076
  // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's
3077
  // territory for a line that was never wrong, only no longer load bearing.
3078
  return true;
3079
+ }, [addrAt, cells, copyMarquee, formulaPointCells, formulaRefCells, pasteHighlight, realCol,
3080
+ realRow, rules]);
3081
 
3082
  /**
3083
  * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not
web/src/sheet/SheetPage.tsx CHANGED
@@ -259,14 +259,24 @@ export default function SheetPage() {
259
  const [tabId, setTabId] = useState<string>("");
260
  const [busy, setBusy] = useState(false);
261
  const [notice, setNotice] = useState("");
 
 
262
  /**
263
- * ⭐ W51-T11 — A SECOND LINE, AND IT IS NOT `notice` REUSED. `notice` is a sentence about a
264
- * REFUSAL: an edit that did not land, a sheet that reloaded under you. This one is about the
265
- * MACHINE: which save model is in use, and how long the last recalculation took. Folding them
266
- * together means "Recalculated in 0.4 s" silently overwrites "that edit was not saved", which
267
- * is the one sentence in this page that must not be lost.
 
 
 
 
 
 
 
 
 
268
  */
269
- const [status, setStatus] = useState("");
270
  /**
271
  * ⛔ THE THIRD STATE (W50-T17). See the header: `book === null` cannot distinguish "opening"
272
  * from "could not open", and a spinner shown for the second one never stops.
@@ -507,7 +517,13 @@ export default function SheetPage() {
507
  // ⭐⭐ W51-T11 / R4 — OPENING IS `?tabs=meta` AND THEN THE ACTIVE TAB, in that order and
508
  // never the whole document. A workbook at R4's cap is 100,000 cells a tab; fetching every
509
  // tab to show one is the load this split exists to stop paying.
510
- const opened = first ? await readTabMeta(first.id) : await createWorkbook("Workbook");
 
 
 
 
 
 
511
  if (!live) return;
512
  if (!opened.ok) {
513
  setNotice(opened.message);
@@ -562,7 +578,6 @@ export default function SheetPage() {
562
  if (!book) return;
563
  setBusy(true);
564
  setNotice("");
565
- setStatus("");
566
  const got = await refreshWorkbook(book.id);
567
  setBusy(false);
568
  if (!got.ok) {
@@ -578,12 +593,13 @@ export default function SheetPage() {
578
  dirtyRef.current = new Map();
579
  markAllLoaded(got.value.workbook);
580
  applyLocal(got.value.workbook);
581
- // ⭐ R4: *"recalc runs only on Refresh or a formula commit and its time is shown."* Shown to
582
- // ONE decimal, in seconds, and only when the server actually measured it: rendering a 0.0 for
583
- // a server that sent no number would be an unverifiable aggregate on a screen.
584
- if (got.value.recalcMs !== null) {
585
- setStatus(`Recalculated in ${(got.value.recalcMs / 1000).toFixed(1)} s`);
586
- }
 
587
  }, [applyLocal, book, markAllLoaded]);
588
 
589
  // The action bar's Edit button opens the binding panel below, for any cell - R5 (W52-T09)
@@ -700,7 +716,8 @@ export default function SheetPage() {
700
  // not `>= 400 && !== 403`: that swept in every transient failure too, and latched on
701
  // the first one for the rest of the session.
702
  patchModeRef.current = "put";
703
- setStatus("Saving the whole workbook");
 
704
  return "route_absent";
705
  }
706
  for (const addr of Array.from(addrs)) markDirty(tabKey, addr);
@@ -861,18 +878,22 @@ export default function SheetPage() {
861
  }, [queueSave, flushSave]);
862
 
863
  /**
864
- * ⭐ W51-T08 / C1 — THE IMPORT DOOR, DECLARED WHERE IT WILL LIVE AND INERT UNTIL W51-T13.
 
865
  *
866
- * ⛔ IT IS A REAL FUNCTION AND NOT `undefined` ON PURPOSE. C1 asks the seam to be passed now so
867
- * the wiring is one edit at T13 rather than a prop that has to be threaded through E's component
868
- * afterwards; a prop pinned as `undefined` would prove nothing. It opens nothing today, which is
869
- * the honest state: there is no dialog to open, and inventing a message about a feature nobody
870
- * can see would be copy that outlives its own reason.
 
 
 
 
 
 
871
  */
872
- const onOpenImport = useCallback(() => {
873
- // W51-T13 mounts the import dialog on this handler. Deliberately inert until then.
874
- return;
875
- }, []);
876
 
877
  /**
878
  * ⭐ THE ONE COMMIT DOOR. Every edit the grid can make arrives here: a typed cell, a paste, a
@@ -1490,6 +1511,7 @@ export default function SheetPage() {
1490
  // that has nothing to do with what it guards. R2's one view kind is a property of the PAGE.
1491
  <div className="sheet-page" data-view-kind={SHEET_VIEW_KIND}>
1492
  <SheetRail
 
1493
  loading={loading}
1494
  rows={index.workbooks}
1495
  folders={index.folders}
@@ -1562,17 +1584,9 @@ export default function SheetPage() {
1562
  take the only place a save conflict or a failed refresh is ever said out loud. */}
1563
  {notice && <p className="sheet-notice">{notice}</p>}
1564
 
1565
- {/* ⭐ W51-T11 — THE MACHINE'S OWN LINE, beside the refusal line and never instead of it.
1566
- It carries two sentences and only ever one at a time: "Saving the whole workbook",
1567
- which is what the client says when contract C3's cell PATCH is not served and it has
1568
- fallen back to writing the whole document, and "Recalculated in N.N s" after a
1569
- Refresh that reported its own time (R4). Both are states of the machine rather than
1570
- refusals, which is why neither may take `.sheet-notice`'s slot away from a sentence
1571
- saying an edit did not land.
1572
- ⚠ IT WEARS `.sheet-notice` BECAUSE THAT CLASS IS STYLED AND BOTH SHEET STYLESHEETS
1573
- ARE OUTSIDE THIS TICKET'S FENCE. `.sheet-status` is carried alongside it as the hook
1574
- a later ticket can style without hunting for the element. */}
1575
- {status && <p className="sheet-notice sheet-status">{status}</p>}
1576
 
1577
  {/* ⭐ THREE OUTCOMES, IN THE ORDER THEY CAN HAPPEN. A workbook is switching, so the
1578
  spinner again; a workbook is open, so the grid; nothing opened and `loading` is over,
 
259
  const [tabId, setTabId] = useState<string>("");
260
  const [busy, setBusy] = useState(false);
261
  const [notice, setNotice] = useState("");
262
+ /** W53-T09: bumped by the ribbon's Import button; `SheetRail` opens its dialog on a change. */
263
+ const [importRequest, setImportRequest] = useState(0);
264
  /**
265
+ * ⭐⭐ W53-T08 (owner instructions 14 and 19, ruling R2) — THE MACHINE'S OWN STATUS LINE IS GONE,
266
+ * STATE AND ALL. Owner: *"Remove the whole strip under Home in the sheet module where
267
+ * notifications like 'Recalculated in 0.0 s' appear."* W51-T11's reasoning for keeping it apart
268
+ * from `notice` was correct and is not what changed; what changed is that R2 makes a formula
269
+ * resolve client-side the instant it is committed, so a whole-workbook recalculation is no
270
+ * longer something a person waits on and is told about afterwards. Excel agrees and it is worth
271
+ * recording why: its status bar shows "Calculating (n%)" only WHILE a long recalculation runs,
272
+ * and it shows no completion notice of any kind
273
+ * (`.claude/wiki/research/excel-formula-ux.md` section 5).
274
+ * ⛔ NOTHING REPLACES IT HERE. Per R2 the per-cell shimmer on a database-bound cell is what
275
+ * reports work in progress, and that lives on the cell rather than in a page-level strip.
276
+ * ⚠ `notice` DIRECTLY BELOW IS A DIFFERENT LINE AND IT STAYS. It carries refusals - an edit
277
+ * that did not land, a sheet that reloaded underneath you - and deleting it would take away the
278
+ * only place a save conflict is ever said out loud.
279
  */
 
280
  /**
281
  * ⛔ THE THIRD STATE (W50-T17). See the header: `book === null` cannot distinguish "opening"
282
  * from "could not open", and a spinner shown for the second one never stops.
 
517
  // ⭐⭐ W51-T11 / R4 — OPENING IS `?tabs=meta` AND THEN THE ACTIVE TAB, in that order and
518
  // never the whole document. A workbook at R4's cap is 100,000 cells a tab; fetching every
519
  // tab to show one is the load this split exists to stop paying.
520
+ // W53-T10 (owner instruction 1): the workbook this page mints when a workspace has none
521
+ // is the Sheet's counterpart to the Data module's undeletable "Default view"
522
+ // (`customer-grid/types.ts::DEFAULT_VIEW_NAME`), so it carries the matching name.
523
+ // ⚠ NOT the "Untitled workbook" the Create-new door mints below: that one is the
524
+ // counterpart of a user-created view and its wording is unchanged.
525
+ const opened = first ? await readTabMeta(first.id)
526
+ : await createWorkbook("Default workbook");
527
  if (!live) return;
528
  if (!opened.ok) {
529
  setNotice(opened.message);
 
578
  if (!book) return;
579
  setBusy(true);
580
  setNotice("");
 
581
  const got = await refreshWorkbook(book.id);
582
  setBusy(false);
583
  if (!got.ok) {
 
593
  dirtyRef.current = new Map();
594
  markAllLoaded(got.value.workbook);
595
  applyLocal(got.value.workbook);
596
+ // ⭐⭐ W53-T08 (instruction 14, ruling R2) — THE RECALC TIME IS NO LONGER ANNOUNCED. Wave 49's
597
+ // R4 asked for it to be shown; instruction 14 retires that, and R2 is why it stops being
598
+ // useful information: a formula now resolves as it is committed, so the number this reported
599
+ // was the cost of a whole-workbook round trip that the commit path no longer makes.
600
+ // ⚠ `got.value.recalcMs` is still READ from the response and simply not painted; the server
601
+ // half is untouched, and lane C keeps `POST /sheets/{id}/refresh` for the load and import
602
+ // paths.
603
  }, [applyLocal, book, markAllLoaded]);
604
 
605
  // The action bar's Edit button opens the binding panel below, for any cell - R5 (W52-T09)
 
716
  // not `>= 400 && !== 403`: that swept in every transient failure too, and latched on
717
  // the first one for the rest of the session.
718
  patchModeRef.current = "put";
719
+ // W53-T08: the fallback is silent now. It was never a refusal - the save DOES land -
720
+ // and the strip that carried it is gone; `notice` is reserved for edits that did not.
721
  return "route_absent";
722
  }
723
  for (const addr of Array.from(addrs)) markDirty(tabKey, addr);
 
878
  }, [queueSave, flushSave]);
879
 
880
  /**
881
+ * ⭐⭐ W53-T09 (owner instruction 20) — THE IMPORT DOOR IS LIVE. THIS IS THE ONE EDIT W51-T13
882
+ * WAS SUPPOSED TO MAKE AND NEVER DID.
883
  *
884
+ * The owner reported that the ribbon's Import button does nothing, and the code looked wired,
885
+ * which is exactly why two reads missed it: `Ribbon.tsx`'s `case "import"` calls
886
+ * `onOpenImport?.()`, `SheetGrid.tsx` forwards it, and the chain arrived HERE at a function
887
+ * whose whole body was `return;` under the comment *"Deliberately inert until then."* The seam
888
+ * was honest when it was written; W51-T13 never landed, so a placeholder shipped as a dead
889
+ * control. ⚠ THIS IS THE SHAPE TO WATCH FOR: a deliberately inert handler is indistinguishable
890
+ * from a working one at every layer above it, and no gate can tell them apart.
891
+ * ⛔ NO SECOND DIALOG. `SheetRail.tsx` already owns `ImportDialog` for its own "Import .xlsx"
892
+ * menu item, so this bumps a counter the rail watches: one dialog, two doors. A counter rather
893
+ * than a boolean because a boolean would have to be reset from here when the dialog closed,
894
+ * which is the two-way coupling the rail's own note explains.
895
  */
896
+ const onOpenImport = useCallback(() => setImportRequest((n) => n + 1), []);
 
 
 
897
 
898
  /**
899
  * ⭐ THE ONE COMMIT DOOR. Every edit the grid can make arrives here: a typed cell, a paste, a
 
1511
  // that has nothing to do with what it guards. R2's one view kind is a property of the PAGE.
1512
  <div className="sheet-page" data-view-kind={SHEET_VIEW_KIND}>
1513
  <SheetRail
1514
+ importRequest={importRequest}
1515
  loading={loading}
1516
  rows={index.workbooks}
1517
  folders={index.folders}
 
1584
  take the only place a save conflict or a failed refresh is ever said out loud. */}
1585
  {notice && <p className="sheet-notice">{notice}</p>}
1586
 
1587
+ {/* ⭐⭐ W53-T08 — THE `.sheet-status` LINE THAT SAT HERE IS DELETED (instruction 14). Its
1588
+ hook class went with it; `.sheet-notice` directly above is a DIFFERENT element and
1589
+ survives deliberately. */}
 
 
 
 
 
 
 
 
1590
 
1591
  {/* ⭐ THREE OUTCOMES, IN THE ORDER THEY CAN HAPPEN. A workbook is switching, so the
1592
  spinner again; a workbook is open, so the grid; nothing opened and `loading` is over,
web/src/sheet/SheetRail.tsx CHANGED
@@ -35,9 +35,13 @@
35
  // indents a NESTED row, and a path-replacing level has no nested rows to indent.
36
  // ---------------------------------------------------------------------------
37
 
38
- import { useMemo, useState } from "react";
39
  import type { DragEvent as ReactDragEvent } from "react";
40
  import "../styles/wave52/parity.css";
 
 
 
 
41
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
42
  import { FolderMark, MenuLabel } from "../customer-grid/icons";
43
  import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
@@ -55,6 +59,12 @@ export interface RailStrata {
55
  }
56
 
57
  export interface SheetRailProps {
 
 
 
 
 
 
58
  loading: boolean;
59
  rows: readonly WorkbookRow[];
60
  /**
@@ -244,6 +254,7 @@ const newFolderId = () =>
244
  const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, 80);
245
 
246
  export default function SheetRail({
 
247
  loading,
248
  rows,
249
  sharedWithMe = [],
@@ -315,6 +326,25 @@ export default function SheetRail({
315
  */
316
  const [importing, setImporting] = useState(false);
317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  const byId = useMemo(() => {
319
  const map: Record<string, SheetFolder> = {};
320
  folders.forEach((f) => { map[f.id] = f; });
 
35
  // indents a NESTED row, and a path-replacing level has no nested rows to indent.
36
  // ---------------------------------------------------------------------------
37
 
38
+ import { useEffect, useMemo, useState } from "react";
39
  import type { DragEvent as ReactDragEvent } from "react";
40
  import "../styles/wave52/parity.css";
41
+ // W53-T04 (instr 15). Loaded AFTER wave52's parity patch and at a higher specificity, so the
42
+ // path row's seating is decided by weight rather than by emission order. See the file's header
43
+ // for the two measured row heights that make the extra pixel necessary.
44
+ import "../styles/wave53/sheet-rail.css";
45
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
46
  import { FolderMark, MenuLabel } from "../customer-grid/icons";
47
  import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
 
59
  }
60
 
61
  export interface SheetRailProps {
62
+ /**
63
+ * W53-T09: a monotonic counter the page bumps when the RIBBON's Import button is pressed. Any
64
+ * change opens the import dialog this rail already owns. Optional, so every existing mount and
65
+ * every test that renders this rail without the page compiles unchanged.
66
+ */
67
+ importRequest?: number;
68
  loading: boolean;
69
  rows: readonly WorkbookRow[];
70
  /**
 
254
  const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, 80);
255
 
256
  export default function SheetRail({
257
+ importRequest,
258
  loading,
259
  rows,
260
  sharedWithMe = [],
 
326
  */
327
  const [importing, setImporting] = useState(false);
328
 
329
+ /**
330
+ * ⭐⭐ W53-T09 (owner instruction 20) — THE RIBBON'S IMPORT BUTTON IS THE SECOND DOOR ONTO THIS
331
+ * SAME DIALOG, AND UNTIL NOW IT OPENED NOTHING. The owner reported "the import button doesn't do
332
+ * anything" and the ribbon looked correctly wired, which is why it survived a code read: the
333
+ * chain `Ribbon.tsx case "import"` -> `onOpenImport?.()` -> `SheetGrid.tsx` -> `SheetPage.tsx`
334
+ * is intact end to end, and the LAST link was a function whose entire body was `return;`,
335
+ * carrying the comment *"W51-T13 mounts the import dialog on this handler. Deliberately inert
336
+ * until then."* W51-T13 never landed, so a deliberate placeholder shipped as a dead button.
337
+ * ⛔ THE DIALOG IS NOT MOVED, and that is the point: one dialog, two doors. `importing` above
338
+ * stays this rail's own state because the rail's "Import .xlsx" menu item is the other door,
339
+ * and the counter below only ever REQUESTS an open, so the two cannot fight over who owns it.
340
+ * ⚠ A COUNTER, NOT A BOOLEAN. A boolean prop would latch: the page would have to be told when
341
+ * the dialog closed in order to reset it, which is exactly the two-way coupling this shape
342
+ * avoids. Every increment is one fresh request to open.
343
+ */
344
+ useEffect(() => {
345
+ if (importRequest) setImporting(true);
346
+ }, [importRequest]);
347
+
348
  const byId = useMemo(() => {
349
  const map: Record<string, SheetFolder> = {};
350
  folders.forEach((f) => { map[f.id] = f; });
web/src/sheet/formulaEval.ts ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/formulaEval.ts — the CLIENT half of contract C1's calc split (wave 53, W53-T01).
2
+ //
3
+ // ⭐⭐ RULING R2: a formula that references only OTHER CELLS evaluates HERE, the instant it is
4
+ // committed, and never touches the network. `evaluateFormula` is the whole of that: a small,
5
+ // self-contained engine over numeric literals, A1 cell references (with Excel's `$` tolerated),
6
+ // the four operators, parentheses, and C1's five aggregate functions (SUM/COUNT/AVG/MIN/MAX) run
7
+ // over one simple range. It is NOT a reimplementation of the server's full grammar
8
+ // (`api/formula_runtime.py::evaluate_sheet`) — no cross-sheet references, no function catalogue
9
+ // beyond the five aggregates.
10
+ //
11
+ // ⛔⛔ AND WHAT IT CANNOT ANSWER IS `unsupported`, NEVER AN ERROR. That distinction is the whole
12
+ // safety of shipping a second, smaller engine beside the server's: `=Sheet1!B4+1` and `=IF(...)`
13
+ // are perfectly good formulas this file simply does not speak, so they fall back to EXACTLY the
14
+ // behaviour that existed before this ticket — the cell stays `stale`, keeps its last computed
15
+ // value, and the server's Refresh resolves it. Returning an error for those would turn a working
16
+ // formula into a refusal, which is a far worse regression than the round trip R2 removes.
17
+ //
18
+ // ⛔⛔ THIS FILE IMPORTS NOTHING FROM THE PROJECT, ON PURPOSE. It is compiled and driven standalone
19
+ // by `verify_formula_engine.py`, the same convention `a1.ts` already uses. A bare module with no
20
+ // project imports can never be the reason an unrelated compile's emitted root moves
21
+ // ([[tsc-outdir-root-moves-with-the-import-graph]], the lesson `sheetState.ts`'s own header
22
+ // carries). `sheetState.ts::cellToValue` is the ONE place a `Cell` — a type this file has never
23
+ // heard of — becomes the `CellValue` this file's `get` callback returns.
24
+
25
+ /**
26
+ * What one referenced cell answers with, and what `evaluateFormula` returns.
27
+ *
28
+ * ⭐⭐ `pending` COVERS TWO DIFFERENT FACTS, AND BOTH ARE CARRIED. A referenced cell with NO value
29
+ * at all yet (a bound cell never resolved) is `{ kind: "pending" }` — there is nothing to compute
30
+ * with, and it is treated as zero for arithmetic so a formula never blocks. A referenced cell that
31
+ * DOES have a last known value, but is itself waiting on a fresh server read, is a `number` or
32
+ * `text` value with `pending: true` riding along: the value is used for arithmetic immediately,
33
+ * and the flag rides up through every operation so the FORMULA's own result can say "this used a
34
+ * value that is not fresh" and recompute once the input resolves.
35
+ *
36
+ * ⚠ `unsupported` IS PRODUCED BY THIS FILE AND NEVER BY A GETTER. It means "the server owns this
37
+ * one", not "this is wrong"; see the header.
38
+ */
39
+ export type CellValue =
40
+ | { kind: "number"; value: number; pending?: boolean }
41
+ | { kind: "text"; value: string; pending?: boolean }
42
+ | { kind: "empty" }
43
+ | { kind: "pending" }
44
+ | { kind: "unsupported"; reason: string }
45
+ | { kind: "error"; message: string };
46
+
47
+ /**
48
+ * ⛔ C1's parity list, spelled in the evaluator's own (Excel-flavoured) names.
49
+ * `verify_formula_engine.py` lowercases both this and `platform/modules/sheet.py::AGGREGATE_FNS`
50
+ * and asserts one set: SUM<->sum, COUNT<->count, AVG<->avg, MIN<->min, MAX<->max. Renaming one
51
+ * side without the other reds that gate on purpose.
52
+ */
53
+ export const AGGREGATE_FUNCTIONS = ["SUM", "COUNT", "AVG", "MIN", "MAX"] as const;
54
+ export type AggregateFunction = (typeof AGGREGATE_FUNCTIONS)[number];
55
+
56
+ const AGGREGATE_SET: ReadonlySet<string> = new Set<string>(AGGREGATE_FUNCTIONS);
57
+
58
+ /**
59
+ * ⭐⭐ THE ONE SENTENCE A CYCLE STATES, DECLARED HERE SO ONE FILE OWNS IT. `sheetState.ts`
60
+ * imports this rather than spelling it, because a refusal message a reader sees in a cell and a
61
+ * gate asserts by text must have exactly one source. Sentence case, and no dash of either width
62
+ * (standing rule 2): every `FormulaError` message in this file reaches a cell.
63
+ */
64
+ export const CYCLE_REFUSAL = "This formula refers back to itself.";
65
+
66
+ /** A stated wrong: the reader sees this sentence in the cell instead of a number. */
67
+ class FormulaError extends Error {}
68
+ /** Not wrong, just not ours: the cell keeps its old behaviour and the server answers it. */
69
+ class Unsupported extends Error {}
70
+ /** An input has no value yet, so there is no honest number to state at all. */
71
+ class PendingInput extends Error {}
72
+
73
+ const CELL_REF = /^[A-Za-z]{1,3}[0-9]{1,7}$/;
74
+
75
+ // ── tokenizer ────────────────────────────────────────────────────────────────────────────────
76
+
77
+ type Token =
78
+ | { t: "num"; v: number }
79
+ | { t: "ref"; v: string }
80
+ | { t: "fn"; v: string }
81
+ | { t: "op"; v: "+" | "-" | "*" | "/" | "(" | ")" | ":" };
82
+
83
+ const OPS = "+-*/():";
84
+
85
+ /**
86
+ * ⚠ A LETTER RUN IS A CELL REFERENCE ONLY WHEN DIGITS FOLLOW IT WITH NO GAP. `SUM` ahead of `(`
87
+ * is a function name; `A1` is a reference. There is no ambiguity to resolve, because a bare
88
+ * function name never carries digits, so the two never compete for the same token.
89
+ *
90
+ * ⚠ AND A `$` IS SWALLOWED RATHER THAN REFUSED. `=$F$6+G6` is the same arithmetic as `=F6+G6`:
91
+ * anchoring is a FILL rule (`a1.ts` owns it), and it has no meaning at all to an evaluator.
92
+ */
93
+ const tokenize = (src: string): Token[] => {
94
+ const text = String(src ?? "").trimStart().replace(/^=/, "");
95
+ const tokens: Token[] = [];
96
+ let i = 0;
97
+ while (i < text.length) {
98
+ const ch = text[i];
99
+ if (/\s/.test(ch)) { i += 1; continue; }
100
+ if (OPS.includes(ch)) {
101
+ tokens.push({ t: "op", v: ch as "+" | "-" | "*" | "/" | "(" | ")" | ":" });
102
+ i += 1;
103
+ continue;
104
+ }
105
+ if (/[0-9.]/.test(ch)) {
106
+ let j = i;
107
+ while (j < text.length && /[0-9.]/.test(text[j])) j += 1;
108
+ const n = Number(text.slice(i, j));
109
+ if (!Number.isFinite(n)) throw new Unsupported("number");
110
+ tokens.push({ t: "num", v: n });
111
+ i = j;
112
+ continue;
113
+ }
114
+ if (/[A-Za-z$]/.test(ch)) {
115
+ let j = i;
116
+ if (text[j] === "$") j += 1;
117
+ const lettersFrom = j;
118
+ while (j < text.length && /[A-Za-z]/.test(text[j])) j += 1;
119
+ const letters = text.slice(lettersFrom, j);
120
+ let k = j;
121
+ if (text[k] === "$") k += 1;
122
+ const digitsFrom = k;
123
+ while (k < text.length && /[0-9]/.test(text[k])) k += 1;
124
+ const word = letters + text.slice(digitsFrom, k);
125
+ if (k > digitsFrom && CELL_REF.test(word)) {
126
+ tokens.push({ t: "ref", v: word.toUpperCase() });
127
+ i = k;
128
+ continue;
129
+ }
130
+ if (!letters) throw new Unsupported("token");
131
+ tokens.push({ t: "fn", v: letters.toUpperCase() });
132
+ i = j;
133
+ continue;
134
+ }
135
+ // A quote, a comma, a `!`, a `%`, a `^`: every one of them is a formula the SERVER can read
136
+ // and this file cannot. See the header: that is `unsupported`, never an error.
137
+ throw new Unsupported("token");
138
+ }
139
+ return tokens;
140
+ };
141
+
142
+ // ── the reference grammar (self-contained: this file imports nothing, see the header) ─────────
143
+
144
+ const colToIndex = (letters: string): number => {
145
+ let n = 0;
146
+ for (const ch of letters.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
147
+ return n;
148
+ };
149
+
150
+ const colLetters = (n: number): string => {
151
+ let out = "";
152
+ let v = n;
153
+ while (v > 0) {
154
+ const rem = (v - 1) % 26;
155
+ out = String.fromCharCode(65 + rem) + out;
156
+ v = Math.floor((v - 1) / 26);
157
+ }
158
+ return out;
159
+ };
160
+
161
+ const splitRef = (ref: string): { col: number; row: number } => {
162
+ const m = /^([A-Za-z]{1,3})([0-9]{1,7})$/.exec(ref);
163
+ if (!m) throw new Unsupported("reference");
164
+ return { col: colToIndex(m[1]), row: Number(m[2]) };
165
+ };
166
+
167
+ /** One simple rectangle's addresses, row major. Cross-sheet ranges are out of scope (header). */
168
+ const rangeAddresses = (from: string, to: string): string[] => {
169
+ const a = splitRef(from);
170
+ const b = splitRef(to);
171
+ const out: string[] = [];
172
+ for (let r = Math.min(a.row, b.row); r <= Math.max(a.row, b.row); r += 1) {
173
+ for (let c = Math.min(a.col, b.col); c <= Math.max(a.col, b.col); c += 1) {
174
+ out.push(colLetters(c) + String(r));
175
+ }
176
+ }
177
+ return out;
178
+ };
179
+
180
+ // ── the dependency graph: what a formula READS, and what must be recomputed after a write ─────
181
+
182
+ /** Double and single quoted runs blanked out, so `"B4 is the total"` names no cell. */
183
+ const withoutQuotes = (src: string): string =>
184
+ String(src ?? "").replace(/"[^"]*"/g, (m) => " ".repeat(m.length))
185
+ .replace(/'[^']*'/g, (m) => " ".repeat(m.length));
186
+
187
+ const REF_SCAN = /\$?([A-Za-z]{1,3})\$?([0-9]{1,7})/g;
188
+
189
+ /**
190
+ * ⭐⭐ EVERY A1 ADDRESS A FORMULA READS, RANGES EXPANDED, UPPERCASED, `$` TOLERATED. This is the
191
+ * INPUT EDGE of the recalculation graph and it is deliberately a little generous: over-reporting
192
+ * a dependency only recomputes a cell that did not need it, while under-reporting leaves a stale
193
+ * number on screen, which is the exact defect this ticket exists to end.
194
+ *
195
+ * ⛔ A FUNCTION NAME IS NOT AN ADDRESS AND NEITHER IS A SHEET PREFIX. `LOG10(B4)` reads B4 alone
196
+ * (`LOG10` is rejected by the `(` that follows it) and `Sheet1!B4` reads nothing at all here,
197
+ * because a cross-sheet reference is the server's to resolve and naming a LOCAL `B4` for it would
198
+ * recompute the wrong cell. Both are pinned by `verify_formula_engine.py`.
199
+ */
200
+ export const referencedAddresses = (src: string): string[] => {
201
+ const text = withoutQuotes(src).replace(/^\s*=/, " ");
202
+ const hits: { addr: string; start: number; end: number }[] = [];
203
+ REF_SCAN.lastIndex = 0;
204
+ let m = REF_SCAN.exec(text);
205
+ while (m) {
206
+ const start = m.index;
207
+ const end = start + m[0].length;
208
+ const before = start > 0 ? text[start - 1] : "";
209
+ const after = end < text.length ? text[end] : "";
210
+ const namePart = /[A-Za-z0-9_$!'.]/.test(before);
211
+ const callOrName = after === "(" || /[A-Za-z0-9_.]/.test(after);
212
+ if (!namePart && !callOrName) {
213
+ hits.push({ addr: (m[1] + m[2]).toUpperCase(), start, end });
214
+ }
215
+ m = REF_SCAN.exec(text);
216
+ }
217
+ const out: string[] = [];
218
+ const seen = new Set<string>();
219
+ const push = (addr: string) => {
220
+ if (seen.has(addr)) return;
221
+ seen.add(addr);
222
+ out.push(addr);
223
+ };
224
+ for (let i = 0; i < hits.length; i += 1) {
225
+ const next = hits[i + 1];
226
+ const between = next ? text.slice(hits[i].end, next.start).trim() : "";
227
+ if (next && between === ":") {
228
+ for (const addr of rangeAddresses(hits[i].addr, next.addr)) push(addr);
229
+ i += 1;
230
+ continue;
231
+ }
232
+ push(hits[i].addr);
233
+ }
234
+ return out;
235
+ };
236
+
237
+ /** The formula graph, indexed both ways, with every address upper cased exactly once. */
238
+ const graphOf = (formulas: Record<string, string>) => {
239
+ const reads = new Map<string, string[]>();
240
+ const readBy = new Map<string, string[]>();
241
+ for (const [rawAddr, src] of Object.entries(formulas ?? {})) {
242
+ const addr = rawAddr.toUpperCase();
243
+ const refs = referencedAddresses(src);
244
+ reads.set(addr, refs);
245
+ for (const ref of refs) {
246
+ const list = readBy.get(ref);
247
+ if (list) list.push(addr);
248
+ else readBy.set(ref, [addr]);
249
+ }
250
+ }
251
+ return { reads, readBy };
252
+ };
253
+
254
+ /**
255
+ * Kahn's algorithm over a chosen set of formula nodes. Returns the nodes it could ORDER (a cell
256
+ * after everything it reads) and the ones it could not, which is the whole of cycle detection:
257
+ * a node whose in-degree never reaches zero is in a cycle or downstream of one.
258
+ *
259
+ * ⛔ THE READY LIST IS SORTED, SO THE ORDER IS DETERMINISTIC. Two cells that could equally well
260
+ * be computed first must be computed in the same order on every run, or a gate that pins the
261
+ * order passes on one machine and fails on the next.
262
+ */
263
+ const kahn = (nodes: Set<string>, reads: Map<string, string[]>) => {
264
+ const indegree = new Map<string, number>();
265
+ const edges = new Map<string, string[]>();
266
+ for (const node of nodes) indegree.set(node, 0);
267
+ for (const node of nodes) {
268
+ for (const ref of reads.get(node) ?? []) {
269
+ if (!nodes.has(ref)) continue;
270
+ indegree.set(node, (indegree.get(node) ?? 0) + 1);
271
+ const list = edges.get(ref);
272
+ if (list) list.push(node);
273
+ else edges.set(ref, [node]);
274
+ }
275
+ }
276
+ const ready = [...nodes].filter((n) => (indegree.get(n) ?? 0) === 0).sort();
277
+ const ordered: string[] = [];
278
+ while (ready.length > 0) {
279
+ const node = ready.shift() as string;
280
+ ordered.push(node);
281
+ for (const dependent of edges.get(node) ?? []) {
282
+ const left = (indegree.get(dependent) ?? 0) - 1;
283
+ indegree.set(dependent, left);
284
+ if (left === 0) {
285
+ ready.push(dependent);
286
+ ready.sort();
287
+ }
288
+ }
289
+ }
290
+ const settled = new Set(ordered);
291
+ const blocked = [...nodes].filter((n) => !settled.has(n)).sort();
292
+ return { ordered, blocked };
293
+ };
294
+
295
+ /**
296
+ * ⭐⭐ EVERY FORMULA ADDRESS THAT CANNOT BE ORDERED AT ALL: it refers back to itself, directly
297
+ * (`A1: =A1`) or round a ring (`A1: =B1`, `B1: =A1`), or it reads one that does. Those cells get
298
+ * {@link CYCLE_REFUSAL} rather than a number, because there is no number to give and the only
299
+ * alternatives are a hang and a wrong answer.
300
+ */
301
+ export const cyclicAddresses = (formulas: Record<string, string>): string[] => {
302
+ const { reads } = graphOf(formulas);
303
+ return kahn(new Set(reads.keys()), reads).blocked;
304
+ };
305
+
306
+ /**
307
+ * ⭐⭐ THE HEART OF INSTRUCTION 11'S SECOND HALF. After `changed` addresses are written, THESE
308
+ * formula cells must be recomputed, in DEPENDENCY ORDER — each one after everything it reads, so
309
+ * `A1` changing recomputes `B1 (=A1+1)` and then `C1 (=B1*2)`, in that order, in one pass.
310
+ * Without this a sheet computes `=F6+G6` once and then never again, which is exactly the owner's
311
+ * "formula is still broken, it only works until I press Refresh".
312
+ *
313
+ * ⛔ THE CHANGED ADDRESSES THEMSELVES ARE NOT IN THE RESULT. Their new cells are what the caller
314
+ * just built; recomputing them here would either duplicate that work or, for a cell the caller
315
+ * deliberately cleared, undo it.
316
+ *
317
+ * ⛔ IT TERMINATES ON A CYCLE. Anything unorderable is appended at the END, in a stable sorted
318
+ * order, and the caller ({@link CYCLE_REFUSAL}'s user, `sheetState.ts::recalcDependents`) states
319
+ * the refusal for it. A recursive walk would have recursed forever on the same input.
320
+ */
321
+ export const recalcOrder = (
322
+ formulas: Record<string, string>,
323
+ changed: readonly string[],
324
+ ): string[] => {
325
+ const { reads, readBy } = graphOf(formulas);
326
+ const changedSet = new Set((changed ?? []).map((a) => String(a).toUpperCase()));
327
+ const affected = new Set<string>();
328
+ const queue: string[] = [...changedSet];
329
+ while (queue.length > 0) {
330
+ const cur = queue.shift() as string;
331
+ for (const dependent of readBy.get(cur) ?? []) {
332
+ if (affected.has(dependent) || changedSet.has(dependent)) continue;
333
+ affected.add(dependent);
334
+ queue.push(dependent);
335
+ }
336
+ }
337
+ const { ordered, blocked } = kahn(affected, reads);
338
+ return [...ordered, ...blocked];
339
+ };
340
+
341
+ // ── evaluation ───────────────────────────────────────────────────────────────────────────────
342
+
343
+ /** A number in progress, carrying whether any input it used was `pending` (last known, not fresh). */
344
+ interface Num { n: number; pending: boolean }
345
+
346
+ const toNum = (cv: CellValue): Num => {
347
+ if (cv.kind === "number") return { n: cv.value, pending: cv.pending === true };
348
+ if (cv.kind === "text") {
349
+ const trimmed = cv.value.trim();
350
+ if (trimmed === "") return { n: 0, pending: cv.pending === true };
351
+ const n = Number(trimmed.replace(/,/g, ""));
352
+ if (!Number.isFinite(n)) throw new FormulaError("This formula expects a number here.");
353
+ return { n, pending: cv.pending === true };
354
+ }
355
+ if (cv.kind === "empty") return { n: 0, pending: false };
356
+ // ⛔⛔ THE TRAP THE TICKET NAMES. A cell with no value at all yet never blocks arithmetic: it
357
+ // reads as zero, WITH `pending: true` riding up so the whole formula can mark itself the same
358
+ // way and recompute the moment the real value arrives.
359
+ if (cv.kind === "pending") return { n: 0, pending: true };
360
+ if (cv.kind === "unsupported") throw new Unsupported(cv.reason);
361
+ throw new FormulaError(cv.message);
362
+ };
363
+
364
+ interface Cursor { tokens: Token[]; i: number }
365
+
366
+ const peekTok = (c: Cursor): Token | undefined => c.tokens[c.i];
367
+ const atEnd = (c: Cursor): boolean => c.i >= c.tokens.length;
368
+ const take = (c: Cursor): Token => {
369
+ const tk = c.tokens[c.i];
370
+ if (!tk) throw new Unsupported("ended early");
371
+ c.i += 1;
372
+ return tk;
373
+ };
374
+ const isOp = (tk: Token | undefined, v: string): boolean => !!tk && tk.t === "op" && tk.v === v;
375
+
376
+ type Getter = (addr: string) => CellValue;
377
+
378
+ const evalAggregate = (name: string, addrs: string[], get: Getter): Num => {
379
+ const nums: number[] = [];
380
+ let pending = false;
381
+ let counted = 0;
382
+ for (const addr of addrs) {
383
+ const cv = get(addr);
384
+ if (cv.kind === "empty") continue;
385
+ if (cv.kind === "pending") { pending = true; continue; }
386
+ if (cv.kind === "unsupported") throw new Unsupported(cv.reason);
387
+ if (cv.kind === "error") throw new FormulaError(cv.message);
388
+ if (cv.kind === "text" && cv.value.trim() === "") continue;
389
+ const num = toNum(cv);
390
+ pending = pending || num.pending;
391
+ nums.push(num.n);
392
+ counted += 1;
393
+ }
394
+ const sum = nums.reduce((a, b) => a + b, 0);
395
+ switch (name) {
396
+ case "SUM": return { n: sum, pending };
397
+ case "COUNT": return { n: counted, pending };
398
+ case "AVG": return { n: nums.length ? sum / nums.length : 0, pending };
399
+ case "MIN": return { n: nums.length ? Math.min(...nums) : 0, pending };
400
+ case "MAX": return { n: nums.length ? Math.max(...nums) : 0, pending };
401
+ default: throw new Unsupported(name);
402
+ }
403
+ };
404
+
405
+ const parseAtom = (c: Cursor, get: Getter): Num => {
406
+ const tk = take(c);
407
+ if (tk.t === "num") return { n: tk.v, pending: false };
408
+ if (tk.t === "ref") return toNum(get(tk.v));
409
+ if (tk.t === "fn") {
410
+ const name = tk.v;
411
+ // ⭐ EVERY OTHER FUNCTION IN THE CATALOGUE IS THE SERVER'S. `IF`, `ROUND`, `TEXT` and the
412
+ // rest are real formulas this file does not speak, so they take the `unsupported` road home
413
+ // and keep working exactly as they did before this ticket (see the header).
414
+ if (!AGGREGATE_SET.has(name)) throw new Unsupported(name);
415
+ if (!isOp(peekTok(c), "(")) throw new Unsupported(name);
416
+ take(c);
417
+ const from = take(c);
418
+ if (from.t !== "ref" || !isOp(peekTok(c), ":")) throw new Unsupported(name);
419
+ take(c);
420
+ const to = take(c);
421
+ if (to.t !== "ref") throw new Unsupported(name);
422
+ if (!isOp(peekTok(c), ")")) throw new Unsupported(name);
423
+ take(c);
424
+ return evalAggregate(name, rangeAddresses(from.v, to.v), get);
425
+ }
426
+ if (tk.t === "op" && tk.v === "(") {
427
+ const inner = parseExpr(c, get);
428
+ if (!isOp(peekTok(c), ")")) throw new Unsupported("parenthesis");
429
+ take(c);
430
+ return inner;
431
+ }
432
+ throw new Unsupported("token");
433
+ };
434
+
435
+ const parseUnary = (c: Cursor, get: Getter): Num => {
436
+ if (isOp(peekTok(c), "-")) {
437
+ take(c);
438
+ const inner = parseUnary(c, get);
439
+ return { n: -inner.n, pending: inner.pending };
440
+ }
441
+ if (isOp(peekTok(c), "+")) { take(c); return parseUnary(c, get); }
442
+ return parseAtom(c, get);
443
+ };
444
+
445
+ const parseTerm = (c: Cursor, get: Getter): Num => {
446
+ let left = parseUnary(c, get);
447
+ while (isOp(peekTok(c), "*") || isOp(peekTok(c), "/")) {
448
+ const op = take(c);
449
+ const right = parseUnary(c, get);
450
+ if (op.t === "op" && op.v === "/") {
451
+ // ⛔ A DIVISOR THAT IS ONLY ZERO BECAUSE IT HAS NOT LOADED IS NOT A DIVISION BY ZERO. It is
452
+ // a value nobody has yet, so the whole formula waits rather than accusing the reader of
453
+ // dividing by something they never wrote.
454
+ if (right.n === 0 && right.pending) throw new PendingInput("divisor");
455
+ if (right.n === 0) throw new FormulaError("This formula divides by zero.");
456
+ left = { n: left.n / right.n, pending: left.pending || right.pending };
457
+ } else {
458
+ left = { n: left.n * right.n, pending: left.pending || right.pending };
459
+ }
460
+ }
461
+ return left;
462
+ };
463
+
464
+ const parseExpr = (c: Cursor, get: Getter): Num => {
465
+ let left = parseTerm(c, get);
466
+ while (isOp(peekTok(c), "+") || isOp(peekTok(c), "-")) {
467
+ const op = take(c);
468
+ const right = parseTerm(c, get);
469
+ const plus = op.t === "op" && op.v === "+";
470
+ left = { n: plus ? left.n + right.n : left.n - right.n,
471
+ pending: left.pending || right.pending };
472
+ }
473
+ return left;
474
+ };
475
+
476
+ /**
477
+ * ⚠ BINARY FLOATING POINT'S OWN NOISE, TRIMMED AT THE LAST PLACE IT CAN BE TRUSTED. `0.1 + 0.2`
478
+ * is `0.30000000000000004` in every language that uses doubles, and a spreadsheet that paints
479
+ * that reads as broken. 15 significant digits is the widest a double round trips exactly, so this
480
+ * removes the noise and nothing else.
481
+ */
482
+ const cleanNumber = (n: number): number => {
483
+ if (!Number.isFinite(n) || Number.isInteger(n)) return n;
484
+ return Number(n.toPrecision(15));
485
+ };
486
+
487
+ /**
488
+ * ⭐⭐ THE ONE ENTRY POINT, CONTRACT C1. `src` may or may not carry its leading `=`; both are
489
+ * accepted so a caller can hand this either the raw stored formula or its own trimmed draft.
490
+ *
491
+ * ⭐ A BARE SINGLE REFERENCE PASSES THROUGH UNCOERCED. `=F6` of a text cell is F6's text, not a
492
+ * refusal: only once an operator or a function is involved does this coerce through arithmetic,
493
+ * exactly as Excel's own distinction between "reads a cell" and "computes with a cell" works.
494
+ *
495
+ * ⛔ NEVER THROWS. Every outcome — a token this engine does not speak, a function that belongs to
496
+ * the server, a division by zero, a reference to a cell held in a genuine error state — comes
497
+ * back as a `CellValue`, because a formula cell's caller (`sheetState.ts::setFormula`) has
498
+ * exactly one door for each of them and it is a value, not an exception.
499
+ */
500
+ export const evaluateFormula = (src: string, get: Getter): CellValue => {
501
+ try {
502
+ const tokens = tokenize(src);
503
+ if (tokens.length === 0) return { kind: "empty" };
504
+ if (tokens.length === 1 && tokens[0].t === "ref") {
505
+ const one = tokens[0];
506
+ return one.t === "ref" ? get(one.v) : { kind: "empty" };
507
+ }
508
+ const cursor: Cursor = { tokens, i: 0 };
509
+ const result = parseExpr(cursor, get);
510
+ if (!atEnd(cursor)) throw new Unsupported("trailing tokens");
511
+ if (!Number.isFinite(result.n)) {
512
+ return { kind: "error", message: "This formula could not be calculated." };
513
+ }
514
+ const value = cleanNumber(result.n);
515
+ return result.pending ? { kind: "number", value, pending: true } : { kind: "number", value };
516
+ } catch (err) {
517
+ if (err instanceof PendingInput) return { kind: "pending" };
518
+ if (err instanceof Unsupported) return { kind: "unsupported", reason: err.message };
519
+ if (err instanceof FormulaError) return { kind: "error", message: err.message };
520
+ return { kind: "error", message: "This formula could not be calculated." };
521
+ }
522
+ };
web/src/sheet/sheetState.ts CHANGED
@@ -26,6 +26,14 @@ import {
26
  shiftForStructure, shiftRef,
27
  } from "./a1";
28
  import type { StructuralShift } from "./a1";
 
 
 
 
 
 
 
 
29
 
30
  /** R19's three MARKS. `refused` is a fourth state and not one of the three: it replaces the value
31
  * rather than qualifying it, so it gets its own treatment in the renderer. */
@@ -46,6 +54,15 @@ export const markOf = (cell: Cell | null | undefined): CellMark => {
46
  if (cell.kind === "empty") return "none";
47
  if (cell.state === "refused") return "refused";
48
  if (cell.kind === "literal") return "typed";
 
 
 
 
 
 
 
 
 
49
  if (cell.state === "stale") return "bound-stale";
50
  return "bound-fresh";
51
  };
@@ -200,32 +217,162 @@ export const withCell = (book: Workbook, tabId: string, addr: string, cell: Cell
200
  export const isFormulaText = (text: string | null | undefined): boolean =>
201
  String(text ?? "").trimStart().startsWith("=");
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  /**
204
  * A hand typed FORMULA cell.
205
  *
206
- * ⛔ IT CARRIES NO VALUE, AND THAT IS R10 RATHER THAN AN OVERSIGHT. A sheet is a SNAPSHOT: only
207
- * Refresh computes, and the authority for evaluation is the server (`formula_runtime.py`), never
208
- * this file. So a freshly typed formula is `stale` and DISPLAYS ITS OWN TEXT until a refresh
209
- * replaces it, which is the honest thing to paint: the reader sees what they typed plus the mark
210
- * that means "not computed yet", instead of a blank cell that reads as nothing.
 
 
 
 
 
211
  *
212
- * ⛔ The binding, source and refusal of whatever was there before are DROPPED. A formula has none
213
- * of the three, and a left over `binding` would repaint from the database on the next refresh.
 
214
  */
215
- export const setFormula = (cell: Cell | null | undefined, formula: string): Cell => {
 
 
 
 
216
  const rest = { ...(cell ?? {}) } as Partial<Cell>;
217
  delete rest.binding;
218
  delete rest.source;
219
  delete rest.refusal;
220
  delete rest.refreshed_at;
221
  delete rest.text;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  return {
223
  ...rest,
224
  kind: "formula",
225
- state: "stale",
226
  formula,
227
  value: null,
228
- display: formula,
 
229
  };
230
  };
231
 
@@ -241,9 +388,74 @@ export const setFormula = (cell: Cell | null | undefined, formula: string): Cell
241
  * removes the value and leaves the border, exactly as Excel does and exactly as the Delete key
242
  * does one door away, so the two cannot disagree about what a cleared cell looks like.
243
  */
244
- export const commitTyped = (cell: Cell | null | undefined, text: string): Cell | null => {
 
 
 
 
245
  if (String(text ?? "") === "") return blankOf(cell);
246
- return isFormulaText(text) ? setFormula(cell, text) : setLiteral(cell, text);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  };
248
 
249
  /**
@@ -448,6 +660,19 @@ export interface BoundDragTally {
448
  /** A bulk edit that also carries what the drag rules did. Every existing consumer still reads it. */
449
  export interface FillEdit extends BulkEdit, BoundDragTally {}
450
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  const emptyTally = (): BoundDragTally => ({ dragged: 0, noCatalogue: 0, noField: 0, atEnd: 0 });
452
 
453
  /** How many MONTHS one step of each unit is worth. `start` is `YYYY-MM` for all three (C2). */
@@ -739,46 +964,101 @@ export const pasteCells = (
739
  values: readonly (readonly string[])[],
740
  bounds: { cols: number; rows: number },
741
  drag?: DragContext,
742
- ): FillEdit => {
 
 
 
 
 
 
 
 
 
 
 
 
743
  const edits: Record<string, Cell | null> = {};
744
  const tally = emptyTally();
745
- for (let r = 0; r < values.length; r += 1) {
746
- const row = values[r] ?? [];
747
- for (let c = 0; c < row.length; c += 1) {
748
- const col = targetCol + c;
749
- const rowIndex = targetRow + r;
750
- if (col >= bounds.cols || rowIndex >= bounds.rows) continue;
751
- const addr = addressOf(col, rowIndex);
752
- const cell = cellAt(tab, addr);
753
- // ⭐⭐ R5 (W52-T09): A BOUND TARGET IS NO LONGER SKIPPED. Landing a plain value on a
754
- // database-bound cell now clears it and drops its binding through `commitTyped`, exactly
755
- // as typing over one does — the wall this door once kept is gone (see `BulkEdit`'s note).
756
- //
757
- // ⭐⭐ W51-T19 — THE FOURTH DOOR, AND IT NEEDS THE SOURCE CELLS TO EXIST AT ALL. A
758
- // clipboard round trip carries TEXT: glide writes what a cell READS, so a copied bound
759
- // cell arrives here as its number with no binding anywhere on it. Where the door that
760
- // pasted also knows what was copied ({@link DragContext.cells}), the binding takes the
761
- // rule path exactly as a fill does; where it does not, the block lands as the values it
762
- // really is. Guessing that a matching number came from a binding would be worse.
763
- //
764
- // ⛔ THE OFFSET IS THE BLOCK'S, NOT THE CELL'S. Every cell in a pasted block moves by the
765
- // SAME delta, exactly as a moved formula does: the cell at `[r][c]` came from
766
- // `(from.col + c, from.row + r)` and lands at `(targetCol + c, targetRow + r)`, so the two
767
- // `c`s cancel. Writing `col - from.col` instead adds the block's own width back in and
768
- // gives the second column of a two column paste a period one month further out than the
769
- // first, which reads as a working feature until somebody checks the numbers.
770
- const copied = drag?.cells?.[r]?.[c] ?? null;
771
- if (copied && copied.kind === "bound" && drag?.from) {
772
- const out = dragBoundCell(copied, targetCol - drag.from.col, targetRow - drag.from.row,
773
- drag.catalogue);
774
- edits[addr] = out.cell;
775
- tally.dragged += 1;
776
- if (out.noCatalogue) tally.noCatalogue += 1;
777
- if (out.noField) tally.noField += 1;
778
- if (out.atEnd) tally.atEnd += 1;
779
- continue;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
780
  }
781
- edits[addr] = commitTyped(cell, String(row[c] ?? ""));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782
  }
783
  }
784
  return { edits, ...tally };
@@ -800,6 +1080,7 @@ export const fillCells = (
800
  source: { col0: number; row0: number; col1: number; row1: number },
801
  destination: { col0: number; row0: number; col1: number; row1: number },
802
  drag?: DragContext,
 
803
  ): FillEdit => {
804
  const sc0 = Math.min(source.col0, source.col1);
805
  const sr0 = Math.min(source.row0, source.row1);
@@ -807,6 +1088,10 @@ export const fillCells = (
807
  const sh = Math.abs(source.row1 - source.row0) + 1;
808
  const edits: Record<string, Cell | null> = {};
809
  const tally = emptyTally();
 
 
 
 
810
  for (let row = Math.min(destination.row0, destination.row1);
811
  row <= Math.max(destination.row0, destination.row1); row += 1) {
812
  for (let col = Math.min(destination.col0, destination.col1);
@@ -850,6 +1135,7 @@ export const fillCells = (
850
  edits[addr] = setFormula(
851
  target,
852
  fillFormula(pattern.formula ?? "", row - srcRow, col - srcCol),
 
853
  );
854
  continue;
855
  }
 
26
  shiftForStructure, shiftRef,
27
  } from "./a1";
28
  import type { StructuralShift } from "./a1";
29
+ // ⭐⭐ W53-T01 / CONTRACT C1 — THE ONE IMPORT THAT MAKES A COMMITTED FORMULA COMPUTE LOCALLY.
30
+ // `formulaEval.ts` imports nothing back from this file (see its own header): it takes a plain
31
+ // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
32
+ // one door that turns this file's `Cell` into that shape, so the evaluator itself never has to.
33
+ import {
34
+ CYCLE_REFUSAL, cyclicAddresses, evaluateFormula, recalcOrder,
35
+ } from "./formulaEval";
36
+ import type { CellValue } from "./formulaEval";
37
 
38
  /** R19's three MARKS. `refused` is a fourth state and not one of the three: it replaces the value
39
  * rather than qualifying it, so it gets its own treatment in the renderer. */
 
54
  if (cell.kind === "empty") return "none";
55
  if (cell.state === "refused") return "refused";
56
  if (cell.kind === "literal") return "typed";
57
+ // ⭐⭐ W53-T01 / R2 — A FORMULA THAT COMPUTED IN THIS BROWSER IS NOT A DATABASE READING, AND
58
+ // THE FALL-THROUGH WOULD HAVE SAID IT WAS. Every formula cell used to be `stale` (nothing on
59
+ // the client could compute one), so it always took the line above and wore the YELLOW triangle.
60
+ // Now that R2 computes one on commit it becomes `fresh`, and one line lower `bound-fresh` would
61
+ // paint R19's BLUE triangle: "this number came from a database, and it is current". A hand
62
+ // typed `=F6+G6` came from no database at all, so it wears the grey dot a hand typed value
63
+ // wears. A formula still WAITING on a bound dependency keeps the yellow, because that is
64
+ // exactly what it means there: a database reading that is not fresh yet.
65
+ if (cell.kind === "formula") return cell.state === "stale" ? "bound-stale" : "typed";
66
  if (cell.state === "stale") return "bound-stale";
67
  return "bound-fresh";
68
  };
 
217
  export const isFormulaText = (text: string | null | undefined): boolean =>
218
  String(text ?? "").trimStart().startsWith("=");
219
 
220
+ /**
221
+ * ⭐⭐ W53-T01 / CONTRACT C1 — A `Cell` (this file's whole vocabulary) READ AS AN INPUT TO THE
222
+ * evaluator (`formulaEval.ts`, which knows no `Cell` at all — see its header). This is the one
223
+ * door: `evaluateFormula`'s `get` callback is `(addr) => cellToValue(cellAt(tab, addr))`, and
224
+ * nothing else in the app builds a `CellValue` by hand.
225
+ *
226
+ * ⛔⛔ A CELL'S `state` DECIDES `pending`, NOT ITS `value`. A `value` of `null` on a bound or
227
+ * formula cell that has NEVER resolved is the TRAP's other half: `{ kind: "pending" }`, no number
228
+ * to use at all, which arithmetic reads as zero while marking the whole result pending. A bound
229
+ * cell that HAS resolved before, however stale, carries its LAST KNOWN value — ruling R2 says a
230
+ * referencing formula renders from exactly that, immediately, with the dependency marked pending
231
+ * rather than blocking on the network.
232
+ */
233
+ export const cellToValue = (cell: Cell | null | undefined): CellValue => {
234
+ if (!cell || cell.kind === "empty") return { kind: "empty" };
235
+ if (cell.state === "refused") {
236
+ return { kind: "error", message: cell.refusal?.message ?? "This cell could not be calculated." };
237
+ }
238
+ if (cell.value == null) {
239
+ // ⛔ A BLANK LITERAL IS EMPTY; A BOUND OR FORMULA CELL WITH NOTHING COMPUTED IS PENDING. The
240
+ // difference is a confident zero versus an honest "not yet", and it is the whole of the trap.
241
+ return cell.kind === "literal" ? { kind: "empty" } : { kind: "pending" };
242
+ }
243
+ const pending = cell.kind !== "literal" && cell.state === "stale";
244
+ const n = asNumber(cell.value);
245
+ if (n !== null) {
246
+ return pending ? { kind: "number", value: n, pending: true } : { kind: "number", value: n };
247
+ }
248
+ const text = String(cell.value);
249
+ return pending ? { kind: "text", value: text, pending: true } : { kind: "text", value: text };
250
+ };
251
+
252
+ /**
253
+ * ⭐⭐ W53-T01 — THE READER A BULK DOOR HANDS THE EVALUATOR, and the reason it is a function of
254
+ * the edits rather than of the tab. A fill or a paste writes many cells in one pass, and a later
255
+ * cell in that pass may READ an earlier one: `=B2+1` filled down B3..B20 is twenty formulas each
256
+ * reading the one above it. Reading the TAB would give every one of them the value from before
257
+ * the fill started. So an address this pass has already written answers with what it wrote.
258
+ *
259
+ * ⚠ `get` IS THE BASE, not the whole of it. A caller that has a component's own getter in hand
260
+ * passes it; a caller that does not gets the tab, which is the same thing one layer down.
261
+ */
262
+ const overlayGetter = (
263
+ tab: SheetTab | null | undefined,
264
+ edits: Record<string, Cell | null>,
265
+ get?: (addr: string) => CellValue,
266
+ ): ((addr: string) => CellValue) => {
267
+ const base = get ?? ((addr: string) => cellToValue(cellAt(tab, addr)));
268
+ return (addr: string) => (Object.prototype.hasOwnProperty.call(edits, addr)
269
+ ? cellToValue(edits[addr])
270
+ : base(addr));
271
+ };
272
+
273
+ /**
274
+ * What `setFormula` builds once it has an `evaluateFormula` result: the shared tail of every leg.
275
+ *
276
+ * ⛔⛔ `pending` AND `unsupported` KEEP THE LAST COMPUTED VALUE, WHICH IS R10 UNCHANGED. Neither
277
+ * of them means the old number is wrong; one means an input has not arrived and the other means
278
+ * the SERVER owns this formula (a cross sheet reference, a catalogue function this smaller engine
279
+ * does not speak). Both mark the cell `stale` and leave what was last computed alone, so a
280
+ * formula that used to work keeps working and Refresh still answers it. Only a cell with nothing
281
+ * to show at all falls back to painting its own text, which is exactly what it did before R2.
282
+ */
283
+ const cellFromFormulaResult = (
284
+ base: Partial<Cell>, formula: string, result: CellValue,
285
+ ): Cell => {
286
+ const shared = { ...base, kind: "formula" as const, formula };
287
+ const held = (): Cell => {
288
+ if (base.value == null) return { ...shared, state: "stale", value: null, display: formula };
289
+ return { ...shared, state: "stale", value: base.value,
290
+ display: base.display ?? String(base.value) };
291
+ };
292
+ switch (result.kind) {
293
+ case "number":
294
+ return { ...shared, state: result.pending ? "stale" : "fresh", value: result.value,
295
+ display: String(result.value) };
296
+ case "text":
297
+ return { ...shared, state: result.pending ? "stale" : "fresh", value: result.value,
298
+ display: result.value };
299
+ case "empty":
300
+ return { ...shared, state: "fresh", value: null, display: "" };
301
+ case "pending":
302
+ case "unsupported":
303
+ return held();
304
+ case "error":
305
+ return { ...shared, state: "refused", value: null, display: "",
306
+ refusal: { code: "formula_error", message: result.message } };
307
+ default: {
308
+ const _exhaustive: never = result;
309
+ return _exhaustive;
310
+ }
311
+ }
312
+ };
313
+
314
  /**
315
  * A hand typed FORMULA cell.
316
  *
317
+ * ⭐⭐ RULING R2 (W53-T01) — A FORMULA OVER OTHER CELLS COMPUTES HERE, NOW, OFFLINE. Before this
318
+ * ticket a sheet was a pure snapshot: only Refresh computed anything, evaluation lived entirely
319
+ * on the server, and a freshly typed formula stayed `stale` and painted its own text until the
320
+ * next whole-workbook round trip. R2 ends that for the COMMIT path: when `get` is supplied this
321
+ * calls `formulaEval.ts::evaluateFormula` immediately and stores the computed `value` and
322
+ * `display`, so the cell shows its NUMBER the instant Enter is pressed, with no network request.
323
+ *
324
+ * ⚠ `get` IS OPTIONAL AND BACKWARD COMPATIBLE ON PURPOSE. Passing none reproduces the exact old
325
+ * return value — `stale`, no value, displays its own text — which is what a caller that has no
326
+ * tab in hand (a test fixture, a future door) should still get rather than a wrong number.
327
  *
328
+ * ⛔ The binding, source and refusal of whatever was there before are DROPPED either way. A
329
+ * formula has none of the three, and a left over `binding` would repaint from the database on the
330
+ * next refresh.
331
  */
332
+ export const setFormula = (
333
+ cell: Cell | null | undefined,
334
+ formula: string,
335
+ get?: (addr: string) => CellValue,
336
+ ): Cell => {
337
  const rest = { ...(cell ?? {}) } as Partial<Cell>;
338
  delete rest.binding;
339
  delete rest.source;
340
  delete rest.refusal;
341
  delete rest.refreshed_at;
342
  delete rest.text;
343
+ if (!get) {
344
+ return {
345
+ ...rest,
346
+ kind: "formula",
347
+ state: "stale",
348
+ formula,
349
+ value: null,
350
+ display: formula,
351
+ };
352
+ }
353
+ return cellFromFormulaResult(rest, formula, evaluateFormula(formula, get));
354
+ };
355
+
356
+ /**
357
+ * ⭐⭐ W53-T01 — A CYCLE STATES ITSELF. `=A1` in A1, or `A1: =B1` beside `B1: =A1`, has no value
358
+ * to compute and only two wrong answers available: a hang, or a number picked from whichever side
359
+ * of the ring happened to be visited first. So it refuses, in one sentence, exactly as R16's other
360
+ * refusals do — {@link displayText} paints the message rather than a blank.
361
+ */
362
+ const refuseCycle = (cell: Cell | null | undefined, formula: string): Cell => {
363
+ const rest = { ...(cell ?? {}) } as Partial<Cell>;
364
+ delete rest.binding;
365
+ delete rest.source;
366
+ delete rest.refreshed_at;
367
+ delete rest.text;
368
  return {
369
  ...rest,
370
  kind: "formula",
371
+ state: "refused",
372
  formula,
373
  value: null,
374
+ display: "",
375
+ refusal: { code: "formula_cycle", message: CYCLE_REFUSAL },
376
  };
377
  };
378
 
 
388
  * removes the value and leaves the border, exactly as Excel does and exactly as the Delete key
389
  * does one door away, so the two cannot disagree about what a cleared cell looks like.
390
  */
391
+ export const commitTyped = (
392
+ cell: Cell | null | undefined,
393
+ text: string,
394
+ get?: (addr: string) => CellValue,
395
+ ): Cell | null => {
396
  if (String(text ?? "") === "") return blankOf(cell);
397
+ return isFormulaText(text) ? setFormula(cell, text, get) : setLiteral(cell, text);
398
+ };
399
+
400
+ /**
401
+ * ⭐⭐ W53-T01 / INSTRUCTION 11 — WHAT ELSE HAS TO CHANGE BECAUSE THESE CELLS DID. Given the
402
+ * edits a commit is about to write, this returns the ADDITIONAL edits for every formula cell that
403
+ * READS one of them, transitively, recomputed in dependency order: change F6 and `=F6+G6`
404
+ * follows, and anything reading THAT follows it, in one pass. Without this, a formula computes
405
+ * once when it is typed and never again, which is the owner's "it only works until I press
406
+ * Refresh" with an extra step rather than a fix.
407
+ *
408
+ * ⛔⛔ THE CALLER MERGES THIS INTO THE SAME `onCommit`, NEVER A SECOND ONE. `SheetPage.tsx`'s
409
+ * commit takes a HISTORY STEP and queues a SAVE, so two calls would make one edit cost two
410
+ * Ctrl+Z presses and two writes racing for the same `rev`.
411
+ *
412
+ * ⛔ AND IT IS CALLED FROM A COMMIT DOOR, NEVER FROM AN EFFECT WATCHING THE DOCUMENT. An effect
413
+ * that recomputed on load would mutate a workbook nobody edited, queue a write to the tenant
414
+ * store, and leave a phantom undo step behind merely for opening the sheet.
415
+ *
416
+ * ⚠ THE GETTER IS AN OVERLAY, and that is what makes the ORDER mean anything: an address the
417
+ * commit is writing reads its NEW cell, an address this function has already recomputed reads
418
+ * THAT, and everything else reads the tab. So `C1 = =B1*2` sees the `B1` recomputed one step
419
+ * earlier in the same pass rather than the one on screen.
420
+ */
421
+ export const recalcDependents = (
422
+ tab: SheetTab | null | undefined,
423
+ edits: Record<string, Cell | null>,
424
+ ): Record<string, Cell | null> => {
425
+ const formulas: Record<string, string> = {};
426
+ for (const [addr, cell] of Object.entries(tab?.cells ?? {})) {
427
+ if (cell && cell.kind === "formula" && cell.formula) formulas[addr] = cell.formula;
428
+ }
429
+ for (const [addr, cell] of Object.entries(edits ?? {})) {
430
+ if (cell && cell.kind === "formula" && cell.formula) formulas[addr] = cell.formula;
431
+ else delete formulas[addr];
432
+ }
433
+ const out: Record<string, Cell | null> = {};
434
+ const has = (map: Record<string, Cell | null>, addr: string): boolean =>
435
+ Object.prototype.hasOwnProperty.call(map, addr);
436
+ const currentAt = (addr: string): Cell | null => {
437
+ if (has(out, addr)) return out[addr];
438
+ if (has(edits ?? {}, addr)) return edits[addr];
439
+ return cellAt(tab, addr);
440
+ };
441
+ const get = (addr: string): CellValue => cellToValue(currentAt(addr));
442
+ const cyclic = new Set(cyclicAddresses(formulas));
443
+ // A JUST TYPED formula can itself close a ring, and it is not in the walk below (its own new
444
+ // cell is the caller's). It is caught here instead, so `=A1` typed into A1 refuses rather than
445
+ // quietly reading whatever A1 held a moment ago.
446
+ for (const addr of Object.keys(edits ?? {})) {
447
+ const cell = edits[addr];
448
+ if (cell && cell.kind === "formula" && cyclic.has(addr)) {
449
+ out[addr] = refuseCycle(cell, cell.formula ?? formulas[addr] ?? "");
450
+ }
451
+ }
452
+ for (const addr of recalcOrder(formulas, Object.keys(edits ?? {}))) {
453
+ const formula = formulas[addr];
454
+ if (!formula) continue;
455
+ const prev = currentAt(addr);
456
+ out[addr] = cyclic.has(addr) ? refuseCycle(prev, formula) : setFormula(prev, formula, get);
457
+ }
458
+ return out;
459
  };
460
 
461
  /**
 
660
  /** A bulk edit that also carries what the drag rules did. Every existing consumer still reads it. */
661
  export interface FillEdit extends BulkEdit, BoundDragTally {}
662
 
663
+ /**
664
+ * A PASTE, which is a fill that can also refuse for a reason no other bulk door has.
665
+ *
666
+ * ⭐⭐ W53-T03 — THE REFUSAL IS A FIELD, NOT A THROW AND NOT A SILENT EMPTY RESULT. A paste whose
667
+ * target rectangle is not a whole multiple of the copied block writes NOTHING, and the door that
668
+ * pasted has to be able to say so; every other thing a bulk door says already comes back on the
669
+ * result object, so this one does too.
670
+ */
671
+ export interface PasteEdit extends FillEdit {
672
+ /** Set when the target rectangle cannot hold whole copies of the block. `edits` is then empty. */
673
+ sizeRefusal?: string;
674
+ }
675
+
676
  const emptyTally = (): BoundDragTally => ({ dragged: 0, noCatalogue: 0, noField: 0, atEnd: 0 });
677
 
678
  /** How many MONTHS one step of each unit is worth. `start` is `YYYY-MM` for all three (C2). */
 
964
  values: readonly (readonly string[])[],
965
  bounds: { cols: number; rows: number },
966
  drag?: DragContext,
967
+ get?: (addr: string) => CellValue,
968
+ /**
969
+ * THE TARGET RECTANGLE, IN THE SHEET'S OWN COORDINATES, WHEN SOMEBODY DRAGGED ONE OUT.
970
+ *
971
+ * ⭐⭐ W53-T03 — WITHOUT IT THIS FUNCTION ONLY EVER KNEW THE COPIED BLOCK'S OWN SHAPE, which
972
+ * is why one copied cell pasted over a selection of twenty wrote the top left one and left
973
+ * nineteen untouched. Excel repeats the block across the selection whenever the selection is a
974
+ * whole multiple of it on each axis, refuses when it is not, and anchors the block at the cell
975
+ * when a single cell is selected. Absent, or a single cell, keeps that anchored paste, which is
976
+ * what every existing caller and every existing proof already expects.
977
+ */
978
+ region?: CellRange,
979
+ ): PasteEdit => {
980
  const edits: Record<string, Cell | null> = {};
981
  const tally = emptyTally();
982
+ // ⭐ W53-T01 / R2: a PASTED formula computes on landing too, and it reads through an OVERLAY —
983
+ // an address this same paste has already written answers with what the paste wrote, not with
984
+ // what is still on screen, so a two row block whose second row reads its first is right.
985
+ const read = overlayGetter(tab, edits, get);
986
+ // ⚠ AN EMPTY PAYLOAD IS ONE BLANK CELL, NOT NOTHING (W53-T03). A copy of a single blank cell
987
+ // reaches this door as `[[""]]`, but an empty row says exactly the same thing, and a payload
988
+ // that is genuinely nothing was already refused by the door that read the clipboard. Without
989
+ // this, "paste a blank over twenty cells" would write nothing and say nothing.
990
+ const source = values.length === 0 || values.every((row) => row.length === 0)
991
+ ? ([[""]] as readonly (readonly string[])[])
992
+ : values;
993
+ /**
994
+ * Land the copied block ONCE, with its top left corner at `originCol` / `originRow`.
995
+ *
996
+ * ⚠ A RAGGED ROW STILL WRITES ONLY THE CELLS IT HAS. That is the behaviour an anchored paste
997
+ * has always had, and tiling must not quietly start blanking cells the block never reached.
998
+ */
999
+ const writeBlock = (originCol: number, originRow: number) => {
1000
+ for (let r = 0; r < source.length; r += 1) {
1001
+ const row = source[r] ?? [];
1002
+ for (let c = 0; c < row.length; c += 1) {
1003
+ const col = originCol + c;
1004
+ const rowIndex = originRow + r;
1005
+ if (col >= bounds.cols || rowIndex >= bounds.rows) continue;
1006
+ const addr = addressOf(col, rowIndex);
1007
+ const cell = cellAt(tab, addr);
1008
+ // ⭐⭐ R5 (W52-T09): A BOUND TARGET IS NO LONGER SKIPPED. Landing a plain value on a
1009
+ // database-bound cell now clears it and drops its binding through `commitTyped`, exactly
1010
+ // as typing over one does — the wall this door once kept is gone (see `BulkEdit`'s note).
1011
+ //
1012
+ // ⭐⭐ W51-T19 — THE FOURTH DOOR, AND IT NEEDS THE SOURCE CELLS TO EXIST AT ALL. A
1013
+ // clipboard round trip carries TEXT: glide writes what a cell READS, so a copied bound
1014
+ // cell arrives here as its number with no binding anywhere on it. Where the door that
1015
+ // pasted also knows what was copied ({@link DragContext.cells}), the binding takes the
1016
+ // rule path exactly as a fill does; where it does not, the block lands as the values it
1017
+ // really is. Guessing that a matching number came from a binding would be worse.
1018
+ //
1019
+ // ⛔ THE OFFSET IS THE BLOCK'S, NOT THE CELL'S. Every cell in a pasted block moves by the
1020
+ // SAME delta, exactly as a moved formula does: the cell at `[r][c]` came from
1021
+ // `(from.col + c, from.row + r)` and lands at `(targetCol + c, targetRow + r)`, so the two
1022
+ // `c`s cancel. Writing `col - from.col` instead adds the block's own width back in and
1023
+ // gives the second column of a two column paste a period one month further out than the
1024
+ // first, which reads as a working feature until somebody checks the numbers.
1025
+ const copied = drag?.cells?.[r]?.[c] ?? null;
1026
+ if (copied && copied.kind === "bound" && drag?.from) {
1027
+ const out = dragBoundCell(copied, originCol - drag.from.col,
1028
+ originRow - drag.from.row, drag.catalogue);
1029
+ edits[addr] = out.cell;
1030
+ tally.dragged += 1;
1031
+ if (out.noCatalogue) tally.noCatalogue += 1;
1032
+ if (out.noField) tally.noField += 1;
1033
+ if (out.atEnd) tally.atEnd += 1;
1034
+ continue;
1035
+ }
1036
+ edits[addr] = commitTyped(cell, String(row[c] ?? ""), read);
1037
  }
1038
+ }
1039
+ };
1040
+ // ⭐⭐ W53-T03 — THE SELECTION SAYS HOW MANY TIMES THE BLOCK LANDS; THE BLOCK NEVER DOES.
1041
+ // ⚠ The source width is the WIDEST row, so a ragged block still has one honest shape to repeat.
1042
+ const rect = region ? normalised(region) : null;
1043
+ const wide = rect ? rect.col1 - rect.col0 + 1 : 1;
1044
+ const tall = rect ? rect.row1 - rect.row0 + 1 : 1;
1045
+ const srcRows = source.length;
1046
+ let srcCols = 0;
1047
+ for (const row of source) srcCols = Math.max(srcCols, row.length);
1048
+ if (!rect || srcRows === 0 || srcCols === 0 || (wide === 1 && tall === 1)) {
1049
+ // No drag, or one target cell: the block lands anchored where it was dropped, as it always has.
1050
+ writeBlock(targetCol, targetRow);
1051
+ return { edits, ...tally };
1052
+ }
1053
+ if (wide % srcCols !== 0 || tall % srcRows !== 0) {
1054
+ // ⛔ NOTHING IS WRITTEN ON A REFUSAL. Half a tile would leave the selection holding half a
1055
+ // paste, which is the one outcome nobody can see well enough to put back by hand.
1056
+ return { edits: {}, ...emptyTally(),
1057
+ sizeRefusal: "The copy area and the paste area are not the same size." };
1058
+ }
1059
+ for (let ty = 0; ty < tall / srcRows; ty += 1) {
1060
+ for (let tx = 0; tx < wide / srcCols; tx += 1) {
1061
+ writeBlock(rect.col0 + tx * srcCols, rect.row0 + ty * srcRows);
1062
  }
1063
  }
1064
  return { edits, ...tally };
 
1080
  source: { col0: number; row0: number; col1: number; row1: number },
1081
  destination: { col0: number; row0: number; col1: number; row1: number },
1082
  drag?: DragContext,
1083
+ get?: (addr: string) => CellValue,
1084
  ): FillEdit => {
1085
  const sc0 = Math.min(source.col0, source.col1);
1086
  const sr0 = Math.min(source.row0, source.row1);
 
1088
  const sh = Math.abs(source.row1 - source.row0) + 1;
1089
  const edits: Record<string, Cell | null> = {};
1090
  const tally = emptyTally();
1091
+ // ⭐ W53-T01 / R2: a formula DRAGGED down shows its own number rather than its text, and it
1092
+ // reads through the same overlay a paste does — a fill walks top to bottom, so the third cell
1093
+ // of a running total must see the second cell this very fill just wrote.
1094
+ const read = overlayGetter(tab, edits, get);
1095
  for (let row = Math.min(destination.row0, destination.row1);
1096
  row <= Math.max(destination.row0, destination.row1); row += 1) {
1097
  for (let col = Math.min(destination.col0, destination.col1);
 
1135
  edits[addr] = setFormula(
1136
  target,
1137
  fillFormula(pattern.formula ?? "", row - srcRow, col - srcCol),
1138
+ read,
1139
  );
1140
  continue;
1141
  }
web/src/shell/Shell.tsx CHANGED
@@ -31,6 +31,16 @@
31
  // ---------------------------------------------------------------------------
32
 
33
  import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
 
 
 
 
 
 
 
 
 
 
34
  /* ⛔ `import { createPortal } from "react-dom";` STOOD HERE AND IS DELETED (W41-T32). The database
35
  flyout was this file's ONLY portal — checked by the compiler, not by reading: `tsc -b` named it
36
  (TS6133) the moment the panel went, which is the unused-locals check doing the remembering
@@ -78,10 +88,14 @@ import type { SettingsSection } from "../settings/SettingsModal";
78
  import { Brand } from "./Brand";
79
  import { ErrorBoundary } from "./ErrorBoundary";
80
  import LoginPage from "./LoginPage";
81
- import { ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, STARRED_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, hasVisibleRailSlot, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
82
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent } from "./nav";
83
  // ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one.
84
- import { DbIcon, gridScopeFor } from "./dbFrame";
 
 
 
 
85
  /* ⭐ W35-T09 — the app's own star (B-3): one mark, one meaning (DESIGN.md §4). */
86
  import { StarIcon } from "../ui/icons";
87
  // W51-T31 — the shell's overlays join the ONE Escape stack (C8 / DESIGN.md §4). Every
@@ -556,6 +570,11 @@ function ExtIcon() {
556
  looking like the database module, COMPLETELY"* — made them a SECOND surface's too. `gridScopeFor`
557
  is not a move but a fix: the registry key and the grid scope are different spellings, and the map
558
  used to live inline in the native branch below where nothing else could reach it.
 
 
 
 
 
559
  ⛔ `DbHead` MOVED WITH THEM AND IS NOW DELETED (W36-T51, owner item 7 — *"Remove the header for
560
  database completely"*). Its tombstone, and the list of what must NOT be swept away with it, is in
561
  `dbFrame.tsx` where it lived. */
@@ -573,7 +592,7 @@ function DotsIcon() {
573
 
574
  /** WAVE 19 R12 — the gear beside the account menu's one Settings row. Drawn in
575
  * the same 16x16 stroke vocabulary as the rest of this file (SVG, never an
576
- * emoji — the platform's own rule), so it sits beside `DbIcon` and `SparkIcon`
577
  * as one family rather than as an icon borrowed from somewhere else. */
578
  function GearIcon() {
579
  return (
@@ -622,8 +641,10 @@ function BubbleIcon() {
622
  * needle touches the arc and the two merge into one stroke at 16px;
623
  * · a COIN WITH A RIM (two concentric circles) — reads as a bullseye, and it is the loudest
624
  * mark in the menu;
625
- * · a COIN STACK — that is `dbFrame.tsx::DbIcon`. The app already spends that shape on
626
- * "database", and one mark may mean one thing (DESIGN.md §4);
 
 
627
  * · a WALLET — reads as a battery;
628
  * · a gauge WITH A HUB — better than the first, still optically thin beside the gear.
629
  * The pie won on legibility and on weight: a closed circle sits at the same optical weight as
@@ -670,11 +691,15 @@ function ExitIcon() {
670
  ⚠ THAT SENTENCE IS STALE AND W51-T30 CORRECTS IT RATHER THAN LEAVING IT TO ROT. It read *"NOT
671
  the same mark as the rail's `RobotIcon`, which SURVIVES and is what owner item 5 asked for. Two
672
  glyphs, two jobs; only the header's is retired."* The rail's robot is gone too now (R15, wave
673
- 51) and the rail draws `FlowIcon` — a two-node flow glyph, which is the SAME FAMILY of mark this
674
  header one was.
675
- ⛔ THAT IS NOT A LICENCE TO BRING THIS ONE BACK. `AutoIcon` belonged to a HEADER that no longer
676
- exists, at header geometry; `FlowIcon` is drawn fresh below in the rail's own 16x16 vocabulary
677
- and is the only flow mark in this file. Resurrecting `AutoIcon` would give the module two. */
 
 
 
 
678
 
679
  /* ⭐ `BellIcon` LIVED HERE AND IS DELETED (wave 34, R15) — AND THAT DELETION CLOSES `D-207`.
680
  The Inbox row took `MailIcon`, leaving this local copy with no call site. D-207 records that
@@ -721,33 +746,18 @@ function MailIcon() {
721
  );
722
  }
723
 
724
- /** ⭐⭐ WAVE 51 · T30 (R15) — the Agents row's mark: TWO ROUNDED NODES JOINED BY ONE EDGE.
725
- *
726
- * ⛔ IT REPLACES `RobotIcon`, WHICH IS DELETED, and the swap is about what the row OPENS, not
727
- * about a nicer drawing. R15 was chosen over a cleaner robot and over a sparkles glyph: a robot
728
- * says "a machine did this", which is the least specific true thing about the page. An agent here
729
- * IS a flow — a step, an edge, the next step — so the mark states the module's shape instead of
730
- * its vibe, and it stops reading as the generic AI badge every other product now wears.
731
- *
732
- * Geometry follows `iconShapes.ts`'s standing rule even though this file is not that module:
733
- * 16x16 box, stroke-only, round caps, `currentColor`, vector paths — NEVER emoji (owner constant).
734
- * ⚠ THE NODES ARE OUTLINED, NOT SOLID, and that is inherited scar tissue rather than taste: the
735
- * robot's own note recorded that a FILLED badge "blooms darker than its neighbours", so a filled
736
- * pair here would break the same column. Weight and paint both come from `.shell-nav-icon` — this
737
- * glyph declares no `stroke-width` and no `fill` of its own, which is the only way it stays level
738
- * with `HomeIcon`, `PlugIcon` and `SheetIcon` when the rail's weight is next retuned.
739
- * The two nodes sit at 180° rotation about the box centre and the edge leaves the upper node's
740
- * bottom centre for the lower node's left edge, so the mark is balanced at 16px rather than
741
- * leaning into one corner. */
742
- function FlowIcon() {
743
- return (
744
- <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
745
- <rect x="1.9" y="2.2" width="5.4" height="4.4" rx="1.1" />
746
- <rect x="8.7" y="9.4" width="5.4" height="4.4" rx="1.1" />
747
- <path d="M4.6 6.6v3.6a1.4 1.4 0 0 0 1.4 1.4h2.7" />
748
- </svg>
749
- );
750
- }
751
 
752
  /** ⭐⭐ WAVE 35 · T04 (owner item 5) — AN ACTUAL PLUG. Owner: *"change the Icon for the connector to
753
  * look like the cable head that you would put in an electrical outlet."*
@@ -774,8 +784,10 @@ function PlugIcon() {
774
  * rules across and two down, which is the shortest mark that reads as a spreadsheet rather than
775
  * as a table or a window at 16px. Same 16x16 / `currentColor` / 1.35 vocabulary as every other
776
  * rail mark, so it sits in the column without redrawing the row's weight.
777
- * ⚠ ITS OWN GLYPH, NOT `DbIcon`'s CYLINDER: Sheet stands at the head of the data band and beside
778
- * Data, and two rows wearing one mark is how a reader stops believing the marks mean anything. */
 
 
779
  function SheetIcon() {
780
  return (
781
  <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
@@ -1040,6 +1052,40 @@ export default function Shell() {
1040
  );
1041
  }
1042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1043
  function ShellFrame() {
1044
  const [session, setSession] = useState<Session>({ phase: "checking" });
1045
  const [nav, setNav] = useState<Nav>({ phase: "idle" });
@@ -1130,16 +1176,25 @@ function ShellFrame() {
1130
  // Owner items 10/11 — the navigation folds to a slim strip: by the toggle in the rail head,
1131
  // or automatically when the user clicks into the work surface (NAV_MINIMIZE_EVENT from the
1132
  // grid). Remembered per browser; expanding is always one click on the same toggle.
1133
- const [navCollapsed, setNavCollapsed] = useState<boolean>(() => {
1134
- try {
1135
- return localStorage.getItem("aios-nav-collapsed") === "1";
1136
- } catch {
1137
- return false;
1138
- }
1139
- });
 
 
 
 
 
 
 
1140
  useEffect(() => {
1141
  try {
1142
- localStorage.setItem("aios-nav-collapsed", navCollapsed ? "1" : "0");
 
 
1143
  } catch {
1144
  // storage can be blocked; the toggle still works for the session
1145
  }
@@ -1168,7 +1223,30 @@ function ShellFrame() {
1168
  /** Every deliberate expand goes through here, so a fifth expand door cannot be added quietly. */
1169
  const expandRail = useCallback(() => {
1170
  setNavCollapsed(false);
 
1171
  }, []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1172
  // Owner item 3 (2026-07-31) — the collapsed strip names its icons on hover. A real DOM
1173
  // tooltip positioned FIXED beside the rail: the rail scrolls and clips (overflow), so a
1174
  // CSS ::after inside it could never escape; and it is pointer-events:none by standing rule
@@ -1249,6 +1327,11 @@ function ShellFrame() {
1249
  /** A folded rail is always the global rail, never a squeezed database path. */
1250
  const collapseRail = useCallback(() => {
1251
  setNavCollapsed(true);
 
 
 
 
 
1252
  }, []);
1253
  /** Drill into the database list. RESUMES the walk rather than restarting it — see `closeDbFly`. */
1254
  /** Drill from the list into ONE database. The row's own `href` does the navigating; this records
@@ -1292,16 +1375,6 @@ function ShellFrame() {
1292
  const onDataError = (e: Event) =>
1293
  setDataError(String((e as CustomEvent).detail ?? "") || "The data could not be loaded.");
1294
  const onToast = (e: Event) => setToast(String((e as CustomEvent).detail ?? ""));
1295
- // ⭐⭐ W38-T04 (R9) — THE AUTOMATIC FOLD IS UNCONDITIONAL, AND THAT IS THE WHOLE RULE.
1296
- // `NAV_MINIMIZE_EVENT` fires from `CustomerGrid` on EVERY cell click and EVERY view switch;
1297
- // this is its only listener, and it folds, every time, with nothing in front of it. W34-T12's
1298
- // `railHeldOpen` guard stood here and is deleted (see the block by `expandRail` for why the
1299
- // ref went with it). ⛔ ANY early return, condition or stored preference added between this
1300
- // line and the fold re-creates the behaviour owner item 3 asked to be fixed FOREVER — and
1301
- // `verify_ui.py`'s `W38-T04 unconditional` leg exists to go red the moment one appears.
1302
- const onNavMinimize = () => {
1303
- collapseRail();
1304
- };
1305
  // C-SHARE: the rail asks, the frame opens. A malformed detail opens NOTHING —
1306
  // `parseShareRequest` fail-closes on an unknown kind rather than launching a
1307
  // dialog whose every save would 400.
@@ -1310,16 +1383,94 @@ function ShellFrame() {
1310
  window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
1311
  window.addEventListener(DATA_ERROR_EVENT, onDataError);
1312
  window.addEventListener(TOAST_EVENT, onToast);
1313
- window.addEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
1314
  window.addEventListener(SHARE_OPEN_EVENT, onShareOpen);
1315
  return () => {
1316
  window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
1317
  window.removeEventListener(DATA_ERROR_EVENT, onDataError);
1318
  window.removeEventListener(TOAST_EVENT, onToast);
1319
- window.removeEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
1320
  window.removeEventListener(SHARE_OPEN_EVENT, onShareOpen);
1321
  };
1322
- }, [collapseRail]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1323
 
1324
  // The toast clears itself; nothing else depends on it having been seen.
1325
  useEffect(() => {
@@ -2307,6 +2458,7 @@ function ShellFrame() {
2307
  <a
2308
  className={"shell-nav-item shell-nav-home" + (route === HOME_ROUTE ? " is-active" : "")}
2309
  href={`#/${HOME_ROUTE}`}
 
2310
  onMouseEnter={navCollapsed ? tipEnter("Home") : undefined}
2311
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2312
  >
@@ -2329,6 +2481,7 @@ function ShellFrame() {
2329
  "shell-nav-item shell-nav-starred" + (route === STARRED_ROUTE ? " is-active" : "")
2330
  }
2331
  href={`#/${STARRED_ROUTE}`}
 
2332
  onMouseEnter={navCollapsed ? tipEnter("Starred") : undefined}
2333
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2334
  >
@@ -2350,6 +2503,7 @@ function ShellFrame() {
2350
  <a
2351
  className={"shell-nav-item shell-nav-alerts" + (route === INBOX_ROUTE ? " is-active" : "")}
2352
  href={`#/${INBOX_ROUTE}`}
 
2353
  onMouseEnter={navCollapsed ? tipEnter("Inbox") : undefined}
2354
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2355
  >
@@ -2402,6 +2556,7 @@ function ShellFrame() {
2402
  (route === ASSISTANT_ROUTE ? " is-active" : "")
2403
  }
2404
  onClick={() => {
 
2405
  window.location.hash = `#/${ASSISTANT_ROUTE}`;
2406
  }}
2407
  onMouseEnter={navCollapsed ? tipEnter("Assistant") : undefined}
@@ -2473,6 +2628,7 @@ function ShellFrame() {
2473
  (active && active.key === automation.key ? " is-active" : "")
2474
  }
2475
  href={automation.href}
 
2476
  onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
2477
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2478
  >
@@ -2492,7 +2648,7 @@ function ShellFrame() {
2492
  Agents is a MODULE — a fixed rail row like Home or Connectors — and a module's
2493
  glyph is the product's, not the tenant's. `FolderMark` is still how every real
2494
  database draws its chosen mark. */}
2495
- <FlowIcon />
2496
  <span className="shell-nav-label">{automation.label}</span>
2497
  </a>
2498
  ) : automationSlot === "unavailable" ? (
@@ -2507,7 +2663,7 @@ function ShellFrame() {
2507
  : "This list could not be loaded in full. Reload to retry."
2508
  }
2509
  >
2510
- <FlowIcon />
2511
  <span className="shell-nav-label shell-nav-label--muted">Agents</span>
2512
  <span className="shell-nav-note-dot" aria-hidden="true" />
2513
  </div>
@@ -2547,6 +2703,7 @@ function ShellFrame() {
2547
  (route === SHEET_ROUTE ? " is-active" : "")
2548
  }
2549
  href={`#/${SHEET_ROUTE}`}
 
2550
  onMouseEnter={navCollapsed ? tipEnter("Sheet") : undefined}
2551
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2552
  >
@@ -2581,14 +2738,17 @@ function ShellFrame() {
2581
  onMouseEnter={navCollapsed ? tipEnter("Data") : undefined}
2582
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2583
  onClick={() => {
2584
- if (navCollapsed) expandRail();
 
 
 
2585
  if (dbAt) return;
2586
  const firstDatabase = dataDatabases.find((database) => !database.externalHref);
2587
  if (firstDatabase) selectDatabase(firstDatabase.key);
2588
  else openNewDb("blank");
2589
  }}
2590
  >
2591
- <DbIcon />
2592
  {/* ⭐⭐ W41-T32 (R2) — "Database" BECOMES "Data". Owner instruction 29, in passing:
2593
  *"when a user click on a Database (let's rename it to Data)"*.
2594
  ⛔ THE LABEL ONLY. The route key, the class `shell-nav-db` and every selector that
@@ -2611,6 +2771,7 @@ function ShellFrame() {
2611
  (route === CONNECTORS_ROUTE ? " is-active" : "")
2612
  }
2613
  href={`#/${CONNECTORS_ROUTE}`}
 
2614
  onMouseEnter={navCollapsed ? tipEnter("Connectors") : undefined}
2615
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2616
  >
@@ -2684,7 +2845,12 @@ function ShellFrame() {
2684
  // settle, and whose acceptance test is "THE RAIL PAINTS ONCE", never "the spinner is
2685
  // gone". [[a-rail-must-paint-once]]
2686
  className={"shell-nav-item shell-nav-templates" + (railLoading ? " is-rail-hidden" : "")}
2687
- onClick={() => setAssistOpen("templates")}
 
 
 
 
 
2688
  onMouseEnter={navCollapsed ? tipEnter("Templates") : undefined}
2689
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2690
  >
 
31
  // ---------------------------------------------------------------------------
32
 
33
  import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
34
+ /* ⭐ W53-T34 / contract C4 — the shell's glyphs live in ONE file now. See the tombstone where
35
+ `FlowIcon` used to be drawn, further down. */
36
+ import { AgentIcon, DatabaseIcon } from "./icons";
37
+ // ⭐ W53-T35 / C4 — the shell's own sheet, imported here the way `NavExtras.tsx` imports
38
+ // `navExtras.css`. It carries the one rule that keeps the DATABASE mark out of the folder
39
+ // fill (`styles/wave45/data-applications.css` paints every `.cg-folder-mark path` brand
40
+ // purple, which is right for a folder and is owner instruction 26's complaint for a
41
+ // database). It is scoped by two classes, so it wins on specificity and does not rest on
42
+ // import order — the sheet it overrides ships in a lazy chunk.
43
+ import "./shell.css";
44
  /* ⛔ `import { createPortal } from "react-dom";` STOOD HERE AND IS DELETED (W41-T32). The database
45
  flyout was this file's ONLY portal — checked by the compiler, not by reading: `tsc -b` named it
46
  (TS6133) the moment the panel went, which is the unused-locals check doing the remembering
 
88
  import { Brand } from "./Brand";
89
  import { ErrorBoundary } from "./ErrorBoundary";
90
  import LoginPage from "./LoginPage";
91
+ import { ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, STARRED_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, hasVisibleRailSlot, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
92
  import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent } from "./nav";
93
  // ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one.
94
+ // ⛔ W53-T35 — `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears `icons.tsx::DatabaseIcon`
95
+ // (owner instruction 26: the Home page's cylinder is the correct one), and `dbFrame.tsx` keeps
96
+ // exporting `DbIcon` for `query/queryParts.tsx`, which still draws the coin stack. Only
97
+ // `gridScopeFor` is read from this module now.
98
+ import { gridScopeFor } from "./dbFrame";
99
  /* ⭐ W35-T09 — the app's own star (B-3): one mark, one meaning (DESIGN.md §4). */
100
  import { StarIcon } from "../ui/icons";
101
  // W51-T31 — the shell's overlays join the ONE Escape stack (C8 / DESIGN.md §4). Every
 
570
  looking like the database module, COMPLETELY"* — made them a SECOND surface's too. `gridScopeFor`
571
  is not a move but a fix: the registry key and the grid scope are different spellings, and the map
572
  used to live inline in the native branch below where nothing else could reach it.
573
+ ⛔ W53-T35 — THIS FILE NO LONGER DRAWS `DbIcon`. Owner instruction 26 standardised the database
574
+ mark on the Home page's outline cylinder, so the Data rail row renders
575
+ `shell/icons.tsx::DatabaseIcon` and only `gridScopeFor` is still imported from `dbFrame.tsx`.
576
+ `DbIcon` stays exported there because `query/queryParts.tsx` still mounts it; if that surface is
577
+ standardised too, it points at `icons.tsx` and `dbFrame.tsx`'s copy goes.
578
  ⛔ `DbHead` MOVED WITH THEM AND IS NOW DELETED (W36-T51, owner item 7 — *"Remove the header for
579
  database completely"*). Its tombstone, and the list of what must NOT be swept away with it, is in
580
  `dbFrame.tsx` where it lived. */
 
592
 
593
  /** WAVE 19 R12 — the gear beside the account menu's one Settings row. Drawn in
594
  * the same 16x16 stroke vocabulary as the rest of this file (SVG, never an
595
+ * emoji — the platform's own rule), so it sits beside `DatabaseIcon` and `SparkIcon`
596
  * as one family rather than as an icon borrowed from somewhere else. */
597
  function GearIcon() {
598
  return (
 
641
  * needle touches the arc and the two merge into one stroke at 16px;
642
  * · a COIN WITH A RIM (two concentric circles) — reads as a bullseye, and it is the loudest
643
  * mark in the menu;
644
+ * · a COIN STACK — that WAS this rail's database mark (`dbFrame.tsx::DbIcon`), and the
645
+ * argument stands under W53-T35's replacement: the shape is still spent on "database"
646
+ * (now as `icons.tsx::DatabaseIcon`'s cylinder here, and as `DbIcon` on Query), and one
647
+ * mark may mean one thing (DESIGN.md §4);
648
  * · a WALLET — reads as a battery;
649
  * · a gauge WITH A HUB — better than the first, still optically thin beside the gear.
650
  * The pie won on legibility and on weight: a closed circle sits at the same optical weight as
 
691
  ⚠ THAT SENTENCE IS STALE AND W51-T30 CORRECTS IT RATHER THAN LEAVING IT TO ROT. It read *"NOT
692
  the same mark as the rail's `RobotIcon`, which SURVIVES and is what owner item 5 asked for. Two
693
  glyphs, two jobs; only the header's is retired."* The rail's robot is gone too now (R15, wave
694
+ 51) and the rail drew `FlowIcon` — a two-node flow glyph, which was the SAME FAMILY of mark this
695
  header one was.
696
+ ⚠ THAT PARAGRAPH IS STALE IN ITS TURN AND W53-T34 CORRECTS IT RATHER THAN LEAVING IT TO ROT:
697
+ `FlowIcon` IS GONE TOO (owner instruction 4), and there is no flow mark anywhere in the shell
698
+ any more. The rail now draws `shell/icons.tsx::AgentIcon`, a square with two eyes.
699
+ ⛔ THAT IS NOT A LICENCE TO BRING THIS ONE BACK — it is the opposite. `AutoIcon` belonged to a
700
+ HEADER that no longer exists, at header geometry, and its family of mark has now been rejected
701
+ by the owner on the rail. Resurrecting it would re-open a settled question with a glyph nobody
702
+ asked for. */
703
 
704
  /* ⭐ `BellIcon` LIVED HERE AND IS DELETED (wave 34, R15) — AND THAT DELETION CLOSES `D-207`.
705
  The Inbox row took `MailIcon`, leaving this local copy with no call site. D-207 records that
 
746
  );
747
  }
748
 
749
+ /* ⛔ `FlowIcon` LIVED HERE AND IS GONE TWICE OVER (W53-T34, owner instruction 4). It was the
750
+ two-node flow glyph wave 51 drew for the Agents row, and it has moved AND been redrawn in the
751
+ same edit, so neither half of that is a search anyone should have to run:
752
+ · MOVED — every shell glyph now lives in `shell/icons.tsx` (contract C4), because the
753
+ database cylinder was being hand-copied across three files and the copy nobody edits is the
754
+ one a reader sees. The mark this row mounts is imported at the top of this file.
755
+ · REDRAWN — owner instruction 4: *"Agent module icon is still ugly. How about just make it
756
+ square and have two dots in side that looks like an eye."* `shell/icons.tsx::AgentIcon` is
757
+ that square, and its own comment carries why the flow argument lost at 16px.
758
+ ⛔ AND `RobotIcon`, WHICH `FlowIcon` REPLACED IN WAVE 51 (R15), STAYS DELETED. Two glyphs have
759
+ now been retired from this one row; the next person to dislike the mark should draw a third,
760
+ not resurrect either. `verify_icons.py` fails on a `RobotIcon` in code, by name. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
761
 
762
  /** ⭐⭐ WAVE 35 · T04 (owner item 5) — AN ACTUAL PLUG. Owner: *"change the Icon for the connector to
763
  * look like the cable head that you would put in an electrical outlet."*
 
784
  * rules across and two down, which is the shortest mark that reads as a spreadsheet rather than
785
  * as a table or a window at 16px. Same 16x16 / `currentColor` / 1.35 vocabulary as every other
786
  * rail mark, so it sits in the column without redrawing the row's weight.
787
+ * ⚠ ITS OWN GLYPH, NOT THE DATABASE CYLINDER (`icons.tsx::DatabaseIcon` since W53-T35; it was
788
+ * `dbFrame.tsx::DbIcon` when this was written): Sheet stands at the head of the data band and
789
+ * beside Data, and two rows wearing one mark is how a reader stops believing the marks mean
790
+ * anything. */
791
  function SheetIcon() {
792
  return (
793
  <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
 
1052
  );
1053
  }
1054
 
1055
+ /** How the rail came to be folded, as persisted in `aios-nav-collapsed`. */
1056
+ type NavFold = "0" | "1" | "auto";
1057
+
1058
+ /** The one key both halves of the fold read and write. */
1059
+ const NAV_FOLD_KEY = "aios-nav-collapsed";
1060
+
1061
+ /**
1062
+ * ⭐⭐ WAVE 53 · T32 (ruling R1) — WHO FOLDED THE RAIL, not merely whether it is folded.
1063
+ *
1064
+ * The stored value used to be a boolean, and that is exactly why owner instruction 3 had to be
1065
+ * written: a rail the GRID folded on a cell click was indistinguishable from a rail the READER
1066
+ * folded with the minimize button, so the grid's fold followed you to Home and survived the next
1067
+ * app open. Three values keep them apart:
1068
+ * `"0"` the rail is open.
1069
+ * `"1"` the reader folded it themselves. A choice, and it holds everywhere, Home included.
1070
+ * `"auto"` the work surface folded it (`NAV_MINIMIZE_EVENT`). Still folded, still remembered,
1071
+ * but it is the surface's fold and it does not outlive that surface.
1072
+ *
1073
+ * ⚠ `"1"` IS READ BY THE OLD SPELLING TOO, and that is not an accident: every browser that has
1074
+ * opened this app before today holds a literal `"1"`, and treating it as an explicit fold is the
1075
+ * kinder reading of an unknowable one. Anything that is not `"0"` means folded, so a value this
1076
+ * function has never heard of still fails safe as folded rather than silently opening the rail.
1077
+ */
1078
+ function readNavFold(): NavFold {
1079
+ try {
1080
+ const raw = localStorage.getItem(NAV_FOLD_KEY);
1081
+ if (raw === "auto") return "auto";
1082
+ return raw === "1" ? "1" : "0";
1083
+ } catch {
1084
+ // storage can be blocked; the rail then simply starts open, as it does for a new reader
1085
+ return "0";
1086
+ }
1087
+ }
1088
+
1089
  function ShellFrame() {
1090
  const [session, setSession] = useState<Session>({ phase: "checking" });
1091
  const [nav, setNav] = useState<Nav>({ phase: "idle" });
 
1176
  // Owner items 10/11 — the navigation folds to a slim strip: by the toggle in the rail head,
1177
  // or automatically when the user clicks into the work surface (NAV_MINIMIZE_EVENT from the
1178
  // grid). Remembered per browser; expanding is always one click on the same toggle.
1179
+ const [navCollapsed, setNavCollapsed] = useState<boolean>(() => readNavFold() !== "0");
1180
+ /**
1181
+ * ⭐⭐ W53-T32 (R1) — was the fold on screen the SURFACE's or the READER's? A ref, not state,
1182
+ * because it is read by the effects below at the moment they run and never by the render: a
1183
+ * re-render standing between the fold and the write is precisely what would let the flag and
1184
+ * `navCollapsed` disagree about the same fold.
1185
+ *
1186
+ * ⚠ Seeded from `readNavFold()`, the SAME reader that seeds `navCollapsed` one line above, so
1187
+ * the two cannot start out describing different histories. Lazy-initialised (`null` until the
1188
+ * first render asks) rather than passed to `useRef` directly, which would re-read storage on
1189
+ * every render of the largest component in the app for a value that can only change here.
1190
+ */
1191
+ const navFoldWasAuto = useRef<boolean | null>(null);
1192
+ if (navFoldWasAuto.current === null) navFoldWasAuto.current = readNavFold() === "auto";
1193
  useEffect(() => {
1194
  try {
1195
+ // ⚠ The WHO, not just the whether — see `readNavFold`. An automatic fold that wrote `"1"`
1196
+ // here would be an explicit fold as far as tomorrow's app open could tell.
1197
+ localStorage.setItem(NAV_FOLD_KEY, navCollapsed ? (navFoldWasAuto.current ? "auto" : "1") : "0");
1198
  } catch {
1199
  // storage can be blocked; the toggle still works for the session
1200
  }
 
1223
  /** Every deliberate expand goes through here, so a fifth expand door cannot be added quietly. */
1224
  const expandRail = useCallback(() => {
1225
  setNavCollapsed(false);
1226
+ navFoldWasAuto.current = false;
1227
  }, []);
1228
+ /**
1229
+ * ⭐⭐ W53-T33 (owner instruction 6) — A RAIL ICON OPENS ITS MODULE **AND** OPENS THE RAIL.
1230
+ *
1231
+ * Owner: *"When clicking any of the icon under a minimized main navigation ... we should not
1232
+ * only open that module, but also unminimized the main navigation. Only when the user click
1233
+ * anywhere in the module like it is wired right now should the main navigation be minimized
1234
+ * again."* So this is an EXPAND-ONLY handler: it never collapses, and `onNavMinimize` keeps
1235
+ * owning the click-into-the-module fold exactly as before.
1236
+ *
1237
+ * ⛔ ONE HANDLER, NOT NINE INLINE COPIES, AND IT GOES THROUGH `expandRail` — the one door.
1238
+ * `verify_ui.py` counts every setter call site and reddens on a third one, which
1239
+ * is what stops a rail row from growing its own private expand. Rows that are plain `<a href>`
1240
+ * simply add `onClick={expandOnNavClick}`; the two rows that already own an `onClick` call it as
1241
+ * their first statement, so navigation and expansion cannot answer differently.
1242
+ *
1243
+ * ⚠ The `navCollapsed` guard is not decoration: an unguarded `expandRail()` would clear
1244
+ * `navFoldWasAuto` on every rail click in the EXPANDED state too, which is the flag the
1245
+ * auto-fold logic reads.
1246
+ */
1247
+ const expandOnNavClick = useCallback(() => {
1248
+ if (navCollapsed) expandRail();
1249
+ }, [navCollapsed, expandRail]);
1250
  // Owner item 3 (2026-07-31) — the collapsed strip names its icons on hover. A real DOM
1251
  // tooltip positioned FIXED beside the rail: the rail scrolls and clips (overflow), so a
1252
  // CSS ::after inside it could never escape; and it is pointer-events:none by standing rule
 
1327
  /** A folded rail is always the global rail, never a squeezed database path. */
1328
  const collapseRail = useCallback(() => {
1329
  setNavCollapsed(true);
1330
+ // ⭐ W53-T32 (R1) — a fold arriving through this door is the READER's until something says
1331
+ // otherwise, and the only thing that says otherwise is the `NAV_MINIMIZE_EVENT` handler, on
1332
+ // the line straight after its own `collapseRail()`. Clearing it here rather than in the
1333
+ // minimize button's own handler keeps the count of `setNavCollapsed` call sites at two.
1334
+ navFoldWasAuto.current = false;
1335
  }, []);
1336
  /** Drill into the database list. RESUMES the walk rather than restarting it — see `closeDbFly`. */
1337
  /** Drill from the list into ONE database. The row's own `href` does the navigating; this records
 
1375
  const onDataError = (e: Event) =>
1376
  setDataError(String((e as CustomEvent).detail ?? "") || "The data could not be loaded.");
1377
  const onToast = (e: Event) => setToast(String((e as CustomEvent).detail ?? ""));
 
 
 
 
 
 
 
 
 
 
1378
  // C-SHARE: the rail asks, the frame opens. A malformed detail opens NOTHING —
1379
  // `parseShareRequest` fail-closes on an unknown kind rather than launching a
1380
  // dialog whose every save would 400.
 
1383
  window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
1384
  window.addEventListener(DATA_ERROR_EVENT, onDataError);
1385
  window.addEventListener(TOAST_EVENT, onToast);
 
1386
  window.addEventListener(SHARE_OPEN_EVENT, onShareOpen);
1387
  return () => {
1388
  window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
1389
  window.removeEventListener(DATA_ERROR_EVENT, onDataError);
1390
  window.removeEventListener(TOAST_EVENT, onToast);
 
1391
  window.removeEventListener(SHARE_OPEN_EVENT, onShareOpen);
1392
  };
1393
+ }, []);
1394
+
1395
+ // ── ⭐⭐ W53-T32 (ruling R1): THE FOLD IS NOT SUBSCRIBED TO ON A READING SURFACE ─────────
1396
+ //
1397
+ // Owner instruction 3: *"Never collapse on home or starred UNLESS the user click the minmize
1398
+ // navigation button of course. Also apply this for inbox module."*
1399
+ //
1400
+ // ⛔ W38-T04 IS UNTOUCHED, AND THAT IS THE WHOLE REASON THIS IS AN EFFECT RATHER THAN A GUARD.
1401
+ // R9 says the automatic fold may never be declined, and the handler below still declines
1402
+ // nothing: it folds the moment it hears the event, with nothing in front of it. What R1 changes
1403
+ // is not what the handler does, it is whether the handler is LISTENING at all. On Home, Starred
1404
+ // and Inbox this effect leaves before it subscribes, so no event reaches a handler that could
1405
+ // have folded. Leaving one of those routes re-runs the effect and re-attaches the listener, so
1406
+ // Data, Sheet and Connectors keep the wave-38 behaviour exactly, cell click for cell click.
1407
+ //
1408
+ // ⚠ A guard in front of `collapseRail()` would have been the OTHER way to write this, and it
1409
+ // is the one wave 38 forbade: `verify_ui.py`'s `W38-T04 unconditional` leg reads the 500
1410
+ // characters after the handler's own name and goes red on any `if`, `return`, `&&`, `||` or
1411
+ // `localStorage` standing before the fold. The condition belongs to the SUBSCRIPTION, one scope
1412
+ // out, which is also the honest place for it: these three pages never had anything to fold for.
1413
+ useEffect(() => {
1414
+ if (NAV_STAYS_EXPANDED_ROUTES.has(route)) return;
1415
+ // ⭐⭐ W38-T04 (R9) — THE AUTOMATIC FOLD IS UNCONDITIONAL, AND THAT IS THE WHOLE RULE.
1416
+ // `NAV_MINIMIZE_EVENT` fires from `CustomerGrid` on EVERY cell click and EVERY view switch;
1417
+ // this is its only listener, and it folds, every time, with nothing in front of it. W34-T12's
1418
+ // `railHeldOpen` guard stood here and is deleted (see the block by `expandRail` for why the
1419
+ // ref went with it). ⛔ ANY early return, condition or stored preference added between this
1420
+ // line and the fold re-creates the behaviour owner item 3 asked to be fixed FOREVER — and
1421
+ // `verify_ui.py`'s `W38-T04 unconditional` leg exists to go red the moment one appears.
1422
+ const onNavMinimize = () => {
1423
+ collapseRail();
1424
+ // ⭐ W53-T32 (R1) — AFTER the fold, never before it: this line records that the fold
1425
+ // was the surface's rather than the reader's, and a line standing in FRONT of
1426
+ // `collapseRail()` is the declining guard R9 revoked. `collapseRail` clears this flag
1427
+ // as its own last statement, so the order here is what makes the automatic fold
1428
+ // distinguishable from the minimize button pressing the same door one instruction later.
1429
+ navFoldWasAuto.current = true;
1430
+ };
1431
+ window.addEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
1432
+ return () => window.removeEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
1433
+ }, [collapseRail, route]);
1434
+
1435
+ // ── ⭐⭐ W53-T32 (ruling R1): AN AUTOMATIC FOLD DOES NOT OUTLIVE THE SURFACE THAT MADE IT ──
1436
+ //
1437
+ // The other half of instruction 3, and the half that is visible on a cold start: *"When user
1438
+ // first open the app and they're at home. Make sure the navigation is unminimized."* Not
1439
+ // subscribing is not enough on its own, because `navCollapsed` is ONE persisted flag: a rail the
1440
+ // grid folded on a Data cell click is still folded when you arrive at Home, and still folded on
1441
+ // the next app open, which is the fold owner instruction 3 says must not be there.
1442
+ //
1443
+ // So the fold is undone at the door, and ONLY the automatic one. `"1"` — the reader's own
1444
+ // minimize — walks straight past this and stays folded on Home, which is the *"UNLESS the user
1445
+ // click the minmize navigation button"* clause honoured rather than merely quoted.
1446
+ //
1447
+ // ⚠ `expandRail` IS THE DOOR, not `setNavCollapsed`. W34-T12's one-door rule survives R9 and is
1448
+ // gated, and this is the fourth control to go through it rather than the fifth to go around.
1449
+ //
1450
+ // ⛔ THE REF ALONE IS NOT ENOUGH, AND THE CASE THAT PROVES IT IS THE READER'S OWN FOLD. When
1451
+ // `collapseRail()` folds a rail that is ALREADY folded — the reader minimized it, then clicked a
1452
+ // Data cell — `navCollapsed` does not change, so the persistence effect never re-runs and storage
1453
+ // KEEPS the `"1"` the reader put there, while the handler's next line has already marked the ref
1454
+ // automatic. Storage is the record that did not move, which makes it the honest arbiter of who
1455
+ // folded the rail currently on screen: an explicit `"1"` is never reopened here, so *"UNLESS the
1456
+ // user click the minmize navigation button"* holds across a trip through a work surface too.
1457
+ //
1458
+ // ⚠ THE REF STAYS IN THE TEST rather than being replaced by the read. A browser with site data
1459
+ // blocked answers `"0"` to every `readNavFold()`, and a test on storage alone would then refuse
1460
+ // to reopen anything — leaving the rail folded on Home for exactly the readers who cannot
1461
+ // persist a preference in the first place. Ref says "an automatic fold happened"; storage says
1462
+ // "and the reader did not fold it first"; both have to agree before the rail is reopened.
1463
+ //
1464
+ // ⚠ `localStorage` IS LEGAL HERE and moving this read is what would break the gate, not keeping
1465
+ // it. `verify_ui.py`'s `W38-T04 unconditional` leg bans it only in the 500 characters after
1466
+ // `const onNavMinimize` and before that handler's own `collapseRail()`. This is a different
1467
+ // scope and a different question: not whether to fold, but whether an old fold still speaks for
1468
+ // the reader.
1469
+ useEffect(() => {
1470
+ if (!NAV_STAYS_EXPANDED_ROUTES.has(route)) return;
1471
+ if (!navCollapsed || !navFoldWasAuto.current || readNavFold() === "1") return;
1472
+ expandRail();
1473
+ }, [route, navCollapsed, expandRail]);
1474
 
1475
  // The toast clears itself; nothing else depends on it having been seen.
1476
  useEffect(() => {
 
2458
  <a
2459
  className={"shell-nav-item shell-nav-home" + (route === HOME_ROUTE ? " is-active" : "")}
2460
  href={`#/${HOME_ROUTE}`}
2461
+ onClick={expandOnNavClick}
2462
  onMouseEnter={navCollapsed ? tipEnter("Home") : undefined}
2463
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2464
  >
 
2481
  "shell-nav-item shell-nav-starred" + (route === STARRED_ROUTE ? " is-active" : "")
2482
  }
2483
  href={`#/${STARRED_ROUTE}`}
2484
+ onClick={expandOnNavClick}
2485
  onMouseEnter={navCollapsed ? tipEnter("Starred") : undefined}
2486
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2487
  >
 
2503
  <a
2504
  className={"shell-nav-item shell-nav-alerts" + (route === INBOX_ROUTE ? " is-active" : "")}
2505
  href={`#/${INBOX_ROUTE}`}
2506
+ onClick={expandOnNavClick}
2507
  onMouseEnter={navCollapsed ? tipEnter("Inbox") : undefined}
2508
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2509
  >
 
2556
  (route === ASSISTANT_ROUTE ? " is-active" : "")
2557
  }
2558
  onClick={() => {
2559
+ expandOnNavClick();
2560
  window.location.hash = `#/${ASSISTANT_ROUTE}`;
2561
  }}
2562
  onMouseEnter={navCollapsed ? tipEnter("Assistant") : undefined}
 
2628
  (active && active.key === automation.key ? " is-active" : "")
2629
  }
2630
  href={automation.href}
2631
+ onClick={expandOnNavClick}
2632
  onMouseEnter={navCollapsed ? tipEnter(automation.label) : undefined}
2633
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2634
  >
 
2648
  Agents is a MODULE — a fixed rail row like Home or Connectors — and a module's
2649
  glyph is the product's, not the tenant's. `FolderMark` is still how every real
2650
  database draws its chosen mark. */}
2651
+ <AgentIcon />
2652
  <span className="shell-nav-label">{automation.label}</span>
2653
  </a>
2654
  ) : automationSlot === "unavailable" ? (
 
2663
  : "This list could not be loaded in full. Reload to retry."
2664
  }
2665
  >
2666
+ <AgentIcon />
2667
  <span className="shell-nav-label shell-nav-label--muted">Agents</span>
2668
  <span className="shell-nav-note-dot" aria-hidden="true" />
2669
  </div>
 
2703
  (route === SHEET_ROUTE ? " is-active" : "")
2704
  }
2705
  href={`#/${SHEET_ROUTE}`}
2706
+ onClick={expandOnNavClick}
2707
  onMouseEnter={navCollapsed ? tipEnter("Sheet") : undefined}
2708
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2709
  >
 
2738
  onMouseEnter={navCollapsed ? tipEnter("Data") : undefined}
2739
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2740
  onClick={() => {
2741
+ // W53-T33 — was `if (navCollapsed) expandRail();`. Same behaviour, one owner: this
2742
+ // row was the ONLY one that already expanded, and instruction 6 makes that rule the
2743
+ // whole rail's, so the rule lives in `expandOnNavClick` rather than here.
2744
+ expandOnNavClick();
2745
  if (dbAt) return;
2746
  const firstDatabase = dataDatabases.find((database) => !database.externalHref);
2747
  if (firstDatabase) selectDatabase(firstDatabase.key);
2748
  else openNewDb("blank");
2749
  }}
2750
  >
2751
+ <DatabaseIcon />
2752
  {/* ⭐⭐ W41-T32 (R2) — "Database" BECOMES "Data". Owner instruction 29, in passing:
2753
  *"when a user click on a Database (let's rename it to Data)"*.
2754
  ⛔ THE LABEL ONLY. The route key, the class `shell-nav-db` and every selector that
 
2771
  (route === CONNECTORS_ROUTE ? " is-active" : "")
2772
  }
2773
  href={`#/${CONNECTORS_ROUTE}`}
2774
+ onClick={expandOnNavClick}
2775
  onMouseEnter={navCollapsed ? tipEnter("Connectors") : undefined}
2776
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2777
  >
 
2845
  // settle, and whose acceptance test is "THE RAIL PAINTS ONCE", never "the spinner is
2846
  // gone". [[a-rail-must-paint-once]]
2847
  className={"shell-nav-item shell-nav-templates" + (railLoading ? " is-rail-hidden" : "")}
2848
+ onClick={() => {
2849
+ // W53-T33 — instruction 6 says "any of the icon". Templates opens an OVERLAY rather
2850
+ // than a route, and the rail expanding behind it is what every other row now does.
2851
+ expandOnNavClick();
2852
+ setAssistOpen("templates");
2853
+ }}
2854
  onMouseEnter={navCollapsed ? tipEnter("Templates") : undefined}
2855
  onMouseLeave={navCollapsed ? tipLeave : undefined}
2856
  >
web/src/shell/icons.tsx ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // shell/icons.tsx — THE SHELL'S GLYPH VOCABULARY, in one file.
3
+ //
4
+ // WHY THIS FILE EXISTS (wave 53, contract C4). The rail's marks were defined
5
+ // inline in `Shell.tsx`, and one of them — the database cylinder — was ALSO
6
+ // hand-copied into `ViewSidebar.tsx` and into the Home page. Three hands drawing
7
+ // one mark is how two rows that mean the same thing stop looking alike; the copy
8
+ // nobody edits is the one a reader sees. So the shell's glyphs live here, are
9
+ // imported by every shell surface, and are edited in exactly one place.
10
+ //
11
+ // THE RULES, and they are not style preferences:
12
+ // · ONE EXPORT PER GLYPH. No shared sub-components, no shared state, no
13
+ // parameterised "icon factory" — a second glyph must be addable by appending
14
+ // a function, without reading the one above it.
15
+ // · EACH EXPORT CARRIES THE WAVE AND TICKET THAT DREW IT in its own comment,
16
+ // so the next person changing a mark can find the instruction it answers
17
+ // before they overrule it.
18
+ // · 16x16 viewBox, stroke-only, round caps, vector paths — NEVER emoji
19
+ // (owner constant).
20
+ // · NO LOCAL PAINT. `.shell-nav-icon` in `index.css` owns `fill: none`,
21
+ // `stroke: currentColor` and the shared `stroke-width: 1.2`. A glyph that
22
+ // hardcodes any of those leaves the column the next time the rail's weight
23
+ // is retuned, and nothing goes red — it just drifts.
24
+ // ⛔ THAT LAST RULE HAS A TRAP THE FIRST GLYPH HERE ALREADY HIT. A CSS class
25
+ // rule BEATS an SVG presentation attribute, so `fill="currentColor"` on a
26
+ // shape inside `.shell-nav-icon` renders INVISIBLE: the class says
27
+ // `fill: none` and wins. A "solid" dot is therefore drawn as a SMALL STROKED
28
+ // CIRCLE whose own 1.2 stroke closes the hole, never as a filled one.
29
+ //
30
+ // Guarded by `verify_icons.py` (gate `icons`), which reads the glyphs from THIS
31
+ // file and the mounts from `Shell.tsx`.
32
+ // ---------------------------------------------------------------------------
33
+
34
+ /** ⭐⭐ WAVE 53 · T34 (owner instruction 4) — THE AGENTS ROW'S MARK: A SQUARE
35
+ * WITH TWO EYES. Owner, verbatim: *"Agent module icon is still ugly. How about
36
+ * just make it square and have two dots in side that looks like an eye."*
37
+ *
38
+ * ⛔ IT REPLACES `FlowIcon`, THE TWO-NODE FLOW GLYPH WAVE 51 SHIPPED HERE — and
39
+ * `FlowIcon` had itself replaced a robot, which R15 deleted. NEITHER COMES
40
+ * BACK. The flow mark was the better ARGUMENT (an agent is a step, an edge, the
41
+ * next step) and it lost anyway, because at 16px three loose outlined shapes
42
+ * read as a diagram of nothing rather than as one thing. A face reads as one
43
+ * thing at any size, which is the whole of what a 16px rail mark has to do.
44
+ *
45
+ * ⚠ THE DOTS ARE STROKED CIRCLES, NOT FILLED ONES, AND THAT IS THE POINT OF
46
+ * FAILURE IF ANYONE "TIDIES" IT. `.shell-nav-icon` declares `fill: none`, and a
47
+ * class rule outranks a presentation attribute, so `fill="currentColor"` here
48
+ * paints NOTHING and the square renders empty. At r=0.95 under the class's own
49
+ * 1.2 stroke the remaining hole is 0.7 units wide, which closes into a solid dot
50
+ * at 16px while keeping the glyph's paint entirely delegated the way every
51
+ * sibling mark's is. An inline style would also work and is the wrong trade: it
52
+ * would be the one mark in the rail that does not follow the class.
53
+ * ⚠ THE RADIUS AND THE SPACING ARE A PAIR, MEASURED ON THE SHOT, not tuned
54
+ * independently. Under a 1.2 stroke r=0.95 draws a 3.1-wide dot, so the centres
55
+ * are 4.6 apart to leave 1.5 of clear ground between them: closer and the two
56
+ * dots blur into one bar at 16px, which is a squint, not a pair of eyes.
57
+ *
58
+ * Geometry: the square sits on the same box as `SheetIcon` (2.4 to 13.6) so the
59
+ * two marks share a silhouette in the column, with a wider corner radius so it
60
+ * reads as a head rather than as another sheet. The eyes sit a touch above the
61
+ * box centre, which is where a face carries them; dead-centre reads as a
62
+ * colon. */
63
+ export function AgentIcon() {
64
+ return (
65
+ <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
66
+ <rect x="2.4" y="2.4" width="11.2" height="11.2" rx="2.7" />
67
+ <circle cx="5.7" cy="7.8" r="0.95" />
68
+ <circle cx="10.3" cy="7.8" r="0.95" />
69
+ </svg>
70
+ );
71
+ }
72
+
73
+ /** ⭐⭐ WAVE 53 · T35 (owner instruction 26, contract C4) — THE DATABASE CYLINDER, ONE DRAWING.
74
+ * Owner, verbatim: *"The icon for a database should be standardized, including the one in the
75
+ * View rail. It shouldn't be filled with purple. The icon on the home page is the correct one."*
76
+ * So the HOME page's mark is canonical and this is it: the three `d` strings below are
77
+ * `customer-grid/iconShapes.ts::DATABASE_SHAPE_PATHS` copied byte for byte, which is what makes
78
+ * the rail's Data row and the Home tile the same drawing rather than two that resemble each
79
+ * other.
80
+ *
81
+ * ⛔ THE COPY IS DELIBERATE, AND IMPORTING THE CONSTANT INSTEAD IS THE WRONG FIX. This file is
82
+ * reached from the EAGER shell entry, and `iconShapes.ts` pulls the grid's icon vocabulary with
83
+ * it — a ~48 kB chunk dragged into the first paint to save three strings. What stops the two
84
+ * copies drifting is not an import, it is `verify_icons.py`, which reads BOTH files and compares
85
+ * the `d` values byte for byte. A drift is a red gate, not a silently different cylinder.
86
+ *
87
+ * ⚠ NO `fill=` AND NO `stroke-width` HERE, like every sibling: `.shell-nav-icon` owns both. That
88
+ * is also the whole of the owner's complaint, one layer down — the View rail's copy of this mark
89
+ * is painted by `.cg-folder-mark path` in `styles/wave45/data-applications.css`, a rule that is
90
+ * CORRECT for a folder and fills a database with brand purple. See `shell/shell.css` for the
91
+ * two-class override that keeps a database out of that rule; a glyph declaring its own paint here
92
+ * would have solved this row and left that one broken.
93
+ *
94
+ * ⚠ IT REPLACES `dbFrame.tsx::DbIcon` AT THE DATA ROW, not everywhere: `query/queryParts.tsx`
95
+ * still draws `DbIcon`, so the coin stack is alive and is a DIFFERENT mark. If that surface is
96
+ * ever standardised too, it points here. */
97
+ export function DatabaseIcon() {
98
+ return (
99
+ <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
100
+ <path d="M3.5 3.9a4.5 1.9 0 1 0 9 0a4.5 1.9 0 1 0-9 0" />
101
+ <path d="M3.5 3.9v8.2a4.5 1.9 0 0 0 9 0V3.9" />
102
+ <path d="M3.5 8a4.5 1.9 0 0 0 9 0" />
103
+ </svg>
104
+ );
105
+ }
web/src/shell/nav.ts CHANGED
@@ -1302,6 +1302,30 @@ export const CHROME_ROUTES: ReadonlySet<string> = new Set([
1302
  SUBSCRIPTION_ROUTE,
1303
  ]);
1304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1305
  /**
1306
  * Old route key → the key that replaced it. Applied to the hash before ANYTHING else reads it.
1307
  *
 
1302
  SUBSCRIPTION_ROUTE,
1303
  ]);
1304
 
1305
+ /**
1306
+ * ⭐⭐ WAVE 53 · T32 (ruling R1) — THE SURFACES WHERE THE NAV NEVER FOLDS ITSELF. Owner,
1307
+ * instruction 3, verbatim: *"When user first open the app and they're at home. Make sure the
1308
+ * navigation is unminimized."* and *"Never collapse on home or starred UNLESS the user click the
1309
+ * minmize navigation button of course. Also apply this for inbox module."*
1310
+ *
1311
+ * These three are READING surfaces: Home, Starred and Inbox are lists of places to go, and a rail
1312
+ * that folds itself while you are choosing where to go has taken away the very thing the page is
1313
+ * for. Every other route is a WORK surface, where the fold buys screen for the work — W38-T04's
1314
+ * unconditional cell-click fold is untouched there and stays exactly as ruling R9 left it.
1315
+ *
1316
+ * ⛔ THE SET EXISTS SO A FOURTH SUCH SURFACE JOINS BY ADDING A KEY HERE. The alternative — each
1317
+ * new reading page finding and amending every fold call site — is how one of them ends up
1318
+ * disagreeing with the other three, which is the shape of the defect this ticket fixes.
1319
+ * ⚠ It is NOT a subset anyone should re-derive from `CHROME_ROUTES`: Connectors and Query are
1320
+ * chrome too and both are worked IN, so the two sets answer different questions and must stay
1321
+ * two sets.
1322
+ */
1323
+ export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet<string> = new Set([
1324
+ HOME_ROUTE,
1325
+ STARRED_ROUTE,
1326
+ INBOX_ROUTE,
1327
+ ]);
1328
+
1329
  /**
1330
  * Old route key → the key that replaced it. Applied to the hash before ANYTHING else reads it.
1331
  *
web/src/shell/shell.css ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ---------------------------------------------------------------------------
2
+ shell/shell.css — the shell's OWN sheet, imported by `Shell.tsx` the way
3
+ `NavExtras.tsx` imports `navExtras.css`. A shell-local override lives here
4
+ rather than in `index.css`, where it would have a global blast radius.
5
+
6
+ ⭐⭐ WAVE 53 · T35 (owner instruction 26, contract C4) — A DATABASE IS NOT A
7
+ FOLDER. Owner, verbatim: *"The icon for a database should be standardized,
8
+ including the one in the View rail. It shouldn't be filled with purple. The
9
+ icon on the home page is the correct one."*
10
+
11
+ ⛔ THE PURPLE IS CSS, NOT AN SVG FILL, AND THAT IS THE WHOLE DIAGNOSIS.
12
+ `styles/wave45/data-applications.css` declares
13
+ `.cg-folder-mark path { fill:var(--lp-purple-deep); stroke:var(--lp-purple-deep); }`
14
+ — right for a folder (W45-T14/C6: one folder, one meaning), and wrong for a
15
+ database, because `customer-grid/iconShapes.ts::DatabaseMark` renders under
16
+ that same `cg-folder-mark` class. A class rule OUTRANKS a presentation
17
+ attribute, so the mark's own `fill="none"` loses and the cylinder ships
18
+ filled. That sheet is imported by `CustomerGrid.tsx`, so the repaint lands
19
+ wherever the grid chunk has loaded — which is why Home looks right (it paints
20
+ before that chunk arrives) and the View rail looks wrong.
21
+
22
+ ⛔ THE FOLDER RULE IS NOT THE BUG AND MUST NOT BE TOUCHED: `verify_folders.py`
23
+ and `verify_w45_data_applications.py` both assert it verbatim. The defect is
24
+ that a DATABASE mark wears a FOLDER class, so the fix is a wrapper the
25
+ database mark alone sits inside.
26
+
27
+ ⚠ TWO CLASSES, ON PURPOSE — this wins on SPECIFICITY (0,2,1 against the
28
+ folder rule's 0,1,1) and therefore does not depend on import order, which
29
+ matters because the sheet it overrides ships in a LAZY chunk whose arrival
30
+ time is not something this file can pin.
31
+
32
+ ⚠ AND THE STROKE IS RESTATED, not merely the fill: dropping `fill` alone
33
+ would leave the cylinder outlined in `--lp-purple-deep`, which is still not
34
+ the mark Home draws. `--lp-muted` is `#6B7280`, which is exactly the
35
+ `LP_MUTED` that `iconShapes.ts` paints `DATABASE_MARK_TONE = "neutral"` with
36
+ — so the rail's cylinder and the Home tile's end up the same grey outline,
37
+ which is what instruction 26 asked for.
38
+
39
+ Guarded by `verify_icons.py` (gate `icons`), whose T35 leg reads this rule by
40
+ name — a scan for `fill=` inside the SVG is green on exactly the broken
41
+ screen the owner reported.
42
+ --------------------------------------------------------------------------- */
43
+
44
+ .cg-db-mark .cg-folder-mark path,
45
+ .home-db-glyph .cg-folder-mark path { fill: none; stroke: var(--lp-muted); }
46
+
47
+ /* ⛔ THE HOME LEG IS NOT DECORATION, AND IT IS THE PART A SCREENSHOT OF A COLD
48
+ LOAD CANNOT SHOW. Home draws the SAME `DatabaseMark` inside
49
+ `.home-tile-chip.home-db-glyph`, and it looks correct today only because
50
+ `data-applications.css` ships in the GRID chunk, which has not arrived yet on
51
+ a first paint of Home. Open Data once and go back and the Home tiles fill
52
+ purple too — the owner's "the icon on the home page is the correct one" is
53
+ true of the page they were looking at, not of the page after a round trip.
54
+ One rule, both surfaces, no dependence on which chunk loaded first.
55
+ ⚠ It reads a `home-*` class from the shell's sheet deliberately: the
56
+ alternative is a third copy of this override in `styles/wave50/rail.css`,
57
+ which is the drift instruction 26 is complaining about, one layer down. */
58
+
59
+ /* The wrapper is a LAYOUT no-op by construction. `.cg-fold-toggle` lays its
60
+ children out as flex items, and `index.css` gives the mark itself
61
+ `flex: 0 0 auto`; putting a span around it would otherwise hand the row a
62
+ shrinkable, baseline-aligned box in its place and nudge the label. These
63
+ three declarations hand the span exactly what the svg had. */
64
+ .cg-db-mark { display: inline-flex; align-items: center; flex: 0 0 auto; }
web/src/styles/wave52/ribbon.css CHANGED
@@ -52,13 +52,50 @@
52
  gap: 0;
53
  }
54
 
 
 
 
 
 
 
55
  .sheet-ribbon-clip-stack .sheet-ribbon-btn {
56
- justify-content: flex-start;
57
- width: 92px;
58
  height: 18px;
59
  padding: 0 4px;
60
  }
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  /* -- Import / Refresh / Full screen (instruction 14): the SAME horizontal strip as the Home tab,
63
  never a ribbon group. Sits between the tab list and the collapse chevron; the chevron keeps its
64
  own `margin-left: auto` (wave51/sheet-engine.css), which still pushes it to the far right of
 
52
  gap: 0;
53
  }
54
 
55
+ /* ⭐ W53-T06 (owner instruction 17) — the three stacked controls are ICON ONLY now, so the 92px
56
+ this rule reserved for "Format painter" beside its glyph is 66px of dead space per row. The
57
+ width becomes the glyph's own box: `.sheet-ribbon-btn`'s 26px min-width with this rule's own
58
+ 4px side padding, centred rather than left-aligned because there is no longer a caption for a
59
+ left edge to align. ⚠ IT IS A FIXED WIDTH, NOT CONTENT-DERIVED, which is why removing the word
60
+ alone would not have reclaimed a pixel - the caption and this number had to go together. */
61
  .sheet-ribbon-clip-stack .sheet-ribbon-btn {
62
+ justify-content: center;
63
+ width: 26px;
64
  height: 18px;
65
  padding: 0 4px;
66
  }
67
 
68
+ /* -- W53-T05 (owner instruction 16): THE ALIGNMENT GROUP IS TWO ROWS, NOT ONE LINE.
69
+
70
+ Excel stacks the vertical three over the horizontal three and hangs the rest beside them; a
71
+ single nine-button line was this group's only real departure from that. The mechanism is the one
72
+ `.sheet-ribbon-clip-stack` above already established: a COLUMN wrapper sitting inside
73
+ `.sheet-ribbon-group-controls` (which is itself a row flex, wave51/sheet-engine.css), with each
74
+ row a plain row flex of the SAME `.sheet-ribbon-btn` buttons. No new control shape and no new
75
+ button size, which is what DESIGN.md section 4 means by "new sidebar/nav elements join the
76
+ existing rhythm".
77
+
78
+ ⭐ THE RIBBON DOES NOT GROW. Two 26px rows is 52px, which is exactly the `min-height: 52px` the
79
+ large Paste button above already imposes on the ribbon's control band, so the tallest thing in
80
+ the row is unchanged and the strip keeps its height. The `gap: 0` is deliberate for the same
81
+ reason - a gap here would be the one thing that pushes past 52px.
82
+
83
+ ⚠ THE ROW DIVS CARRY NO PADDING. Horizontal rhythm stays with `.sheet-ribbon-group-controls`'s
84
+ own `gap: 1px`, restated here rather than inherited because these rows are its GRANDCHILDREN
85
+ now, not its children, and a flex gap does not cascade. */
86
+ .sheet-ribbon-align {
87
+ display: flex;
88
+ flex-direction: column;
89
+ justify-content: center;
90
+ gap: 0;
91
+ }
92
+
93
+ .sheet-ribbon-align-row {
94
+ display: flex;
95
+ align-items: center;
96
+ gap: 1px;
97
+ }
98
+
99
  /* -- Import / Refresh / Full screen (instruction 14): the SAME horizontal strip as the Home tab,
100
  never a ribbon group. Sits between the tab list and the collapse chevron; the chevron keeps its
101
  own `margin-left: auto` (wave51/sheet-engine.css), which still pushes it to the far right of
web/src/styles/wave53/ribbon-pop.css ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* wave 53 -- lane B (W53-T07, owner instruction 25). THE RIBBON POPOVER'S SURFACE, RESTATED FOR A
2
+ PORTAL.
3
+
4
+ ⭐⭐ WHY THIS FILE EXISTS AT ALL. Every `Ribbon.tsx` popover now renders through
5
+ `customer-grid/OverlaySurface.tsx::AnchoredOverlay`, which is a body-level `position: fixed`
6
+ node created by `createPortal`. It is therefore no longer a DOM descendant of
7
+ `.sheet-ribbon-slot`, of `.sheet-ribbon-scroll` or of anything else in the ribbon, so ANY rule
8
+ written as `#ancestor .child` stops matching the moment it is portalled -- silently, with no
9
+ build error and no gate anywhere going red. The surface a menu paints (its background, its
10
+ edge, its shadow) is exactly the thing that must never depend on where the node happens to sit,
11
+ because a transparent menu over a grid canvas is unreadable and still looks correct in the DOM
12
+ inspector ([[a-portal-overlay-carries-its-own-surface]]).
13
+
14
+ ⛔ WHY NOT JUST EDIT `.sheet-ribbon-pop`. That rule lives in `styles/wave50/sheet.css`, which is
15
+ OUTSIDE this ticket's file fence. The portalled element keeps that class (KeyTips reads it, and
16
+ the child vocabulary below is shared with it), and this file adds a SECOND class that restates
17
+ the whole surface on its own terms. Where the two disagree, this file is the one written for a
18
+ portal.
19
+
20
+ ⭐⭐ THE BORDER IS THE REAL BUG FIX HERE, AND IT PREDATES THIS TICKET. `wave50/sheet.css`'s
21
+ `.sheet-ribbon-pop` declares `border: 1px solid var(--lp-line-strong)`, and `--lp-line-strong`
22
+ IS NOT DECLARED ANYWHERE in `index.css`. A `var()` naming an undeclared custom property makes
23
+ the whole declaration invalid at computed-value time, which resolves `border` to its initial
24
+ value -- `border-style: none`. So the ribbon menus have been shipping with NO edge at all, only
25
+ a shadow. `wave51/sheet-engine.css`'s own header records catching this exact ghost token on the
26
+ scrollbar thumb in W51-T16; this is the second site. `--lp-line` is the declared hairline and is
27
+ what every other quiet edge in the sheet chrome uses.
28
+
29
+ Tokens only (`var(--lp-*)`), no literal hex, no literal font-size (DESIGN.md section 2). The
30
+ shadow's `rgba()` is copied byte for byte from the rule it replaces -- shadows are permitted on
31
+ overlays and ONLY on overlays (DESIGN.md section 4), and there is no shadow token to name.
32
+
33
+ Imported directly by `sheet/Ribbon.tsx`, not through `index.css`'s `@import` chain, for the
34
+ reason `styles/wave52/ribbon.css`'s own header sets out: `index.css` is shared across every
35
+ lane and a line there is the trivial-but-collision-prone edit. A component-owned side-effect
36
+ import is this repo's established way around it (`customer-grid/Toolbar.tsx` imports its own
37
+ `./filters.css` the same way). */
38
+
39
+ .sheet-ribbon-pop-portal {
40
+ /* ⛔ NO `position`, `left`, `top`, `max-width` OR `max-height` HERE. `AnchoredOverlay` writes
41
+ all five as an INLINE style every time it measures, and an inline declaration wins over this
42
+ file regardless of source order. Restating them would be dead code that reads as if it were
43
+ load bearing. */
44
+ display: flex;
45
+ flex-direction: column;
46
+ gap: 1px;
47
+ min-width: 168px;
48
+ padding: 5px;
49
+ /* The surface, self contained: nothing below depends on an ancestor in the ribbon. */
50
+ background: var(--lp-surface);
51
+ border: 1px solid var(--lp-line);
52
+ border-radius: var(--lp-r-md);
53
+ box-shadow: 0 6px 18px rgba(25, 34, 46, 0.16);
54
+ color: var(--lp-ink);
55
+ /* A menu taller than the viewport gets a `max-height` from `AnchoredOverlay`'s collision
56
+ arithmetic; without this it would be clipped by that height instead of scrolling inside it,
57
+ which is the same class of defect this ticket was opened for. */
58
+ overflow-y: auto;
59
+ }
60
+
61
+ /* The swatch grid, the chip and the menu row are declared as PLAIN classes in
62
+ `styles/wave50/sheet.css` (`.sheet-ribbon-item`, `.sheet-ribbon-swatches`, `.sheet-ribbon-row`,
63
+ `.sheet-ribbon-step`, `.sheet-ribbon-count`), so they keep matching inside the portal and are
64
+ deliberately not restated. The chip is the one exception: it names the same ghost token the
65
+ popover's border did, so its edge is invisible for the same reason and is fixed here for the
66
+ portalled case rather than left to look like a rendering accident. */
67
+ .sheet-ribbon-pop-portal .sheet-ribbon-chip {
68
+ border: 1px solid var(--lp-line);
69
+ }
web/src/styles/wave53/sheet-rail.css ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ---------------------------------------------------------------------------
2
+ styles/wave53/sheet-rail.css - the LAST pixel of Sheet/Data rail parity
3
+ (wave 53, W53-T04, owner instruction 15, the owner's THIRD report).
4
+
5
+ ⭐⭐ THE MEASUREMENT, NOT THE DIFF. Two 1440x900 frames were taken at `#/sheet` and at
6
+ `#/data?database=customer_data` and scanned for dark-pixel row bands in the rail column
7
+ (x = 300..560). W51-T09 and W52-T21 had already closed most of the gap; what remained was
8
+ exactly one pixel, and it was in the PATH ROW, not in the create door:
9
+
10
+ band Sheet Data
11
+ .cg-views-top icons 61-70 61-70 <- agree
12
+ rule under .cg-views-top 87 87 <- agree
13
+ path row text 103-112 104-113 <- 1px
14
+ rule under the path row 123 124 <- 1px
15
+ "+ Create new..." 145-154 146-155 <- 1px
16
+ "Find..." 173-182 174-183 <- 1px
17
+
18
+ Everything from the path row DOWN sat one pixel HIGH on the Sheet. The white space the
19
+ instruction describes is therefore not above "+ Create new..." at all; it is the path row
20
+ above it being one pixel SHORT, which pulls the whole stack up.
21
+
22
+ ⭐⭐ WHY THE ROW IS SHORT, AND WHY THERE IS NO MAGIC NUMBER BELOW. Both rails render the same
23
+ element, `nav.cg-fold-head.cg-view-path.cg-segmented-path`, and it is `box-sizing: border-box`
24
+ everywhere (index.css:42). Its own chrome is identical on both:
25
+
26
+ .cg-fold-head padding: 1px 2px (index.css:5875)
27
+ .cg-view-path border-bottom: 1px (wave46/rail-select.css:245 for Data,
28
+ wave52/parity.css for Sheet)
29
+ .cg-segmented-path min-height: 30px (same two sheets)
30
+
31
+ What is NOT identical is the tallest CHILD, and that is correct rather than a defect. The
32
+ Data rail's row ends in `databaseActions`, a 28px `button.shell-dots`
33
+ (`ViewSidebar.tsx:2718`, sized by `wave46/rail-select.css:202`). The Sheet rail has no
34
+ database to act on, so wave-49 R2 requires that control to be ABSENT rather than
35
+ present-and-inert, and the row's tallest child is a 26px `.cg-path-history-button`
36
+ (index.css:557).
37
+
38
+ So the two rows resolve their heights by DIFFERENT rules:
39
+
40
+ Data 28 + 1 + 1 + 1 = 31px natural, which OVERFLOWS the 30px floor and wins
41
+ Sheet 26 + 1 + 1 + 1 = 29px natural, which is under the floor, so 30px wins
42
+
43
+ The shared `min-height: 30px` was never the Data row's height. It is a floor the Data row
44
+ clears by one pixel and the Sheet row does not reach. The honest fix is therefore not to
45
+ invent a 28px control the Sheet cannot honour, and not to nudge a margin: it is to seat the
46
+ Sheet's path row in the same 31px box the Data row COMPUTES, and to say where each of those
47
+ four pixels comes from.
48
+
49
+ ⛔ SPECIFICITY IS DELIBERATE AND MUST NOT BE "SIMPLIFIED". `wave52/parity.css` states
50
+ `.sheet-page .cg-segmented-path` at (0,2,0). A tie here would leave the winner to whichever
51
+ sheet the bundler emits last, which no lane controls and which can flip between builds - the
52
+ same coin flip `wave46/rail-select.css` warns about at its `button.shell-dots` rule. Adding
53
+ `.cg-view-path` makes this (0,3,0) and it wins outright.
54
+
55
+ ⛔ SCOPED UNDER `.sheet-page` so it can never reach the Data rail, which has no `.sheet-page`
56
+ ancestor. This lane owns the Sheet side only.
57
+
58
+ ⛔ TOKENS ONLY: no colour, no font-size, no z-index is declared here at all.
59
+ --------------------------------------------------------------------------- */
60
+
61
+ .sheet-page .cg-view-path.cg-segmented-path {
62
+ /* 28px (the height the Data row's `button.shell-dots` gives it)
63
+ + 1px + 1px (`.cg-fold-head`'s vertical padding)
64
+ + 1px (`.cg-view-path`'s bottom rule)
65
+ = the 31px border box the Data rail's path row measures. */
66
+ min-height: 31px;
67
+ }