fsanyoto commited on
Commit
39a9177
Β·
verified Β·
1 Parent(s): a848898

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. RELEASES.json +7 -1
  2. VERSION +1 -1
  3. api/formula_runtime.py +106 -23
  4. api/routes_grid.py +138 -5
  5. api/routes_odoo_tables.py +254 -5
  6. api/routes_sheet.py +832 -27
  7. api/routes_tables.py +95 -0
  8. platform/aios_grid.py +55 -1
  9. platform/core/grid_events.py +77 -3
  10. platform/core/relations.py +475 -0
  11. platform/core/shares.py +1 -1
  12. platform/core/sheet_import.py +980 -0
  13. platform/core/sheets.py +929 -38
  14. platform/core/table_store.py +145 -3
  15. platform/harness/filter_eval.py +69 -2
  16. platform/harness/filter_sql.py +91 -0
  17. platform/modules/sheet.py +134 -6
  18. web/src/assistant/AssistantPage.tsx +10 -1
  19. web/src/connectors/ViewDeleteDisclosure.tsx +61 -187
  20. web/src/customer-grid/ColumnMenu.tsx +25 -14
  21. web/src/customer-grid/CustomerGrid.tsx +538 -51
  22. web/src/customer-grid/MapView.tsx +544 -387
  23. web/src/customer-grid/OverlaySurface.tsx +15 -11
  24. web/src/customer-grid/RecordDetail.tsx +545 -566
  25. web/src/customer-grid/RouteNav.tsx +80 -4
  26. web/src/customer-grid/ViewSidebar.tsx +92 -13
  27. web/src/customer-grid/aggregations.ts +150 -48
  28. web/src/customer-grid/apiBridge.ts +137 -9
  29. web/src/customer-grid/iconShapes.ts +20 -0
  30. web/src/customer-grid/summary/SummaryBar.tsx +11 -1
  31. web/src/customer-grid/types.ts +244 -3
  32. web/src/customer-grid/useCustomerData.ts +53 -6
  33. web/src/customer-grid/useVisibleRows.ts +66 -1
  34. web/src/filter-kit/FilterBuilderPanel.tsx +237 -4
  35. web/src/filter-kit/ops.ts +32 -3
  36. web/src/filter-kit/standalone.html +12 -0
  37. web/src/filter-kit/standalone.tsx +66 -0
  38. web/src/index.css +10 -0
  39. web/src/sheet/BindingEditor.tsx +547 -102
  40. web/src/sheet/DrillModal.tsx +25 -4
  41. web/src/sheet/FormulaBar.tsx +58 -0
  42. web/src/sheet/ImportDialog.tsx +326 -0
  43. web/src/sheet/Ribbon.tsx +587 -174
  44. web/src/sheet/RulesDialog.tsx +408 -0
  45. web/src/sheet/SheetGrid.tsx +0 -0
  46. web/src/sheet/SheetPage.tsx +928 -104
  47. web/src/sheet/SheetRail.tsx +450 -42
  48. web/src/sheet/ShortcutsPanel.tsx +97 -0
  49. web/src/sheet/rules.ts +400 -0
  50. web/src/sheet/sheetApi.ts +245 -9
RELEASES.json CHANGED
@@ -1,6 +1,12 @@
1
  {
2
- "current": "eedfb6a",
3
  "releases": [
 
 
 
 
 
 
4
  {
5
  "version": "v69",
6
  "sha": "8598f56",
 
1
  {
2
+ "current": "3c72c5b",
3
  "releases": [
4
+ {
5
+ "version": "v70",
6
+ "sha": "eedfb6a",
7
+ "date": "2026-09-03",
8
+ "subject": "release v70 - wave 50 (grid analytics, the Sheet as a spreadsheet, view trash and audit)"
9
+ },
10
  {
11
  "version": "v69",
12
  "sha": "8598f56",
VERSION CHANGED
@@ -1 +1 @@
1
- eedfb6a
 
1
+ 3c72c5b
api/formula_runtime.py CHANGED
@@ -880,8 +880,18 @@ def _is_range_position(fn, index):
880
  return False
881
 
882
 
883
- def _a1_at(source, i):
884
- """`(replacement_text, next_index)` if an A1 token starts at `i`, else None."""
 
 
 
 
 
 
 
 
 
 
885
  m = _A1_RE.match(source, i)
886
  if not m:
887
  return None
@@ -893,7 +903,7 @@ def _a1_at(source, i):
893
  return None # a function call, not an address. See the note above.
894
  if nxt < len(source) and (source[nxt].isalnum() or source[nxt] in "_$!"):
895
  return None # the token does not end here, so it is not an address
896
- sheet = m.group(1) or m.group(2) or ""
897
  first = (m.group(3) or "") + (m.group(4) or "")
898
  if m.group(5):
899
  last = m.group(5) + (m.group(6) or "")
@@ -901,8 +911,12 @@ def _a1_at(source, i):
901
  return f"A1REF({first!r}, {sheet!r})", end
902
 
903
 
904
- def _rewrite(source):
905
- """Translate Excel punctuation to Python AST punctuation without touching strings."""
 
 
 
 
906
  out, i, quote = [], 0, None
907
  while i < len(source):
908
  c = source[i]
@@ -913,16 +927,6 @@ def _rewrite(source):
913
  out.append(source[i + 1]); i += 2; continue
914
  quote = None
915
  i += 1; continue
916
- if c in ("'", '"'):
917
- quote = c; out.append(c); i += 1; continue
918
- if c == "{":
919
- end = source.find("}", i + 1)
920
- if end < 0:
921
- raise FormulaError("a field reference is missing its closing }")
922
- key = source[i + 1:end].strip()
923
- if not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY:
924
- raise FormulaError("a field reference may contain only letters, digits and _")
925
- out.append(f"REF({key!r})"); i = end + 1; continue
926
  # ⭐ AN A1 TOKEN IS ONLY TRIED AT AN IDENTIFIER BOUNDARY. Without this guard the scanner
927
  # would happily match the tail of a longer name, so `myB4` would end up holding a reference
928
  # to cell B4. The previous SOURCE character decides, not the previous emitted one, because
@@ -931,6 +935,17 @@ def _rewrite(source):
931
  # True, because "" is a substring of every string. That silently disabled A1 addressing for
932
  # any formula STARTING with a reference, which is most of them, while leaving `SUM(B4:B8)`
933
  # working because its `B` follows a `(`. Compare against a tuple, which has no such edge.
 
 
 
 
 
 
 
 
 
 
 
934
  prev = source[i - 1] if i else ""
935
  if (c.isalpha() or c in ("$", "'")) and not (prev.isalnum() or prev in ("_", "$")):
936
  # ⭐ A DOTTED EXCEL NAME IS FOLDED BEFORE THE A1 ATTEMPT (W50-T16). `STDEV.P(` must
@@ -942,11 +957,21 @@ def _rewrite(source):
942
  out.append(dotted.group(1).upper() + "_P")
943
  i = dotted.end()
944
  continue
945
- got = _a1_at(source, i)
946
  if got:
947
  text, i = got
948
  out.append(text)
949
  continue
 
 
 
 
 
 
 
 
 
 
950
  two = source[i:i + 2]
951
  if two in ("<=", ">=", "!=", "=="):
952
  out.append(two); i += 2; continue
@@ -1027,8 +1052,16 @@ def _normal(node, depth=0):
1027
  raise FormulaError("formula contains unsupported syntax")
1028
 
1029
 
1030
- def parse_formula(source):
 
 
 
 
 
 
 
1031
  source = str(source or "")
 
1032
  if not source.strip():
1033
  raise FormulaError("the formula is empty")
1034
  if len(source) > MAX_SOURCE:
@@ -1038,7 +1071,7 @@ def parse_formula(source):
1038
  # Python 3.12 warns while parsing them even though the string is valid for this grammar.
1039
  with warnings.catch_warnings():
1040
  warnings.simplefilter("ignore", SyntaxWarning)
1041
- parsed = ast.parse(_rewrite(source), mode="eval")
1042
  except (SyntaxError, ValueError) as exc:
1043
  raise FormulaError("the formula could not be parsed") from exc
1044
  if sum(1 for _ in ast.walk(parsed)) > MAX_NODES:
@@ -2160,12 +2193,52 @@ def evaluate_fields(definitions, row, *, today=None):
2160
  return {"values": {key: values.get(key) for key in definitions}, "errors": errors}
2161
 
2162
 
2163
- def evaluate_sheet(cells, *, today=None):
2164
- """Evaluate a whole SHEET of A1 cells in dependency order (wave 49, W49-T03).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2165
 
2166
  `cells` is `{addr_key: {"formula": "=..."} or {"value": v}}` where `addr_key` is what
2167
- `a1_key` produces: `B4` on this tab, `SHEET2!C3` on another. Returns
2168
- `{"values": {addr: value}, "errors": {addr: code}}`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2169
 
2170
  β›”β›” **THE REFUSAL IS `circular_reference`, AND IT IS DELIBERATELY NOT THE `"cycle"` THAT
2171
  `evaluate_fields` ALREADY USES.** Renaming that one was considered and rejected on evidence:
@@ -2184,6 +2257,7 @@ def evaluate_sheet(cells, *, today=None):
2184
  """
2185
  values, errors, active, resolved = {}, {}, [], set()
2186
  parsed = {}
 
2187
 
2188
  for addr, spec in (cells or {}).items():
2189
  if not isinstance(spec, dict):
@@ -2202,10 +2276,19 @@ def evaluate_sheet(cells, *, today=None):
2202
  raw = spec.get("formula")
2203
  if isinstance(raw, str) and raw.strip().startswith("="):
2204
  try:
2205
- parsed[addr] = parse_formula(raw.strip()[1:])
2206
  except FormulaError:
2207
  errors[addr] = "bad_formula"
2208
  values[addr] = None
 
 
 
 
 
 
 
 
 
2209
  else:
2210
  values[addr] = spec.get("value")
2211
 
 
880
  return False
881
 
882
 
883
+ def _a1_at(source, i, default_sheet=""):
884
+ """`(replacement_text, next_index)` if an A1 token starts at `i`, else None.
885
+
886
+ ⭐ `default_sheet` IS WHAT MAKES A WORKBOOK PASS POSSIBLE (W51-T23). An UNQUALIFIED reference
887
+ means "this tab", and the only moment anything knows which tab that is, is when the formula is
888
+ read out of a cell that lives on one. So the owning tab is supplied HERE, at rewrite time, and
889
+ `=G4+1` on `Tab05` becomes `A1REF('G4', 'Tab05')` before `_normal` ever builds a key. A
890
+ reference that names its own sheet keeps that name; nothing else in the pipeline changes.
891
+ β›” THE ALTERNATIVE WAS MEASURED AND IS WORSE: qualifying the SPEC KEYS alone and leaving the
892
+ formulas untouched makes cross-tab keys resolvable and breaks every local reference, which the
893
+ wave-51 prototype recorded as 3,770 blanks against a true 785.
894
+ """
895
  m = _A1_RE.match(source, i)
896
  if not m:
897
  return None
 
903
  return None # a function call, not an address. See the note above.
904
  if nxt < len(source) and (source[nxt].isalnum() or source[nxt] in "_$!"):
905
  return None # the token does not end here, so it is not an address
906
+ sheet = m.group(1) or m.group(2) or default_sheet
907
  first = (m.group(3) or "") + (m.group(4) or "")
908
  if m.group(5):
909
  last = m.group(5) + (m.group(6) or "")
 
911
  return f"A1REF({first!r}, {sheet!r})", end
912
 
913
 
914
+ def _rewrite(source, sheet=""):
915
+ """Translate Excel punctuation to Python AST punctuation without touching strings.
916
+
917
+ `sheet` is the tab this formula LIVES ON, and every reference that does not name a tab of its
918
+ own is read as pointing at that one. See `_a1_at` for why it enters the pipeline here.
919
+ """
920
  out, i, quote = [], 0, None
921
  while i < len(source):
922
  c = source[i]
 
927
  out.append(source[i + 1]); i += 2; continue
928
  quote = None
929
  i += 1; continue
 
 
 
 
 
 
 
 
 
 
930
  # ⭐ AN A1 TOKEN IS ONLY TRIED AT AN IDENTIFIER BOUNDARY. Without this guard the scanner
931
  # would happily match the tail of a longer name, so `myB4` would end up holding a reference
932
  # to cell B4. The previous SOURCE character decides, not the previous emitted one, because
 
935
  # True, because "" is a substring of every string. That silently disabled A1 addressing for
936
  # any formula STARTING with a reference, which is most of them, while leaving `SUM(B4:B8)`
937
  # working because its `B` follows a `(`. Compare against a tuple, which has no such edge.
938
+ #
939
+ # β›”β›” THIS BLOCK SITS ABOVE THE QUOTE BRANCH, AND THAT ORDER IS THE WHOLE OF D-638
940
+ # (W51-T23). It used to sit below, so a leading `'` ALWAYS entered string mode first:
941
+ # `'Data'!B12` was emitted as the Python string `'Data'` followed by a separately rewritten
942
+ # `!B12` with an EMPTY sheet name, which cannot parse, and Excel's own quoted spelling came
943
+ # back as "the formula could not be parsed". The guard below already reads `c in ("$", "'")`
944
+ # because the author meant this branch to see a quote; it simply never got the chance.
945
+ # ⭐ MOVING IT IS SAFE BECAUSE `_a1_at` IS ALL OR NOTHING: it answers None unless the whole
946
+ # `'name'!ADDR` shape matches, so a `'...'` used as TEXT falls straight through to the
947
+ # quote branch below and keeps working. `"` never reaches here at all, since the guard
948
+ # admits only letters, `$` and `'`.
949
  prev = source[i - 1] if i else ""
950
  if (c.isalpha() or c in ("$", "'")) and not (prev.isalnum() or prev in ("_", "$")):
951
  # ⭐ A DOTTED EXCEL NAME IS FOLDED BEFORE THE A1 ATTEMPT (W50-T16). `STDEV.P(` must
 
957
  out.append(dotted.group(1).upper() + "_P")
958
  i = dotted.end()
959
  continue
960
+ got = _a1_at(source, i, sheet)
961
  if got:
962
  text, i = got
963
  out.append(text)
964
  continue
965
+ if c in ("'", '"'):
966
+ quote = c; out.append(c); i += 1; continue
967
+ if c == "{":
968
+ end = source.find("}", i + 1)
969
+ if end < 0:
970
+ raise FormulaError("a field reference is missing its closing }")
971
+ key = source[i + 1:end].strip()
972
+ if not re.fullmatch(r"[A-Za-z0-9_]+", key) or len(key) > MAX_FIELD_KEY:
973
+ raise FormulaError("a field reference may contain only letters, digits and _")
974
+ out.append(f"REF({key!r})"); i = end + 1; continue
975
  two = source[i:i + 2]
976
  if two in ("<=", ">=", "!=", "=="):
977
  out.append(two); i += 2; continue
 
1052
  raise FormulaError("formula contains unsupported syntax")
1053
 
1054
 
1055
+ def parse_formula(source, *, sheet=""):
1056
+ """One formula's stored definition. `sheet` is the tab it lives on, or "" for a grid field.
1057
+
1058
+ ⭐ KEYWORD ONLY, AND DEFAULTED TO "", so every caller that has no notion of a tab keeps the
1059
+ definition it always had: with no sheet, an unqualified reference still keys as the bare `B4`
1060
+ that `evaluate_fields` and `routes_query.py::parse_formula` already read. Only a Sheet supplies
1061
+ a tab, and only then do this formula's own references key as `TAB!B4`.
1062
+ """
1063
  source = str(source or "")
1064
+ sheet = str(sheet or "")
1065
  if not source.strip():
1066
  raise FormulaError("the formula is empty")
1067
  if len(source) > MAX_SOURCE:
 
1071
  # Python 3.12 warns while parsing them even though the string is valid for this grammar.
1072
  with warnings.catch_warnings():
1073
  warnings.simplefilter("ignore", SyntaxWarning)
1074
+ parsed = ast.parse(_rewrite(source, sheet), mode="eval")
1075
  except (SyntaxError, ValueError) as exc:
1076
  raise FormulaError("the formula could not be parsed") from exc
1077
  if sum(1 for _ in ast.walk(parsed)) > MAX_NODES:
 
2193
  return {"values": {key: values.get(key) for key in definitions}, "errors": errors}
2194
 
2195
 
2196
+ def _sheet_half(key):
2197
+ """The tab a lookup key names, upper cased, or "" when the key is a bare address."""
2198
+ text = str(key)
2199
+ return text.rsplit("!", 1)[0].upper() if "!" in text else ""
2200
+
2201
+
2202
+ def _unknown_sheets(definition, known):
2203
+ """Every tab this formula points at that the workbook does not have, in the order found.
2204
+
2205
+ β›” IT WALKS `definition["cells"]`, NOT THE EVALUATOR'S NODE LOOKUP, AND THAT IS THE POINT.
2206
+ `_range_arg` treats a key missing from `row` as a BLANK CELL on purpose, because a rectangle
2207
+ almost always contains empty cells; so a check living in the lookup would catch
2208
+ `='Ghost'!A1` and let `=SUM('Ghost'!A1:B9)` answer a confident 0. `cells` carries every
2209
+ address a formula names, scalar and range alike, so one walk covers both.
2210
+ """
2211
+ out = []
2212
+ for key in definition.get("cells") or ():
2213
+ name = _sheet_half(key)
2214
+ if name and name not in known and name not in out:
2215
+ out.append(name)
2216
+ return out
2217
+
2218
+
2219
+ def evaluate_sheet(cells, *, today=None, sheets=None):
2220
+ """Evaluate a whole WORKBOOK of A1 cells in dependency order (wave 49 W49-T03, W51-T23).
2221
 
2222
  `cells` is `{addr_key: {"formula": "=..."} or {"value": v}}` where `addr_key` is what
2223
+ `a1_key` produces: `B4` on a single unnamed tab, `SHEET2!C3` when the caller keys a workbook.
2224
+ Returns `{"values": {addr: value}, "errors": {addr: code}}`.
2225
+
2226
+ ⭐⭐ A SPEC ENTRY MAY CARRY `"sheet"`, AND THAT IS HOW A WORKBOOK GETS ONE MEMOIZED PASS
2227
+ (W51-T23). It names the tab that cell lives on, and it is handed to `parse_formula` so this
2228
+ formula's own unqualified references key as `TAB!B4` rather than `B4`. Every tab in the book
2229
+ therefore goes into ONE `cells` dict with one `resolve` memo over it, so a cross-tab reference
2230
+ is an ordinary lookup and a chain that crosses tabs twice is still computed once.
2231
+ β›” QUALIFYING THE KEYS WITHOUT `"sheet"` IS THE PROTOTYPE'S FAILURE MODE 3, MEASURED: cross-tab
2232
+ references resolve and every LOCAL one breaks, 3,770 blanks against a true 785.
2233
+
2234
+ `sheets` is the list of tab names the workbook actually has. When it is supplied, a formula
2235
+ naming a tab outside it is refused `unknown_sheet` rather than quietly reading as blank; when
2236
+ it is None nothing is checked, so every wave-49 caller keeps its behaviour exactly.
2237
+
2238
+ ⚠ `SHEET_ADDR_KEY` IS STILL HANDED THE FULL KEY, and `ROW()` / `COLUMN()` still answer,
2239
+ because `_call` splits an address at its last `!` before `_split_addr` reads it. That split
2240
+ lands the same way for `G4` and for `TAB05!G4`, so the bare and the argument spelling both
2241
+ survive a workbook pass. It has its own gate leg because it does not look like it would.
2242
 
2243
  β›”β›” **THE REFUSAL IS `circular_reference`, AND IT IS DELIBERATELY NOT THE `"cycle"` THAT
2244
  `evaluate_fields` ALREADY USES.** Renaming that one was considered and rejected on evidence:
 
2257
  """
2258
  values, errors, active, resolved = {}, {}, [], set()
2259
  parsed = {}
2260
+ known = None if sheets is None else {str(n).upper() for n in sheets if str(n or "")}
2261
 
2262
  for addr, spec in (cells or {}).items():
2263
  if not isinstance(spec, dict):
 
2276
  raw = spec.get("formula")
2277
  if isinstance(raw, str) and raw.strip().startswith("="):
2278
  try:
2279
+ definition = parse_formula(raw.strip()[1:], sheet=str(spec.get("sheet") or ""))
2280
  except FormulaError:
2281
  errors[addr] = "bad_formula"
2282
  values[addr] = None
2283
+ continue
2284
+ # β›” A MISSING TAB IS ITS OWN REFUSAL, NOT A BLANK. Left to the lookup it would read as
2285
+ # `unknown_ref` at best and as a confident 0 through a range at worst, and both send
2286
+ # the reader to inspect a formula that is correct except for a tab that is not there.
2287
+ if known is not None and _unknown_sheets(definition, known):
2288
+ errors[addr] = "unknown_sheet"
2289
+ values[addr] = None
2290
+ continue
2291
+ parsed[addr] = definition
2292
  else:
2293
  values[addr] = spec.get("value")
2294
 
api/routes_grid.py CHANGED
@@ -108,7 +108,7 @@ def _scope_or_400(raw):
108
  return scope
109
  if scope not in _SCOPES:
110
  raise err(400, "bad_scope",
111
- f"scope must be one of {', '.join(_SCOPES)} β€” refusing to guess")
112
  return scope
113
 
114
 
@@ -814,7 +814,7 @@ def grid_timeseries(body: dict = Body(default=None), scope: str = "customer",
814
  _sc = _scope_or_400(scope)
815
  if _sc == "product" or _sc.startswith("ut_"):
816
  raise err(400, "bad_timeseries",
817
- "this surface has no time-series channel β€” measures are customer-grain")
818
 
819
  body = body or {}
820
  bucket = body.get("bucket")
@@ -1084,7 +1084,7 @@ def grid_calendar_metrics(body: dict = Body(default=None), scope: str = "custome
1084
  _sc_cal = _scope_or_400(scope)
1085
  if _sc_cal == "product" or _sc_cal.startswith("ut_"):
1086
  raise err(400, "bad_calendar_metrics",
1087
- "the product surface has no measure channel yet β€” measures are customer-grain")
1088
 
1089
  body = body or {}
1090
  raw_groups = body.get("groups")
@@ -1984,7 +1984,7 @@ def grid_events_route(body: dict = Body(default=None),
1984
  raise err(409, "pid_scope_unresolved",
1985
  f"this database is served through the connector mirror and its rows "
1986
  f"cannot be listed in one window, so a change addressed to particular "
1987
- f"records ({len(named)} of {len(events)} here) cannot be admitted β€” "
1988
  f"{lim.get('cause') or 'the row set is unresolved'}. "
1989
  f"{lim.get('recommendation') or ''}".strip())
1990
  else:
@@ -2026,7 +2026,7 @@ def grid_events_route(body: dict = Body(default=None),
2026
  results.append(row)
2027
  except grid_events.StoreUnavailable:
2028
  raise err(503, "store_unavailable",
2029
- "the tenant store is unavailable β€” none of your changes were saved")
2030
 
2031
  out = {"results": results, "rerender": any(r["rerender"] for r in results)}
2032
  if ctx.out.refusals:
@@ -2615,3 +2615,136 @@ def grid_hop_topics(session: Session = Depends(require_session)):
2615
  if not odoo_relational.is_royal(session.tenant):
2616
  return {"topics": [], "windows": [], "omissions": []}
2617
  return _hop_topic_offer()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  return scope
109
  if scope not in _SCOPES:
110
  raise err(400, "bad_scope",
111
+ f"scope must be one of {', '.join(_SCOPES)}. Refusing to guess")
112
  return scope
113
 
114
 
 
814
  _sc = _scope_or_400(scope)
815
  if _sc == "product" or _sc.startswith("ut_"):
816
  raise err(400, "bad_timeseries",
817
+ "this surface has no time-series channel, because measures are customer-grain")
818
 
819
  body = body or {}
820
  bucket = body.get("bucket")
 
1084
  _sc_cal = _scope_or_400(scope)
1085
  if _sc_cal == "product" or _sc_cal.startswith("ut_"):
1086
  raise err(400, "bad_calendar_metrics",
1087
+ "the product surface has no measure channel yet, because measures are customer-grain")
1088
 
1089
  body = body or {}
1090
  raw_groups = body.get("groups")
 
1984
  raise err(409, "pid_scope_unresolved",
1985
  f"this database is served through the connector mirror and its rows "
1986
  f"cannot be listed in one window, so a change addressed to particular "
1987
+ f"records ({len(named)} of {len(events)} here) cannot be admitted. "
1988
  f"{lim.get('cause') or 'the row set is unresolved'}. "
1989
  f"{lim.get('recommendation') or ''}".strip())
1990
  else:
 
2026
  results.append(row)
2027
  except grid_events.StoreUnavailable:
2028
  raise err(503, "store_unavailable",
2029
+ "the tenant store is unavailable, so none of your changes were saved")
2030
 
2031
  out = {"results": results, "rerender": any(r["rerender"] for r in results)}
2032
  if ctx.out.refusals:
 
2615
  if not odoo_relational.is_royal(session.tenant):
2616
  return {"topics": [], "windows": [], "omissions": []}
2617
  return _hop_topic_offer()
2618
+
2619
+
2620
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
2621
+ # ⭐⭐ W51-T05 / RULING R2 / CONTRACT C6 β€” RELATED DATABASES, SERVED.
2622
+ #
2623
+ # R2: *"A 'Linked database' tab exists for FORWARD link fields, REVERSE links (another table's link
2624
+ # field pointing at this table) and the ODOO BRIDGES … one tab per related table, resolved
2625
+ # server-side; two links between the same pair give two tabs subtitled by the field."*
2626
+ #
2627
+ # β›” RESOLVED SERVER-SIDE IS THE RULING, NOT AN IMPLEMENTATION NOTE. `types.ts::relationalTargets`
2628
+ # is the client's forward-only derivation and it STAYS, because it answers a different question
2629
+ # (which of MY columns is a link) on data the client already holds. It cannot see a reverse link β€”
2630
+ # that needs every other definition in the tenant β€” and it cannot see a bridge, which is not a
2631
+ # field at all. So this route is additive to it rather than a replacement for it.
2632
+ #
2633
+ # β›” `grid_pivot` CANNOT SUBSTITUTE AND D-484 IS WHY. `_PIVOT_ROUTES` declares exactly ONE pair,
2634
+ # `("customer_data", "product_data")`, while every link field on `customer_data` targets a
2635
+ # `ut_odoo_*` grid and NO link field anywhere targets `product_data`. The two halves of the
2636
+ # relational feature offer exactly disjoint sets, so the one pivot that is declared is the one that
2637
+ # is never offered. This route is the other half of that repair: it OFFERS the edges that exist.
2638
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
2639
+
2640
+ #: The two registry modules whose link fields are PRE-SET rather than tenant-authored. Their bags
2641
+ #: come from `odoo_relational.module_link_fields`, which `automation_engine` reaches by STRING
2642
+ #: (`getattr(_rel, "module_link_fields", None)`) β€” so it is read here and never moved, renamed or
2643
+ #: shadowed. `core/relations.py` declares the BRIDGES; that function keeps declaring the FIELDS.
2644
+ _PRESET_LINK_MODULES = ("customer_data", "product_data")
2645
+
2646
+
2647
+ def _may_open(session: Session, key: str):
2648
+ """May this session open `key` at all? The SAME two gates `_pivot_side` applies, minus the rows.
2649
+
2650
+ β›” THE ROWS ARE THE POINT OF THE DIFFERENCE. `_pivot_side` calls `perm_scope.scoped_table`,
2651
+ which materialises every row of the side it is checking; a listing that asked that question of
2652
+ a dozen candidate targets would read a dozen whole databases to draw a tab strip. The WALL is
2653
+ `session.require` plus `perm_scope.scoped_fields`, and both of those answer without a row.
2654
+
2655
+ ⚠ FAIL CLOSED. Any refusal, any unknown table, any error is False. A target this account may
2656
+ not open must not appear in the strip, because the tab would 403 on the first click and read as
2657
+ a broken product rather than as a permission.
2658
+ """
2659
+ import core.perm_scope as perm_scope
2660
+
2661
+ try:
2662
+ session.require(key)
2663
+ except HTTPException:
2664
+ return False
2665
+ except Exception: # noqa: BLE001
2666
+ return False
2667
+ try:
2668
+ perm_scope.scoped_fields(session.user, key, st=session.runtime)
2669
+ except Exception: # noqa: BLE001
2670
+ return False
2671
+ return True
2672
+
2673
+
2674
+ def _source_fields(session: Session, table: str):
2675
+ """The link-bearing field list for `table`, under this session's field wall.
2676
+
2677
+ β›”β›” THE PRE-SET COLUMNS ARE NOT IN `scoped_fields` AND THAT IS THE TRAP THIS FUNCTION EXISTS
2678
+ FOR. `odoo_relational.module_link_fields`' own docstring says so: *"`routes_customers` /
2679
+ `routes_products` still build their field lists from `aios_grid` alone, so today these columns
2680
+ live only inside the relational pass."* A `/related` answer built from `scoped_fields` alone
2681
+ would therefore report ZERO forward links on `customer_data` β€” the one grid that has three β€”
2682
+ and look entirely correct doing it.
2683
+ ⚠ APPENDED, NOT MERGED BY KEY: a tenant cannot author a field on a registry module, so the two
2684
+ lists cannot collide, and a union keyed on `key` would hide that if they ever did.
2685
+ """
2686
+ import core.perm_scope as perm_scope
2687
+
2688
+ try:
2689
+ fields = list(perm_scope.scoped_fields(session.user, table, st=session.runtime) or ())
2690
+ except Exception: # noqa: BLE001
2691
+ fields = []
2692
+ if table in _PRESET_LINK_MODULES:
2693
+ try:
2694
+ import odoo_relational
2695
+ fields = fields + list(odoo_relational.module_link_fields(table) or ())
2696
+ except Exception: # noqa: BLE001
2697
+ pass
2698
+ return fields
2699
+
2700
+
2701
+ def related_entries(session: Session, table: str):
2702
+ """C6's `/related` list for `table`, ALREADY NARROWED to targets this session may open.
2703
+
2704
+ `[{key, label, via: {direction, key, field?, on?, from?}, target, served, where?}]`.
2705
+
2706
+ β›” THE NARROWING HAPPENS HERE AND NOWHERE ELSE, so the listing door and the pinned read agree
2707
+ by construction: `routes_odoo_tables._compiled_read` resolves a `related` pin by calling THIS
2708
+ function, which means an edge a reader cannot be offered is also an edge they cannot pin. A
2709
+ second, laxer resolution on the read side would be a permission wall with a hole in it.
2710
+ """
2711
+ import core.relations as relations
2712
+ import core.user_tables as user_tables
2713
+
2714
+ table = str(table or "")
2715
+ defs = {}
2716
+ try:
2717
+ defs = dict(user_tables.all_defs(st=session.runtime) or {})
2718
+ except Exception: # noqa: BLE001
2719
+ defs = {}
2720
+ entries = relations.related(table, fields=_source_fields(session, table), defs=defs)
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.
2742
+ """
2743
+ table = str(table or "").strip()
2744
+ if not table:
2745
+ raise err(400, "bad_table", "name the database to list relations for")
2746
+ if not _may_open(session, table):
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)}
api/routes_odoo_tables.py CHANGED
@@ -245,7 +245,7 @@ def odoo_tables_status(brief: bool = Query(False),
245
  # why this grid still keeps its rows in the tenant document, when it does not have to
246
  "materialisedBecause": (why_not.get(key, "") if materialised else ""),
247
  "refreshed": (max([s for s in stamps if s], default="") if materialised
248
- else "live β€” read through the mirror"),
249
  "locked": table.get("recordMode") == user_tables.AUTOMATION_RECORD_MODE,
250
  # W30/R7: whether this database is served THROUGH the mirror rather than from the copy
251
  # above. Reported per table, because they convert one at a time and an operator
@@ -1222,8 +1222,209 @@ def apply_filtered_bulk(table_key: str, body: dict = Body(default=None),
1222
  _TREE_UNSET = object()
1223
 
1224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1225
  def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=None,
1226
- search=None, tree=_TREE_UNSET):
1227
  """EVERYTHING THAT DECIDES **WHICH ROWS** A CONNECTED GRID MAY ANSWER OVER, compiled once.
1228
 
1229
  Returns `{defn, fields, cur, spec, cols, base_where, wall_params, where, params, limits,
@@ -1246,6 +1447,14 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
1246
  wall refuse is unchanged. A caller that already holds a decoded tree (the aggregates door,
1247
  whose body `_selection_query` has validated) passes `tree=` instead. Exactly one of the two,
1248
  in the shape `datastore.window` uses for `table`/`from_sql`.
 
 
 
 
 
 
 
 
1249
  """
1250
  from routes_tables import _defn_or_refuse
1251
 
@@ -1392,6 +1601,25 @@ def _compiled_read(table_key, session, *, filters=None, filterConj="and", sorts=
1392
  else:
1393
  sort_spec = list(sorts or [])
1394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1395
  # R6's SECOND SENTENCE, ON THE WALL ITSELF. The precision note further down covers the
1396
  # conditions a USER sends; the same arithmetic governs the one an ADMINISTRATOR stored, and
1397
  # a scoped reader has no other way to learn that the boundary they are held to is evaluated
@@ -1496,6 +1724,7 @@ def odoo_table_rows(table_key: str,
1496
  filterConj: str = Query(default="and"),
1497
  sorts: str = Query(default=None),
1498
  search: str = Query(default=None),
 
1499
  session: Session = Depends(require_session)):
1500
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
1501
 
@@ -1509,6 +1738,16 @@ def odoo_table_rows(table_key: str,
1509
  that CANNOT (a column with no mirror expression, an op the compiler refuses) is reported in
1510
  `limits` with its cause and a recommendation β€” R6's second sentence β€” and never silently
1511
  dropped, because an ignored condition widens.
 
 
 
 
 
 
 
 
 
 
1512
  """
1513
  import aios_grid
1514
  import core.perm_scope as perm_scope
@@ -1521,7 +1760,7 @@ def odoo_table_rows(table_key: str,
1521
  # a WINDOW alone needs: the total order, the projection, the overlay merge and the two
1522
  # sentences a page earns (`window_clamped`, the deep-page walk).
1523
  read = _compiled_read(table_key, session, filters=filters, filterConj=filterConj,
1524
- sorts=sorts, search=search)
1525
  defn, fields, cur, spec = read["defn"], read["fields"], read["cur"], read["spec"]
1526
  cols, limits, frm = read["cols"], read["limits"], read["frm"]
1527
  base_where, wall_params = read["base_where"], read["wall_params"]
@@ -1868,9 +2107,13 @@ def odoo_table_aggregates(table_key: str, body: dict = Body(default=None),
1868
  session: Session = Depends(require_session)):
1869
  """SERVER-SIDE SUMMARIES over the WHOLE predicate a server-windowed grid is showing (C1).
1870
 
1871
- Body `{filters, filterConj, search, groupBy?, aggs: [{colId, agg, p?}]}`; response
1872
  `{ok, total_rows, aggregates, groups?, limits}`.
1873
 
 
 
 
 
1874
  β›”β›” THE POINT IS THAT IT IS **NOT** THE WINDOW. `/rows` answers 200 rows at a time, so a
1875
  summary computed from what arrived would change as the reader scrolled and nothing would say
1876
  so (D-159). This computes over every row the same predicate matches: the SAME predicate, from
@@ -1899,8 +2142,14 @@ def odoo_table_aggregates(table_key: str, body: dict = Body(default=None),
1899
  if group_by is not None and not isinstance(group_by, str):
1900
  raise err(400, "bad_selection", "groupBy must be a column id")
1901
 
 
 
 
 
 
1902
  read = _compiled_read(table_key, session, tree=query["filters"],
1903
- filterConj=query["filterConj"], search=query["search"])
 
1904
  out = _aggregate_over(read["cur"], read["spec"], read["cols"], read["where"],
1905
  read["params"], read["frm"], aggs, group_by=group_by,
1906
  limits=read["limits"])
 
245
  # why this grid still keeps its rows in the tenant document, when it does not have to
246
  "materialisedBecause": (why_not.get(key, "") if materialised else ""),
247
  "refreshed": (max([s for s in stamps if s], default="") if materialised
248
+ else "live, read through the mirror"),
249
  "locked": table.get("recordMode") == user_tables.AUTOMATION_RECORD_MODE,
250
  # W30/R7: whether this database is served THROUGH the mirror rather than from the copy
251
  # above. Reported per table, because they convert one at a time and an operator
 
1222
  _TREE_UNSET = object()
1223
 
1224
 
1225
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
1226
+ # ⭐⭐ W51-T05 / C6 β€” THE PINNED READ. `related: {table, record, via}` narrows this grid to the rows
1227
+ # linked to ONE record of another database, AHEAD of anything the client asked for.
1228
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
1229
+
1230
+ #: Past this many pinned ids the `IN (...)` list is worth a sentence. β›” IT IS NOT A CAP β€” standing
1231
+ #: rule 1 forbids one on connected-source data, and its SECOND sentence is the half that gets
1232
+ #: dropped: a cost that cannot be removed is REPORTED with a cause and a recommendation. A customer
1233
+ #: with 40,000 order lines gets all 40,000; they are also told why the page took a moment.
1234
+ _PIN_REPORT_AT = 20_000
1235
+
1236
+
1237
+ def _related_source_value(session, entry, record):
1238
+ """The value of the SOURCE record that this edge is keyed on.
1239
+
1240
+ ⭐ USUALLY THE RECORD ID ITSELF, and that is the cheap path: `customer_data.pid` IS the Odoo
1241
+ `res.partner` id and `ut_odoo_orders.pid` IS the `sale_order` id, so three of the five bridges
1242
+ need no lookup at all.
1243
+
1244
+ β›”β›” `product_data` IS THE EXCEPTION AND IT IS NOT AN EDGE CASE β€” it is one of the two grids R2
1245
+ names. `product_data.pid` is `crc32(default_code)` (`modules/product_data.sku_pid`), NOT an
1246
+ Odoo id, so matching it against `sale_order_line.product_id` resolves ZERO rows for every
1247
+ product, silently, and paints as "this product has never been ordered". The row's `product_id`
1248
+ column carries Odoo's own id (W33-T43 / A2) and that is what the bridge is declared on, so the
1249
+ cell has to be read off the source record.
1250
+
1251
+ ⚠⚠ THE READ IS THE SAME SCOPED ONE `_pivot_side` USES, AND IT IS **NOT** THE SAME COST, WHICH
1252
+ AN EARLIER DRAFT OF THIS DOCSTRING CLAIMED. It reads a whole module pool (5,873 products /
1253
+ 3,643 customers on tenant #0, from the prewarmed cache rather than from Odoo) and scans it
1254
+ linearly for one `pid`. `grid_pivot` pays that ONCE PER PIVOT; this path pays it ONCE PER PAGE,
1255
+ so a reader scrolling a pinned grid pays it again on every window. The frequency is the
1256
+ difference and asserting parity would have hidden it. Reported to the reader as a `limits`
1257
+ sentence by the caller, and booked as a PENDING row with a testable exit condition rather than
1258
+ left as a comment nobody costs.
1259
+
1260
+ β›” A RECORD THAT IS NOT IN THE SCOPED SET ANSWERS None, WHICH THE CALLER TURNS INTO A REFUSAL.
1261
+ Falling back to the raw `record` would pin the target grid on a value from a row this reader
1262
+ may not see, which is the permission wall leaking through the join.
1263
+ """
1264
+ import core.perm_scope as perm_scope
1265
+ import core.relations as relations
1266
+
1267
+ frm = str((entry.get("via") or {}).get("from") or relations.IDENTITY_COL)
1268
+ if frm == relations.IDENTITY_COL:
1269
+ return record
1270
+ # ⚠ STAMPED BY THE CALLER (`__source__`), not carried on the wire: an entry describes an edge
1271
+ # FROM a table, and which table that was is the caller's own question, never the client's.
1272
+ source = str(entry.get("__source__") or "")
1273
+ if not source:
1274
+ return None
1275
+ try:
1276
+ rows = perm_scope.scoped_table(session.user, source, st=session.runtime) or []
1277
+ except Exception: # noqa: BLE001
1278
+ return None
1279
+ want = str(record)
1280
+ for row in rows:
1281
+ if str(row.get("pid")) == want:
1282
+ got = row.get(frm)
1283
+ return got if got not in (None, "") else None
1284
+ return None
1285
+
1286
+
1287
+ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related):
1288
+ """`(sql, params, notes)` for C6's pinned read, or `(None, [], [])` when nothing is pinned.
1289
+
1290
+ β›”β›” WHY THIS DOES NOT CALL `compile_filter_tree(member_ids=)`, WHICH IS WHAT C6'S SENTENCE
1291
+ SAYS. Measured against `platform/harness/filter_sql.py` on 2026-09-03, that call cannot express
1292
+ a pinned read and the failure is silent in the widening direction, twice over:
1293
+
1294
+ 1. `:583` returns None the moment the tree is INACTIVE, and the `member_ids` branch is BELOW
1295
+ that return. A pin with no client filter is exactly the inactive case, so the ids would be
1296
+ dropped and the whole table served.
1297
+ 2. `:588` emits `(tree OR id_sql IN (...))`. Its own docstring: *"`member_ids` reproduces
1298
+ `members.has(r.pid) || matchFilterTree(...)`"*. That is a UNION. ORing a pin onto a
1299
+ filter WIDENS; a pinned read needs an INTERSECTION.
1300
+
1301
+ So the tail is compiled by `core.relations.pin_sql`, in `filter_sql`'s OWN spelling (proven
1302
+ byte for byte by `verify_pivot.py`, not by this comment), and ANDed in. `filter_sql.py` is lane
1303
+ B's file this wave; a narrowing member mode there is an AMENDMENT and is booked in the handoff,
1304
+ not edited in from here.
1305
+
1306
+ ⭐ `id_sql` IS PASSED EXPLICITLY, AS `spec["id"]`, AND IS NEVER DEFAULTED. `harness/semantic.py`
1307
+ defaults it to `f"{alias}.id"` inside its OWN compile calls; a call from the route layer never
1308
+ reaches that line, and `filter_sql:586` RAISES without it. It matters that it is per table
1309
+ rather than a literal `id`: `ut_odoo_order_lines` is join-shaped and its identity is `sol.id`,
1310
+ so a bare `id` would be ambiguous across `sale_order_line` and `sale_order`. It is the same
1311
+ expression this route already trusts as `tiebreak_sql` and as the fallback ORDER BY.
1312
+ """
1313
+ import core.relations as relations
1314
+
1315
+ if isinstance(related, str):
1316
+ related = _json_arg(related, "related")
1317
+ if related in (None, "", {}):
1318
+ return None, [], []
1319
+ if not isinstance(related, dict):
1320
+ raise err(400, "bad_relation",
1321
+ "`related` must be an object naming the record to pin these rows to: "
1322
+ "{table, record, via}")
1323
+
1324
+ source = str(related.get("table") or "")
1325
+ record = related.get("record")
1326
+ via = related.get("via")
1327
+ if not source or record in (None, "") or not isinstance(via, dict):
1328
+ raise err(400, "bad_relation",
1329
+ "a pinned read needs the record's database, the record id and the relation to "
1330
+ "follow, as {table, record, via}. Ask GET /api/v1/grid/" + (source or "{table}")
1331
+ + "/related for the relations this account may follow")
1332
+
1333
+ from routes_grid import _may_open, related_entries
1334
+
1335
+ if not _may_open(session, source):
1336
+ # ⚠ THE CAUSE IS NAMED AS A PAIR, ON PURPOSE. `_may_open` is fail-closed and answers False
1337
+ # both for a genuine permission refusal and for a database it could not read at all, so a
1338
+ # sentence claiming only the first would tell a reader their access was revoked when the
1339
+ # store had merely hiccupped. Naming both is honest and still refuses.
1340
+ raise err(403, "not_permitted",
1341
+ f"'{source}' could not be opened for your account, either because it is not "
1342
+ f"granted to you or because it could not be read just now, so rows here cannot "
1343
+ f"be pinned to one of its records. Ask an administrator for access to that "
1344
+ f"database, or try again")
1345
+
1346
+ # β›” RESOLVED AGAINST THE **SCOPED** LISTING, which is what makes "an edge you cannot be
1347
+ # offered is an edge you cannot pin" structural rather than remembered. `related_entries` is
1348
+ # the same function `GET /grid/{table}/related` answers with; there is no second resolution.
1349
+ entries = related_entries(session, source)
1350
+ entry = relations.pick(entries, via)
1351
+ if entry is None:
1352
+ raise err(400, "unknown_relation", relations.unknown_via_refusal(source, via))
1353
+ entry = dict(entry, __source__=source)
1354
+
1355
+ if str(entry.get("target") or "") != str(table_key):
1356
+ raise err(400, "unknown_relation",
1357
+ f"the relation '{entry.get('key')}' on '{source}' points at "
1358
+ f"'{entry.get('target')}', not at '{table_key}', so it cannot narrow this "
1359
+ f"database. Read the database the relation names, or ask for the relation that "
1360
+ f"reaches this one")
1361
+ if not entry.get("served", True):
1362
+ raise err(409, "relation_not_served", relations.unserved_target_refusal(entry))
1363
+
1364
+ on = str((entry.get("via") or {}).get("on") or "")
1365
+ # ⚠ `spec["cols"]`, NOT the caller's narrowed `cols`. The join column is a JOIN, not a value
1366
+ # this response returns: a relation must keep working when an administrator has hidden the id
1367
+ # column it runs over, and no cell of it is ever projected. The hidden-field closure still
1368
+ # governs everything that reaches the wire, one layer up.
1369
+ binding = (spec.get("cols") or {}).get(on)
1370
+ if not binding:
1371
+ raise err(409, "relation_not_served",
1372
+ f"'{table_key}' has no live expression for '{on}', which is the column this "
1373
+ f"relation joins on, so the rows cannot be narrowed to one record here. Open "
1374
+ f"this database directly, or ask for '{on}' to be added to its live connection")
1375
+ on_expr, on_cast = binding[0], binding[1]
1376
+
1377
+ value = _related_source_value(session, entry, record)
1378
+ if value in (None, ""):
1379
+ raise err(400, "unknown_relation",
1380
+ relations.unresolvable_source_refusal(source, entry))
1381
+ try:
1382
+ value = on_cast(value)
1383
+ except Exception: # noqa: BLE001
1384
+ value = str(value)
1385
+
1386
+ # ── the member ids, in ONE SQL over the bridge column (the ticket's `how:`) ────────────────
1387
+ # β›” NOT THROUGH `datastore.window`: that clamps at `WINDOW_MAX` (5,000) rows, so a customer
1388
+ # with more order lines than that would be pinned to the first 5,000 of them and the tab would
1389
+ # show a smaller, entirely plausible number with nothing red anywhere. Standing rule 1: no cap
1390
+ # on data from a connected source.
1391
+ # ⚠ THE WALL RIDES ALONG. Resolving ids under `base_where` means the id SET a scoped reader can
1392
+ # produce is already narrowed to rows they may see, so the pin cannot be used to learn how many
1393
+ # rows exist beyond their boundary.
1394
+ frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"]
1395
+ parts = [p for p in (base_where, entry.get("where")) if p]
1396
+ parts.append(f"{on_expr} = ?")
1397
+ pred = " AND ".join(f"({p})" for p in parts)
1398
+ ids = [int(r[0]) for r in cur.execute(
1399
+ f'SELECT DISTINCT {spec["id"]} FROM {frm_body} WHERE {pred}',
1400
+ list(wall_params) + [value]).fetchall() if r and r[0] is not None]
1401
+
1402
+ notes = []
1403
+ # ⭐ STANDING RULE 1'S SECOND SENTENCE, ON A COST RATHER THAN ON A CAP. Nothing is limited
1404
+ # here; the reader is told that this particular relation is answered by reading the source
1405
+ # database once per page, because it is keyed on a column rather than on the record id.
1406
+ if str((entry.get("via") or {}).get("from") or "") != relations.IDENTITY_COL:
1407
+ notes.append({
1408
+ "subject": "related", "effect": "slow",
1409
+ "cause": f"this relation is keyed on the '{entry['via']['from']}' column of "
1410
+ f"'{source}' rather than on its record id, so every page of these rows is "
1411
+ f"resolved by reading that database first",
1412
+ "recommendation": "read this database on its own and filter it on "
1413
+ f"'{on}' if you are paging through a large set"})
1414
+ if len(ids) >= _PIN_REPORT_AT:
1415
+ notes.append({
1416
+ "subject": "related", "effect": "slow",
1417
+ "cause": f"this record is linked to {len(ids):,} rows, and each page names every one "
1418
+ f"of them in the query that narrows this database to them",
1419
+ "recommendation": "add a filter beside the relation to ask a smaller question, or "
1420
+ "read this database on its own"})
1421
+
1422
+ sql, params = relations.pin_sql(spec["id"], ids)
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.
1429
 
1430
  Returns `{defn, fields, cur, spec, cols, base_where, wall_params, where, params, limits,
 
1447
  wall refuse is unchanged. A caller that already holds a decoded tree (the aggregates door,
1448
  whose body `_selection_query` has validated) passes `tree=` instead. Exactly one of the two,
1449
  in the shape `datastore.window` uses for `table`/`from_sql`.
1450
+
1451
+ ⭐⭐ `related` (W51-T05 / C6) IS `{table, record, via}` AND IT LANDS HERE FOR THE SAME REASON
1452
+ EVERYTHING ELSE DOES. β›” THE TWO DOORS SPELL IT DIFFERENTLY ON THE WIRE and that is not a
1453
+ choice: `/rows` is a GET whose predicate arrives as JSON in a query STRING (the `filters`
1454
+ precedent), `/aggregates` is a POST whose predicate arrives as a BODY KEY. This argument
1455
+ accepts either, exactly as `filters`/`tree` already does, so the pin cannot end up applied on
1456
+ one door and not the other - which would be C1's promise broken in the direction nobody
1457
+ notices, an aggregate over a whole database sitting under a tab about one record.
1458
  """
1459
  from routes_tables import _defn_or_refuse
1460
 
 
1601
  else:
1602
  sort_spec = list(sorts or [])
1603
 
1604
+ # ── W51-T05 / C6 β€” THE PIN, FOLDED INTO THE BASELINE ──────────────────────────────────────
1605
+ # β›”β›” INTO `base_where`, NOT INTO `where`, AND THE DIFFERENCE IS THREE NUMBERS ON SCREEN.
1606
+ # `base_where` is what `totalUnfiltered` counts and what the wall is made of; `where` is that
1607
+ # plus the reader's own conditions. A relation is NOT one of the reader's conditions - it is
1608
+ # the SCOPE of the tab they opened, exactly as an administrator's row wall is - so "N of M"
1609
+ # under a Linked-database tab must mean "N of M rows related to THIS record". Folding it in
1610
+ # here also means `total`, `totalUnfiltered`, the deep-page walk and C1's aggregates all
1611
+ # inherit it from the ONE compiler, which is the promise this function exists to keep: a
1612
+ # summary that ignored the pin while the window respected it would be a plausible number
1613
+ # describing a different population.
1614
+ # ⭐ AND IT IS AHEAD OF ANY CLIENT FILTER, which is C6's word for it: the predicate below is
1615
+ # ANDed on top of this, never merged into it.
1616
+ _pin_sql, _pin_params, _pin_notes = _related_pin(
1617
+ table_key, session, spec, base_where, wall_params, cur, related)
1618
+ if _pin_sql:
1619
+ base_where = f"({base_where}) AND {_pin_sql}" if base_where else _pin_sql
1620
+ wall_params = list(wall_params) + list(_pin_params)
1621
+ limits.extend(_pin_notes)
1622
+
1623
  # R6's SECOND SENTENCE, ON THE WALL ITSELF. The precision note further down covers the
1624
  # conditions a USER sends; the same arithmetic governs the one an ADMINISTRATOR stored, and
1625
  # a scoped reader has no other way to learn that the boundary they are held to is evaluated
 
1724
  filterConj: str = Query(default="and"),
1725
  sorts: str = Query(default=None),
1726
  search: str = Query(default=None),
1727
+ related: str = Query(default=None),
1728
  session: Session = Depends(require_session)):
1729
  """ONE WINDOW over a connected grid, read straight from the mirror (contract C2).
1730
 
 
1738
  that CANNOT (a column with no mirror expression, an op the compiler refuses) is reported in
1739
  `limits` with its cause and a recommendation β€” R6's second sentence β€” and never silently
1740
  dropped, because an ignored condition widens.
1741
+
1742
+ ⭐⭐ `related` (W51-T05 / C6) IS A **JSON QUERY STRING**, copying the `filters` precedent one
1743
+ argument over: `?related={"table":"customer_data","record":1234,"via":{...}}`. It narrows this
1744
+ window to the rows linked to that ONE record, ahead of `filters`, and `total` /
1745
+ `totalUnfiltered` count inside the pin rather than around it.
1746
+ β›” `routes_connected_tables.connected_table_rows` - the source-neutral ALIAS onto this
1747
+ function - forwards its arguments BY NAME and does not forward this one, so a pinned read must
1748
+ name THIS route. That file is in no lane's fence this wave; the one-line forward is booked in
1749
+ W51-T05's handoff. Degrading to an UNPINNED read is the behaviour that shipped rather than a
1750
+ new wrong answer, which is the one direction this gap is allowed to be wrong in.
1751
  """
1752
  import aios_grid
1753
  import core.perm_scope as perm_scope
 
1760
  # a WINDOW alone needs: the total order, the projection, the overlay merge and the two
1761
  # sentences a page earns (`window_clamped`, the deep-page walk).
1762
  read = _compiled_read(table_key, session, filters=filters, filterConj=filterConj,
1763
+ sorts=sorts, search=search, related=related)
1764
  defn, fields, cur, spec = read["defn"], read["fields"], read["cur"], read["spec"]
1765
  cols, limits, frm = read["cols"], read["limits"], read["frm"]
1766
  base_where, wall_params = read["base_where"], read["wall_params"]
 
2107
  session: Session = Depends(require_session)):
2108
  """SERVER-SIDE SUMMARIES over the WHOLE predicate a server-windowed grid is showing (C1).
2109
 
2110
+ Body `{filters, filterConj, search, related?, groupBy?, aggs: [{colId, agg, p?}]}`; response
2111
  `{ok, total_rows, aggregates, groups?, limits}`.
2112
 
2113
+ ⚠ `related` IS A BODY KEY HERE AND A JSON QUERY STRING ON `/rows`. Same object either way
2114
+ (`{table, record, via}`), same compiler, two transports - because this door is a POST and that
2115
+ one is a GET, and the wire cannot be identical when the method is not.
2116
+
2117
  β›”β›” THE POINT IS THAT IT IS **NOT** THE WINDOW. `/rows` answers 200 rows at a time, so a
2118
  summary computed from what arrived would change as the reader scrolled and nothing would say
2119
  so (D-159). This computes over every row the same predicate matches: the SAME predicate, from
 
2142
  if group_by is not None and not isinstance(group_by, str):
2143
  raise err(400, "bad_selection", "groupBy must be a column id")
2144
 
2145
+ # β›”οΏ½οΏ½οΏ½ THE PIN RIDES THE **SAME** COMPILER, AND THIS ONE LINE IS THE WHOLE OF CORRECTION (3).
2146
+ # `/rows` takes `related` as a JSON query STRING and this door takes it as a BODY KEY; a worker
2147
+ # who assumed both were bodies would have wired the rows and left the summaries answering over
2148
+ # the entire database under a tab that names one record. `_compiled_read` accepts either shape,
2149
+ # so the two doors cannot pin differently without this argument being deleted.
2150
  read = _compiled_read(table_key, session, tree=query["filters"],
2151
+ filterConj=query["filterConj"], search=query["search"],
2152
+ related=payload.get("related"))
2153
  out = _aggregate_over(read["cur"], read["spec"], read["cols"], read["where"],
2154
  read["params"], read["frm"], aggs, group_by=group_by,
2155
  limits=read["limits"])
api/routes_sheet.py CHANGED
@@ -5,6 +5,14 @@ WHAT GOES HERE:
5
  Contract C1's routes over `platform/core/sheets.py`: list, create, read, replace, plus the three
6
  doors that RESOLVE something and are therefore built by later tickets in this lane.
7
 
 
 
 
 
 
 
 
 
8
  ⭐ **THE WALL HERE IS THE ORDINARY SESSION, AND THAT IS THE WHOLE POINT OF THE SPLIT.** Any signed
9
  in user may own a workbook, so a workbook needs no per-database permission. A CELL is different: it
10
  names a database, and W49-T04 puts the per-database wall on the doors that read one, per contract
@@ -27,7 +35,12 @@ while its surface is a 404.
27
  (standing rule 2), and each names both the cause and the subject.
28
  """
29
 
30
- from fastapi import APIRouter, Body, Depends, HTTPException
 
 
 
 
 
31
 
32
  from deps import Session, err, require_session
33
 
@@ -121,7 +134,16 @@ def _view_filter(session: Session, database: str, view_id: str, view_name: str =
121
  # ⚠ `TableStore(table_key, st=...)`, in that order. `st` is the STORE HANDLE, and passing the
122
  # session's runtime is what makes the lookup read THIS tenant's bucket rather than tenant #0's.
123
  store = table_store.TableStore(database, st=session.runtime)
124
- found = store.find_view(view_id, prefer_owner=session.uname)
 
 
 
 
 
 
 
 
 
125
  if not found:
126
  raise err(409, "view_missing", f"View {view_name or view_id} no longer exists.")
127
  _owner, view = found
@@ -129,9 +151,57 @@ def _view_filter(session: Session, database: str, view_id: str, view_name: str =
129
  return rot._fe().tree_parts((view or {}).get("filters"))
130
 
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  def _refuse(exc):
133
- """Turn a `SheetRefusal` into the HTTP answer that names it."""
134
- status = 404 if exc.code == "workbook_missing" else 409 if exc.code.endswith("_stale") else 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  return err(status, exc.code, exc.message)
136
 
137
 
@@ -139,11 +209,229 @@ def _store(session: Session):
139
  return session.runtime
140
 
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  @router.get("/sheets")
143
  def list_sheets(session: Session = Depends(require_session)):
144
- """The workbook list, identity only. Cells never ride this door."""
 
 
 
145
  from core import sheets
146
- return {"workbooks": sheets.list_workbooks(_store(session))}
 
147
 
148
 
149
  @router.post("/sheets", status_code=201)
@@ -171,13 +459,34 @@ def create_sheet(body: dict = Body(default=None), session: Session = Depends(req
171
  #
172
  # ⚠ `Depends(require_session)` ONLY, like every other door in this file, and that is correct: the
173
  # Sheet is granted to everyone, and the rail's folders name no database.
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
 
176
  @router.get("/sheets/index")
177
  def read_sheet_index(session: Session = Depends(require_session)):
178
- """`{workbooks, folders, itemFolders, starred}` for the Sheet rail in ONE read."""
 
 
 
 
 
 
 
 
 
179
  from core import sheets
180
- return {"index": sheets.read_index(_store(session))}
181
 
182
 
183
  @router.put("/sheets/index")
@@ -188,24 +497,332 @@ def write_sheet_index(body: dict = Body(default=None),
188
  ⭐ `repairs` RIDES BACK OUT. `core.sheets.save_folders` records every change it made to the
189
  payload, and the rail says so in a sentence rather than letting a workbook reappear at the
190
  top level with no explanation (R16). Dropping this key is what makes a silent repair.
 
 
 
 
 
 
 
191
  """
192
  from core import sheets
193
  raw = dict(body or {})
194
  try:
195
  out = sheets.save_folders(_store(session), raw.get("folders"),
196
- raw.get("itemFolders"), starred=raw.get("starred"))
 
197
  except sheets.SheetRefusal as exc:
198
  raise _refuse(exc)
199
- return {"index": out}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
 
202
  @router.get("/sheets/{workbook_id}")
203
- def read_sheet(workbook_id: str, session: Session = Depends(require_session)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  from core import sheets
205
  try:
206
- return {"workbook": sheets.get_workbook(_store(session), workbook_id)}
 
 
207
  except sheets.SheetRefusal as exc:
208
  raise _refuse(exc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
 
211
  @router.put("/sheets/{workbook_id}")
@@ -216,9 +833,15 @@ def write_sheet(workbook_id: str, body: dict = Body(default=None),
216
  ⚠ `rev` in the body makes the write CONDITIONAL. Omit it and the last writer wins; send the
217
  `rev` you read and a concurrent change answers `workbook_revision_stale` instead of being
218
  silently overwritten.
 
 
219
  """
220
  from core import sheets
221
  raw = dict(body or {})
 
 
 
 
222
  try:
223
  # `rev` inside the body IS the expectation; `core.sheets.put_workbook` reads it. This door
224
  # does not translate it into a second argument, because two ways to say the same thing is
@@ -231,14 +854,113 @@ def write_sheet(workbook_id: str, body: dict = Body(default=None),
231
 
232
  @router.delete("/sheets/{workbook_id}")
233
  def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
 
 
 
 
 
 
 
 
 
234
  from core import sheets
235
  try:
 
236
  removed = sheets.delete_workbook(_store(session), workbook_id)
237
  except sheets.SheetRefusal as exc:
238
  raise _refuse(exc)
239
  return {"deleted": bool(removed)}
240
 
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  # ── the doors that RESOLVE, and are therefore later tickets ──────────────────────────────────
243
  #
244
  # ⭐ Each is declared here so the surface exists and `main.py` needs no second edit, and each
@@ -256,6 +978,14 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
256
 
257
  ⚠ Each distinct `view_id` is resolved ONCE. `table_store.find_view` runs a legacy migration on
258
  every call, so resolving per cell would make a forty-cell refresh do forty migrations.
 
 
 
 
 
 
 
 
259
  """
260
  from core import sheets
261
  from modules import sheet as sheet_mod
@@ -263,6 +993,7 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
263
 
264
  try:
265
  book = sheets.get_workbook(_store(session), workbook_id)
 
266
  except sheets.SheetRefusal as exc:
267
  raise _refuse(exc)
268
 
@@ -309,14 +1040,26 @@ def refresh_sheet(workbook_id: str, session: Session = Depends(require_session))
309
  else:
310
  cell.pop("limits", None)
311
 
 
 
 
 
 
 
 
 
 
 
 
312
  _recompute_formulas(book, fr, sheet_mod)
 
313
  try:
314
  saved = sheets.put_workbook(_store(session), workbook_id,
315
  {"name": book.get("name"), "sheets": book.get("sheets"),
316
  "refreshed_at": stamp, "rev": book.get("rev")})
317
  except sheets.SheetRefusal as exc:
318
  raise _refuse(exc)
319
- return {"workbook": saved}
320
 
321
 
322
  def _now_iso():
@@ -324,44 +1067,85 @@ def _now_iso():
324
  return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
325
 
326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  def _recompute_formulas(book, fr, sheet_mod):
328
- """Re-evaluate every formula cell across the workbook, per tab, in dependency order.
 
 
 
 
 
 
 
329
 
330
  β›” A REFUSED INPUT PROPAGATES; IT DOES NOT BECOME ZERO (C2, and W49-T09 hardens it further).
331
  A cell whose value is None because the database refused is handed to the engine as absent, so
332
  arithmetic over it stays None rather than silently counting it as nothing.
333
  """
334
- for tab in book.get("sheets") or ():
335
- cells = tab.get("cells") or {}
336
- spec = {}
337
- for addr, cell in cells.items():
 
338
  if not isinstance(cell, dict):
339
  continue
 
340
  if cell.get("kind") == "formula" and cell.get("formula"):
341
- spec[addr] = {"formula": cell["formula"]}
342
  elif cell.get("state") == "refused":
343
  # β›”β›” CARRIED AS A REFUSAL, NOT DROPPED (W49-T09, C2). Leaving a refused cell OUT
344
  # of the inputs is the defect, not the safe option: MEASURED, `=SUM(B4:B8)` with B4
345
  # merely absent answers **3.0 with no error**, while the same range with B4 REFUSED
346
  # answers None and names the cause. Dropping it turns a refusal into a smaller
347
  # total that looks entirely reasonable.
348
- spec[addr] = {"refused": (cell.get("refusal") or {}).get("code") or "refused"}
349
  else:
350
- spec[addr] = {"value": cell.get("value")}
351
- if not any("formula" in v for v in spec.values()):
352
- continue
353
- out = fr.evaluate_sheet(spec)
354
- for addr, cell in cells.items():
 
 
 
355
  if not isinstance(cell, dict) or cell.get("kind") != "formula":
356
  continue
357
- code = (out.get("errors") or {}).get(addr)
358
  if code:
359
  cell["state"] = "refused"
360
  cell["value"] = None
361
  cell["refusal"] = {"code": code, "message": _formula_message(code)}
362
  else:
363
  cell["state"] = "fresh"
364
- cell["value"] = (out.get("values") or {}).get(addr)
365
  cell["display"] = "" if cell["value"] is None else str(cell["value"])
366
  cell.pop("refusal", None)
367
 
@@ -382,6 +1166,10 @@ def _formula_message(code, subject=""):
382
  "circular_reference": "This formula refers back to itself, so it has no value.",
383
  "bad_formula": "This formula could not be read.",
384
  "unknown_ref": "This formula points at a cell that is not filled in.",
 
 
 
 
385
  "div_zero": "This formula divides by zero.",
386
  # ── W50-T16's two diagnostic codes (lane B), worded by lane B, added by W50-T20 ────────
387
  #
@@ -456,6 +1244,23 @@ def _resolve_binding(session: Session, raw_binding, *, today=None):
456
  wall_nodes=wall_nodes, wall_conj=wall_conj, today=today)
457
  except sheet_mod.SheetRefusal as exc:
458
  raise err(400, exc.code, exc.message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
 
460
  row = cur.execute(sql, params).fetchone()
461
  value = row[0] if row else None
 
5
  Contract C1's routes over `platform/core/sheets.py`: list, create, read, replace, plus the three
6
  doors that RESOLVE something and are therefore built by later tickets in this lane.
7
 
8
+ ⭐⭐ **WAVE 51 ADDS C3's THREE DOORS, AND THEY EXIST BECAUSE THE CAPS MOVED (A1).** With the byte
9
+ cap at 16 MiB a whole-document PUT can now legitimately be a 16 MB upload PER COMMIT, so C3 splits
10
+ reading and writing by TAB: `GET /sheets/{id}?tabs=meta` is the workbook without any cells,
11
+ `GET /sheets/{id}/tabs/{tab}` is the one tab a person has open, and
12
+ `PATCH /sheets/{id}/tabs/{tab}/cells` saves the range that changed. PUT stays exactly as it was and
13
+ is what a STRUCTURE change still uses, so a client that finds the PATCH door missing falls back to
14
+ it and says so.
15
+
16
  ⭐ **THE WALL HERE IS THE ORDINARY SESSION, AND THAT IS THE WHOLE POINT OF THE SPLIT.** Any signed
17
  in user may own a workbook, so a workbook needs no per-database permission. A CELL is different: it
18
  names a database, and W49-T04 puts the per-database wall on the doors that read one, per contract
 
35
  (standing rule 2), and each names both the cause and the subject.
36
  """
37
 
38
+ import os
39
+ import tempfile
40
+ import threading
41
+ import uuid
42
+
43
+ from fastapi import APIRouter, Body, Depends, File, HTTPException, UploadFile
44
 
45
  from deps import Session, err, require_session
46
 
 
134
  # ⚠ `TableStore(table_key, st=...)`, in that order. `st` is the STORE HANDLE, and passing the
135
  # session's runtime is what makes the lookup read THIS tenant's bucket rather than tenant #0's.
136
  store = table_store.TableStore(database, st=session.runtime)
137
+ # ⭐⭐ `include_trashed=True` IS R11, AND IT IS ONE KEYWORD BECAUSE THE DEFAULT MUST NOT MOVE
138
+ # (wave 51, W51-T26). A deleted view is MOVED into `<owner>.trash`, so the bare scan answered
139
+ # None and this door refused a cell whose view somebody deleted an hour ago and can still
140
+ # restore with one click. R11: the cell keeps working for the whole 30 days, and the view's
141
+ # filter is copied into the cell's own scope only at PURGE. "Missing" and "trashed" stay
142
+ # different answers - an EXPIRED entry is not offered, so this still refuses by name.
143
+ # β›” THE FLAG IS OPT IN RATHER THAN THE DEFAULT because eight other callers of `find_view` are
144
+ # permission-adjacent (shares, starred, publish, forms); widening there would open doors no
145
+ # ticket asked about, with every gate green.
146
+ found = store.find_view(view_id, prefer_owner=session.uname, include_trashed=True)
147
  if not found:
148
  raise err(409, "view_missing", f"View {view_name or view_id} no longer exists.")
149
  _owner, view = found
 
151
  return rot._fe().tree_parts((view or {}).get("filters"))
152
 
153
 
154
+ #: β›” THE TWO CAP CODES ANSWER 413, NOT 400 (contract C3). A 400 says the request was malformed and
155
+ #: sends a client looking for a typo; these two say the request was perfectly well formed and the
156
+ #: DOCUMENT it would produce cannot be stored, which is what 413 means and is the only status a
157
+ #: client can branch on to show the server's own sentence inline instead of a generic error.
158
+ _CAP_CODES = ("sheet_too_many_cells", "workbook_too_large")
159
+
160
+ #: The refusals that mean "that thing is not here", answered 404 so a client can tell a missing
161
+ #: workbook from a malformed one without reading the sentence.
162
+ _MISSING_CODES = ("workbook_missing", "tab_missing")
163
+
164
+ #: β›”β›” C5's TWO SHARING REFUSALS ANSWER 403, AND THE TUPLE EXISTS BECAUSE THE FALL-THROUGH BELOW
165
+ #: IS 400 (wave 51, W51-T25). Without this branch `workbook_read_only` would arrive as a NAMED 400
166
+ #: carrying a perfectly correct sentence, so nothing on a screen would look wrong and every client
167
+ #: branching on the status would read a permission refusal as a malformed request. A 400 says
168
+ #: "fix your request"; these two say the request was exactly right and this account may not make
169
+ #: it, which is what 403 means and is the only status a client can act on.
170
+ #:
171
+ #: `workbook_read_only` is a VIEWER at a write door; `workbook_owner_only` is a non-owner at a
172
+ #: door C5 reserves for the owner (the two share doors, and DELETE). Two codes rather than one
173
+ #: because they send the reader to two different places: one asks for edit access, the other
174
+ #: cannot be granted at all.
175
+ _FORBIDDEN_CODES = ("workbook_read_only", "workbook_owner_only")
176
+
177
+
178
  def _refuse(exc):
179
+ """Turn a `SheetRefusal` into the HTTP answer that names it.
180
+
181
+ ⭐⭐ THE 409's SHAPE IS COPIED, NOT INVENTED. `{"error": {"code", "message", "rev_current"}}`
182
+ is byte for byte what `main.py::_view_revision_stale` and `routes_tables.py::delete_table_view`
183
+ already ship for `view_revision_stale`, so one class of refusal does not arrive in two shapes
184
+ depending on which module the user happened to be in. `deps.err` shapes `{code, message}` and
185
+ nothing else, so the 409 and the 413 are raised here directly rather than by bending `err`,
186
+ which would change the error shape of every route in the app.
187
+
188
+ ⚠ `workbook_revision_stale` (the PUT door's code) ALSO ENDS `_stale` and still lands here. It
189
+ carries no `rev_current`, so its body is unchanged and the client's existing PUT branch keeps
190
+ working. ⭐ D-639's `index_revision_stale` lands here too and DOES carry one, so the rail's
191
+ new guard needed no branch of its own: matching the family's spelling was the whole cost.
192
+ """
193
+ if exc.code in _CAP_CODES:
194
+ return HTTPException(status_code=413,
195
+ detail={"error": {"code": exc.code, "message": exc.message}})
196
+ if exc.code.endswith("_stale"):
197
+ body = {"code": exc.code, "message": exc.message}
198
+ current = getattr(exc, "rev_current", None)
199
+ if current is not None:
200
+ body["rev_current"] = int(current)
201
+ return HTTPException(status_code=409, detail={"error": body})
202
+ if exc.code in _FORBIDDEN_CODES:
203
+ return err(403, exc.code, exc.message)
204
+ status = 404 if exc.code in _MISSING_CODES else 400
205
  return err(status, exc.code, exc.message)
206
 
207
 
 
209
  return session.runtime
210
 
211
 
212
+ # ── C5: WORKBOOK SHARING (wave 51, W51-T25, rulings R13 + R16) ───────────────────────────────
213
+ #
214
+ # ⭐⭐ THE GRANTS LIVE IN `core.shares`, THE ONE REGISTRY FOR EVERY SHAREABLE OBJECT (wave 20,
215
+ # owner R10). `kind='workbook'` is a member of its `KINDS` tuple and that is the WHOLE cost of the
216
+ # new kind: every predicate in that module treats `kind` as an opaque bucket key, so this file
217
+ # gets `grants / set_grants / role_for / may_administer / shared_with / drop_objects` without a
218
+ # fourth permission decision in a fourth file.
219
+ #
220
+ # β›”β›” AND IT IS NOT STORED ON THE INDEX ROW, WHICH IS THE OBVIOUS SPELLING AND IS A DEFECT.
221
+ # `core.sheets._index_upsert` rebuilds the row from the DOCUMENT on every save, so a `shares` key
222
+ # living there would be deleted by the next PATCH of any cell with nothing going red. The join
223
+ # happens at READ time (`core.sheets.project_shares`), which makes that failure impossible rather
224
+ # than guarded. The full argument is at the join.
225
+ #
226
+ # β›” `workbook` IS DELIBERATELY ABSENT FROM `core.shares.RESHARE_KINDS`. C5 says the share doors
227
+ # are the OWNER's, and leaving the kind out of that tuple is what enforces it: `may_administer`
228
+ # answers True for an `edit` grantee ONLY on a kind listed there, so an editor of a workbook can
229
+ # change cells and cannot change who else reaches it. Adding the kind to that tuple would widen
230
+ # this in one line, from another file, with nothing here to notice.
231
+
232
+ #: C5's wire words, and the registry's. β›” TWO SPELLINGS OF ONE FACT IS HOW ONE OF THEM ENDS UP
233
+ #: IGNORED, so the translation is exactly two functions in exactly this file: the registry's
234
+ #: `('view', 'edit')` is what is STORED and what `role_for` returns, and C5's `viewer` / `editor`
235
+ #: is what crosses the wire. Nothing else in the app may spell either mapping.
236
+ _WIRE_ROLE = {"view": "viewer", "edit": "editor"}
237
+ _STORE_ROLE = {"viewer": "view", "editor": "edit"}
238
+
239
+
240
+ def wire_role(role):
241
+ """A stored registry role as C5's wire word, or `""` for anything that is not a role."""
242
+ return _WIRE_ROLE.get(str(role or "").strip().lower(), "")
243
+
244
+
245
+ def store_role(role):
246
+ """C5's wire word as the registry role to store, or `""` when the client named neither.
247
+
248
+ ⚠ `""` RATHER THAN A DEFAULT. A body that says `role: "admin"` has asked for something this
249
+ door does not offer, and quietly storing `view` would hand back a 200 for a request that was
250
+ refused in substance. The caller turns the empty string into a named refusal.
251
+ """
252
+ return _STORE_ROLE.get(str(role or "").strip().lower(), "")
253
+
254
+
255
+ def _sheet_refusal(code, subject=""):
256
+ """The HTTP answer for one C5 refusal, worded ONCE in `modules/sheet.py::REFUSALS`.
257
+
258
+ ⚠ It returns the exception rather than raising it, exactly as `_refuse` does, so a caller
259
+ reads `raise _sheet_refusal(...)` and the status still comes from the ONE table that maps a
260
+ Sheet code to a status.
261
+ """
262
+ from modules import sheet as sheet_mod
263
+ return _refuse(sheet_mod.SheetRefusal(code, subject))
264
+
265
+
266
+ def _workbook_owner(book):
267
+ """Who OWNS a workbook: the document's `created_by`, folded to the identity a session has.
268
+
269
+ ⭐ `created_by` IS `session.uname` AND THE TWO ARE THE SAME STRING. `create_sheet` passes
270
+ `created_by=session.uname` and `Session.uname` is `user["username"]`, so "did this account
271
+ make this workbook" is decidable from the document alone and needs no second record. That
272
+ matters because the grant registry has no owner for a workbook until its first share is
273
+ written, and the creator must be able to write that first share.
274
+ """
275
+ return str((book or {}).get("created_by") or "").strip().lower()
276
+
277
+
278
+ def _role_on_workbook(session: Session, book):
279
+ """`'owner' | 'edit' | 'view' | None` for this session on this workbook, fail-closed.
280
+
281
+ β›” THE DOCUMENT DECIDES OWNERSHIP AND THE REGISTRY DECIDES GRANTS, and the order is that way
282
+ round because a workbook that has never been shared has no registry record at all. Asking
283
+ `shares.role_for` alone would answer `None` for the person who created it.
284
+ """
285
+ from core import shares
286
+ if session.admin:
287
+ return "owner"
288
+ me = str(session.uname or "").strip().lower()
289
+ if me and _workbook_owner(book) == me:
290
+ return "owner"
291
+ return shares.role_for("workbook", book.get("id"), me, st=_store(session))
292
+
293
+
294
+ def _require_editor(session: Session, book):
295
+ """Refuse 403 `workbook_read_only` unless this session may CHANGE the workbook.
296
+
297
+ β›”β›” EVERY WRITE DOOR CALLS THIS BEFORE ITS REVISION COMPARISON, AND THE ORDER IS THE POINT.
298
+ A viewer holding a stale `rev` who is checked the other way round is told the document changed
299
+ somewhere else, which is true and is not why they were refused: they would refetch, retry, and
300
+ be refused again with the same wrong sentence forever. The refusal has to name the reason the
301
+ write can never succeed.
302
+ """
303
+ if _role_on_workbook(session, book) in ("owner", "edit"):
304
+ return
305
+ raise _sheet_refusal("workbook_read_only", _workbook_owner(book) or "its owner")
306
+
307
+
308
+ def _require_owner(session: Session, book):
309
+ """Refuse 403 `workbook_owner_only` unless this session OWNS the workbook (C5)."""
310
+ if _role_on_workbook(session, book) == "owner":
311
+ return
312
+ raise _sheet_refusal("workbook_owner_only", _workbook_owner(book) or "its owner")
313
+
314
+
315
+ def _wire_shares(rows):
316
+ """Translate each index row's `shares` into C5's role words, in place on a fresh list.
317
+
318
+ `core.sheets.project_shares` joins the REGISTRY's words onto the row; this is the boundary
319
+ where they become C5's, and it is the only one.
320
+ """
321
+ out = []
322
+ for row in rows or ():
323
+ row = dict(row)
324
+ row["shares"] = [{"who": s.get("who"), "role": wire_role(s.get("role"))}
325
+ for s in (row.get("shares") or [])
326
+ if wire_role(s.get("role"))]
327
+ out.append(row)
328
+ return out
329
+
330
+
331
+ def _wire_index(index):
332
+ """One rail document with C5's role words on every row."""
333
+ out = dict(index or {})
334
+ out["workbooks"] = _wire_shares(out.get("workbooks"))
335
+ return out
336
+
337
+
338
+ def _reresolved_for_reader(session: Session, book):
339
+ """A COPY of `book` whose every bound cell was recomputed under THIS reader's scope (C5).
340
+
341
+ β›”β›” IN MEMORY, AND IT MUST NEVER PERSIST. `refresh_sheet` runs the same loop and ends with
342
+ `put_workbook`, and a read path that copied that body would write the READER's numbers into
343
+ the OWNER's document: the same leak as serving stale owner values, in the opposite direction,
344
+ caused by a GET, and therefore reachable by anybody the workbook was shared with. So this
345
+ works on a `copy.deepcopy` and returns it, and nothing here touches the store.
346
+
347
+ ⭐ THE WALL RUNS ONCE PER DISTINCT DATABASE, exactly as `refresh_sheet` does (R16): a reader
348
+ who has lost access to a bound database is refused on every cell of it rather than shown the
349
+ owner's cached number.
350
+
351
+ ⚠ `refreshedFor` IS STAMPED ONLY WHEN A BOUND CELL WAS ACTUALLY RECOMPUTED. A workbook of
352
+ literals has nothing to re-resolve, and a stamp there would be a claim with nothing behind it.
353
+ """
354
+ import copy as _copy
355
+ fresh = _copy.deepcopy(book)
356
+ stamp = _now_iso()
357
+ seen_db = {}
358
+ touched = 0
359
+ for tab in fresh.get("sheets") or ():
360
+ for _addr, cell in (tab.get("cells") or {}).items():
361
+ if not isinstance(cell, dict) or cell.get("kind") != "bound":
362
+ continue
363
+ touched += 1
364
+ binding = cell.get("binding") or {}
365
+ db = str(binding.get("database") or "")
366
+ if db not in seen_db:
367
+ try:
368
+ _require_database(session, db)
369
+ seen_db[db] = None
370
+ except Exception as exc: # noqa: BLE001
371
+ seen_db[db] = exc
372
+ failure = seen_db.get(db)
373
+ if failure is not None:
374
+ cell["state"] = "refused"
375
+ cell["value"] = None
376
+ cell["refusal"] = {"code": "database_unreadable",
377
+ "message": f"You cannot read {db}."}
378
+ cell.pop("limits", None)
379
+ continue
380
+ try:
381
+ out = _resolve_binding(session, binding)
382
+ except HTTPException as exc:
383
+ detail = getattr(exc, "detail", None) or {}
384
+ info = detail.get("error") if isinstance(detail, dict) else None
385
+ cell["state"] = "refused"
386
+ cell["value"] = None
387
+ cell["refusal"] = {
388
+ "code": (info or {}).get("code", "sheet_unresolved"),
389
+ "message": (info or {}).get("message", "This cell could not be refreshed."),
390
+ }
391
+ continue
392
+ cell["state"] = "fresh"
393
+ cell["value"] = out["value"]
394
+ cell["display"] = "" if out["value"] is None else str(out["value"])
395
+ cell["refreshed_at"] = stamp
396
+ cell.pop("refusal", None)
397
+ if out["limits"]:
398
+ cell["limits"] = out["limits"]
399
+ else:
400
+ cell.pop("limits", None)
401
+ if not touched:
402
+ return fresh
403
+ # ⭐ EVERY FORMULA IS RE-EVALUATED TOO, over the numbers this reader is entitled to. Leaving
404
+ # them alone would serve the owner's totals sitting on top of the reader's inputs, which is
405
+ # the leak this whole function exists to close, one layer up.
406
+ from modules import sheet as sheet_mod
407
+ import formula_runtime as fr
408
+ _recompute_formulas(fresh, fr, sheet_mod)
409
+ fresh["refreshedFor"] = str(session.uname or "")
410
+ return fresh
411
+
412
+
413
+ def _read_for(session: Session, book):
414
+ """The workbook this session is entitled to see: stored for the owner, re-resolved otherwise.
415
+
416
+ ⚠ A STRANGER IS A NON-OWNER AND TAKES THE SAME PATH, deliberately. Nothing in this file
417
+ refuses a stranger's READ today (see the module note the measurement is booked under), so the
418
+ fail-closed answer to "what should they be shown" is: whatever THEIR OWN scope computes,
419
+ never the owner's cached numbers.
420
+ """
421
+ if _role_on_workbook(session, book) == "owner":
422
+ return book
423
+ return _reresolved_for_reader(session, book)
424
+
425
+
426
  @router.get("/sheets")
427
  def list_sheets(session: Session = Depends(require_session)):
428
+ """The workbook list, identity only. Cells never ride this door.
429
+
430
+ ⚠ C5's `shares` rides here as well as on `/sheets/index`, because the client reads both.
431
+ """
432
  from core import sheets
433
+ rows = sheets.project_shares(_store(session), sheets.list_workbooks(_store(session)))
434
+ return {"workbooks": _wire_shares(rows)}
435
 
436
 
437
  @router.post("/sheets", status_code=201)
 
459
  #
460
  # ⚠ `Depends(require_session)` ONLY, like every other door in this file, and that is correct: the
461
  # Sheet is granted to everyone, and the rail's folders name no database.
462
+ #
463
+ # β›”β›” MEASURED IN W51-T25 AND BOOKED, NOT FIXED: THAT SENTENCE MEANS EVERY SIGNED IN ACCOUNT CAN
464
+ # ALREADY READ EVERY WORKBOOK. Nothing in `core.sheets.list_workbooks` or `::read_index` filters by
465
+ # owner, and `GET /sheets/{id}` walls on the session alone, so an account holding NO share reads a
466
+ # stranger's workbook with **200**. Driven in `verify_sheet.py` section 5c with a third identity.
467
+ # β‡’ `sharedWithMe` is therefore a PARTITION of a list everyone can already see, and C5's
468
+ # viewer/editor wall guards the WRITE doors rather than closing a read that was never shut.
469
+ # Refusing a stranger's read is not in W51-T25's `done-when` and widening it here would change the
470
+ # behaviour of a door six other tickets are built on, so it is an amendment finding for the root.
471
+ # ⚠ WHAT THIS TICKET DOES GUARANTEE MEANWHILE is the half that leaks data rather than existence:
472
+ # a non-owner never receives the owner's stored numbers, because every cell-bearing read
473
+ # re-resolves under the caller's own scope first.
474
 
475
 
476
  @router.get("/sheets/index")
477
  def read_sheet_index(session: Session = Depends(require_session)):
478
+ """`{workbooks, folders, itemFolders, starred, rev, sharedWithMe}` for the rail in ONE read.
479
+
480
+ ⭐ C5 β€” EVERY ROW CARRIES `shares` AND THE DOCUMENT CARRIES `sharedWithMe`. Both are computed
481
+ from `core.shares` at read time and neither is stored on the index; the join is in
482
+ `core.sheets` and the role words are translated here, at the wire boundary.
483
+
484
+ ⭐⭐ D-639 β€” `rev` RIDES OUT AND THE PUT BELOW CHECKS IT. Half of that pair is a guard nothing
485
+ can reach: a client cannot send a revision it was never given, and a server that never checks
486
+ one is a client stamping a number nobody reads.
487
+ """
488
  from core import sheets
489
+ return {"index": _wire_index(sheets.read_index(_store(session), viewer=session.uname))}
490
 
491
 
492
  @router.put("/sheets/index")
 
497
  ⭐ `repairs` RIDES BACK OUT. `core.sheets.save_folders` records every change it made to the
498
  payload, and the rail says so in a sentence rather than letting a workbook reappear at the
499
  top level with no explanation (R16). Dropping this key is what makes a silent repair.
500
+
501
+ ⭐⭐ D-639 β€” `rev` IN THE BODY MAKES THIS WRITE CONDITIONAL, and it is the half of the guard
502
+ that lives on the server. Send the `rev` the GET handed you and a concurrent reorganisation
503
+ answers 409 `index_revision_stale` carrying `rev_current`, which `_refuse`'s existing
504
+ `_stale` branch shapes for free. ⚠ Omitting it is still legal and still means last writer
505
+ wins, exactly as it does on the workbook PUT: a client that has never read the rail cannot
506
+ send one.
507
  """
508
  from core import sheets
509
  raw = dict(body or {})
510
  try:
511
  out = sheets.save_folders(_store(session), raw.get("folders"),
512
+ raw.get("itemFolders"), starred=raw.get("starred"),
513
+ expect_rev=raw.get("rev"))
514
  except sheets.SheetRefusal as exc:
515
  raise _refuse(exc)
516
+ return {"index": _wire_index(out)}
517
+
518
+
519
+ # ── C4: the .xlsx IMPORT, which is a JOB and not a request (wave 51, W51-T24) ────────────────
520
+ #
521
+ # ⭐⭐ THE JOB EXISTS BECAUSE THE WORK OUTLIVES THE REQUEST. Two openpyxl passes over the owner's
522
+ # treasury model MEASURED 31 s of parsing and 25 s of recalculation on this box, and the Space is
523
+ # slower; a synchronous door would be a browser timeout, a proxy 504, or a person who closed the
524
+ # tab and lost an import that had already finished. So the upload starts a thread, answers with a
525
+ # job id, and `GET /sheets/import/{job}` reports where it got to. β›” NOTHING IN THE JOB READS THE
526
+ # CLIENT: it does not stop when the polling stops, which is the whole point.
527
+ #
528
+ # β›” THE TEMP FILE IS DELETED IN A `finally`, INCLUDING ON REFUSAL. An import that refuses is the
529
+ # case that leaves a 25 MB file behind, because it is the path nobody walks while testing.
530
+ #
531
+ # ⚠ DECLARED ABOVE `/sheets/{workbook_id}`, and it is free insurance rather than a fix: FastAPI
532
+ # matches in declaration order, and `/sheets/index` further up is a literal that a `{param}` route
533
+ # on the SAME depth would eat. These two cannot collide (POST at depth 3 against a GET-only param
534
+ # route, and GET at depth 4 against a depth-3 param route), but the file's discipline is that a
535
+ # literal is declared first and this one is not going to be the exception nobody re-checks.
536
+
537
+ #: Every import this process has run, newest last. ⚠ IT IS PROCESS MEMORY, NOT THE STORE, and
538
+ #: that is correct for a progress reading: it is worthless after a restart and a restart has
539
+ #: already killed the thread it describes. The WORKBOOK is in the store; only the progress is here.
540
+ _IMPORT_JOBS = {}
541
+ _IMPORT_LOCK = threading.Lock()
542
+
543
+ #: How many finished jobs are kept before the oldest is dropped. A job holds its report, which
544
+ #: holds up to `MAX_MISMATCHED` addresses, so an unbounded registry is an unbounded leak in a
545
+ #: process that never restarts.
546
+ _MAX_IMPORT_JOBS = 24
547
+
548
+
549
+ def _job_set(job_id, **fields):
550
+ """Update one job under the registry lock. Called from the worker thread."""
551
+ with _IMPORT_LOCK:
552
+ job = _IMPORT_JOBS.get(job_id)
553
+ if job is not None:
554
+ job.update(fields)
555
+
556
+
557
+ def _job_view(job):
558
+ """C4's wire shape for one job. Only the keys C4 names, and only when they hold something."""
559
+ out = {"state": job.get("state") or "reading",
560
+ "progress": round(float(job.get("progress") or 0.0), 3)}
561
+ for key in ("workbook_id", "report", "sentence"):
562
+ if job.get(key) is not None:
563
+ out[key] = job[key]
564
+ return out
565
+
566
+
567
+ def _reap_jobs():
568
+ """Drop the oldest FINISHED jobs past the cap. A running job is never reaped."""
569
+ with _IMPORT_LOCK:
570
+ done = [k for k, v in _IMPORT_JOBS.items() if v.get("state") in ("done", "refused")]
571
+ while len(_IMPORT_JOBS) > _MAX_IMPORT_JOBS and done:
572
+ _IMPORT_JOBS.pop(done.pop(0), None)
573
+
574
+
575
+ def _import_refused(job_id, code, message):
576
+ _job_set(job_id, state="refused", progress=1.0, code=code, sentence=message)
577
+
578
+
579
+ def _run_import(job_id, path, filename, runtime, uname):
580
+ """The whole import, on its own thread: read, map, recalculate, compare, save.
581
+
582
+ β›”β›” THE REPORT SURVIVES A REFUSAL, and that is the difference between a refusal a person can
583
+ act on and one they cannot. If the document does not fit `MAX_WORKBOOK_BYTES` the save raises,
584
+ and answering with a bare sentence would leave the reader knowing only that something was too
585
+ big; the report already knows how many cells and formulas were in their file and what did not
586
+ survive, so it is written into the job BEFORE the save is attempted.
587
+ """
588
+ from core import sheet_import, sheets
589
+ from modules import sheet as sheet_mod
590
+ import formula_runtime as fr
591
+
592
+ made = None
593
+ try:
594
+ out = sheet_import.import_workbook(
595
+ path, source=filename,
596
+ progress=lambda state, fraction: _job_set(job_id, state=state, progress=fraction))
597
+ book, report = out["workbook"], out["report"]
598
+
599
+ #: β›” PULLED OFF BEFORE THE RECALC OVERWRITES `value`. `_recompute_formulas` replaces every
600
+ #: formula cell's value with OUR answer, so a differential run after it with the cached
601
+ #: readings still on the cells would be comparing our answer against itself.
602
+ cached = sheet_import.take_imported_values(book)
603
+ _job_set(job_id, state="recalc", progress=0.96, report=report)
604
+ _recompute_formulas(book, fr, sheet_mod)
605
+ diff = sheet_import.differential(book, cached)
606
+ report["matched"] = diff["matched"]
607
+ report["mismatched"] = diff["mismatched"]
608
+ report["compared"] = diff["compared"]
609
+ _job_set(job_id, report=report)
610
+
611
+ stamp = _now_iso()
612
+ made = sheets.create_workbook(runtime, name=book.get("name") or "", created_by=uname)
613
+ saved = sheets.put_workbook(runtime, made["id"],
614
+ {"name": book.get("name"), "sheets": book.get("sheets"),
615
+ "refreshed_at": stamp, "rev": made["rev"]})
616
+ _job_set(job_id, state="done", progress=1.0, workbook_id=saved["id"],
617
+ sentence=_import_sentence(report))
618
+ except sheet_import.ImportRefusal as exc:
619
+ _import_refused(job_id, exc.code, exc.message)
620
+ except sheets.SheetRefusal as exc:
621
+ # β›” THE HALF MADE WORKBOOK GOES WITH THE REFUSAL. `create_workbook` has already written an
622
+ # empty document and an index row; leaving them would file an untitled empty workbook into
623
+ # the rail for every import that was too large to store.
624
+ if made is not None:
625
+ try:
626
+ sheets.delete_workbook(runtime, made["id"])
627
+ except Exception: # noqa: BLE001
628
+ pass
629
+ _import_refused(job_id, exc.code, exc.message)
630
+ except Exception as exc: # noqa: BLE001
631
+ _import_refused(job_id, "import_failed",
632
+ "That workbook could not be imported: " + str(exc)[:200])
633
+ finally:
634
+ try:
635
+ os.remove(path)
636
+ except OSError:
637
+ pass
638
+ _reap_jobs()
639
+
640
+
641
+ def _import_sentence(report):
642
+ """What a finished import SAYS, in digits (R16). No em dash and no en dash."""
643
+ compared = int(report.get("compared") or 0)
644
+ matched = int(report.get("matched") or 0)
645
+ line = ("Imported " + str(int(report.get("cells") or 0)) + " cells and "
646
+ + str(int(report.get("formulas") or 0)) + " formulas.")
647
+ if compared:
648
+ line += (" " + str(matched) + " of " + str(compared)
649
+ + " recalculated cells match the answers the file had stored.")
650
+ if report.get("unsupported"):
651
+ line += (" " + str(len(report["unsupported"]))
652
+ + " kinds of thing in that file could not be carried over.")
653
+ return line
654
+
655
+
656
+ @router.post("/sheets/import", status_code=202)
657
+ async def start_sheet_import(file: UploadFile = File(...),
658
+ session: Session = Depends(require_session)):
659
+ """Take an .xlsx upload and START a job (contract C4). Answers `{job, state, progress}`.
660
+
661
+ ⚠ THE TWO REFUSALS HERE ARE SYNCHRONOUS ON PURPOSE. A wrong file type and a file over the cap
662
+ are both knowable before any work starts, so answering them as a job the caller has to poll
663
+ would make the client wait to be told something the server already knew.
664
+ """
665
+ from core import sheet_import
666
+
667
+ name = str(file.filename or "").strip()
668
+ if not name.lower().endswith(".xlsx"):
669
+ raise err(400, "import_not_xlsx",
670
+ "Only an .xlsx workbook can be imported. Save your file as .xlsx and try again.")
671
+ data = await file.read()
672
+ if len(data) > sheet_import.MAX_IMPORT_BYTES:
673
+ raise HTTPException(status_code=413, detail={"error": {
674
+ "code": "import_too_large",
675
+ "message": ("That file is " + _mb(len(data)) + " and an import takes at most "
676
+ + _mb(sheet_import.MAX_IMPORT_BYTES)
677
+ + ", so it cannot be read. Split it into two workbooks and try again.")}})
678
+ if not data:
679
+ raise err(400, "import_empty", "That file holds nothing to import.")
680
+
681
+ handle, path = tempfile.mkstemp(prefix="sheet-import-", suffix=".xlsx")
682
+ with os.fdopen(handle, "wb") as fh:
683
+ fh.write(data)
684
+
685
+ job_id = uuid.uuid4().hex[:16]
686
+ with _IMPORT_LOCK:
687
+ _IMPORT_JOBS[job_id] = {"state": "reading", "progress": 0.0, "owner": session.uname,
688
+ "started": _now_iso()}
689
+ thread = threading.Thread(target=_run_import, name="sheet-import-" + job_id,
690
+ args=(job_id, path, name, _store(session), session.uname),
691
+ daemon=True)
692
+ thread.start()
693
+ return {"job": job_id, "state": "reading", "progress": 0.0}
694
+
695
+
696
+ @router.get("/sheets/import/{job}")
697
+ def read_sheet_import(job: str, session: Session = Depends(require_session)):
698
+ """Where one import got to (contract C4).
699
+
700
+ ⚠ A JOB THAT IS NOT THIS CALLER'S ANSWERS 404, not 403. A 403 would confirm that somebody
701
+ else's import exists, which is a fact this door has no business handing out; a job id is a
702
+ random hex string and "not here" is the honest answer for one the caller does not own.
703
+ """
704
+ with _IMPORT_LOCK:
705
+ found = _IMPORT_JOBS.get(str(job or "").strip())
706
+ snapshot = dict(found) if found else None
707
+ if not snapshot or snapshot.get("owner") != session.uname:
708
+ raise err(404, "import_job_missing", "That import is no longer being tracked.")
709
+ return _job_view(snapshot)
710
+
711
+
712
+ def _mb(byte_count):
713
+ """A byte count as MB with one decimal, the way `core.sheets._mb` says it (R16)."""
714
+ return "%.1f MB" % (float(byte_count) / (1024.0 * 1024.0))
715
 
716
 
717
  @router.get("/sheets/{workbook_id}")
718
+ def read_sheet(workbook_id: str, tabs: str = "",
719
+ session: Session = Depends(require_session)):
720
+ """The whole workbook, or `?tabs=meta` for the workbook WITHOUT any cells (contract C3).
721
+
722
+ ⭐ `?tabs=meta` IS HOW A CLIENT OPENS ONE TAB AT A TIME (R4). A1 raised the byte cap to 16 MiB,
723
+ so the plain read below can now legitimately hand back 16 MB on a workbook with ten tabs the
724
+ reader is not looking at. The meta read carries every tab's identity, geometry and strata and
725
+ none of its cells, and `GET /sheets/{id}/tabs/{tab}` fetches the one tab that is open.
726
+
727
+ ⚠ ANY OTHER VALUE OF `tabs` READS AS THE FULL WORKBOOK, on purpose. A client that sends an
728
+ unknown value has asked for something this door does not know how to trim, and answering with
729
+ everything is the honest superset; refusing would 400 a READ over a query string.
730
+
731
+ ⭐⭐ C5 β€” A NON-OWNER'S READ IS RE-RESOLVED UNDER THEIR OWN SCOPE, and `?tabs=meta` is the one
732
+ shape that skips it because it carries no cells at all. A shared workbook's stored numbers are
733
+ the OWNER's: they were computed under the owner's row scope, so handing them to a reader whom
734
+ an administrator has restricted on that database shows them exactly the rows they were walled
735
+ off from, with a 200 and nothing red.
736
+ """
737
+ from core import sheets
738
+ try:
739
+ book = sheets.get_workbook(_store(session), workbook_id)
740
+ except sheets.SheetRefusal as exc:
741
+ raise _refuse(exc)
742
+ if str(tabs or "").strip().lower() == "meta":
743
+ return {"workbook": sheets.workbook_meta(book)}
744
+ return {"workbook": _read_for(session, book)}
745
+
746
+
747
+ # β›” THE ORDER WAS CHECKED, BECAUSE FASTAPI MATCHES IN DECLARATION ORDER. `/sheets/index`'s hazard
748
+ # (a literal eaten by a `{param}` route on the same prefix) cannot reach these two: both carry a
749
+ # LITERAL `tabs` segment at depth four, and no route in this file declares a parameter at that
750
+ # depth. A mount census cannot prove that either way, so `verify_sheet.py` section 2 DRIVES both
751
+ # doors and reads the answer, which is the only check that can tell a declared route from a
752
+ # reachable one.
753
+
754
+
755
+ @router.get("/sheets/{workbook_id}/tabs/{tab}")
756
+ def read_sheet_tab(workbook_id: str, tab: str,
757
+ session: Session = Depends(require_session)):
758
+ """ONE tab and its cells (contract C3). `{tab}` is the tab's `id`, or its name.
759
+
760
+ ⚠ THE ANSWER CARRIES `rev`, and it has to: the PATCH door below is rev guarded, so a client
761
+ that fetched a tab without the revision it belongs to would have to guess one or re-read the
762
+ whole workbook to save a single cell.
763
+
764
+ β›”β›” C5's RE-RESOLVE IS WIRED HERE TOO, AND THIS IS THE DOOR IT WOULD HAVE BEEN MISSED ON.
765
+ There are THREE read shapes, not one: the full workbook, `?tabs=meta` (no cells, nothing to
766
+ re-resolve) and this one. Wiring the reader's scope into the full read alone would still hand
767
+ a reader the owner's cached numbers through `GET /sheets/{id}/tabs/{tab}` β€” the door the
768
+ client actually uses once a workbook is open, so the leak would be the NORMAL path rather
769
+ than the rare one. ⚠ `refreshedFor` is stamped on the ENVELOPE here rather than on the tab,
770
+ because the tab is `found` verbatim and a key added inside it would be a cell-shaped thing
771
+ that is not a cell.
772
+ """
773
  from core import sheets
774
  try:
775
+ book = sheets.get_workbook(_store(session), workbook_id)
776
+ served = _read_for(session, book)
777
+ found = sheets.find_tab(served, tab)
778
  except sheets.SheetRefusal as exc:
779
  raise _refuse(exc)
780
+ out = {"id": book.get("id"), "rev": book.get("rev"), "tab": found}
781
+ if served.get("refreshedFor"):
782
+ out["refreshedFor"] = served["refreshedFor"]
783
+ return out
784
+
785
+
786
+ @router.patch("/sheets/{workbook_id}/tabs/{tab}/cells")
787
+ def patch_sheet_cells(workbook_id: str, tab: str, body: dict = Body(default=None),
788
+ session: Session = Depends(require_session)):
789
+ """Merge a RANGE of cells into one tab: body `{cells: {A1: Cell | null}, rev}` (contract C3).
790
+
791
+ ⭐ `{"A1": null}` DELETES A1 and leaves its neighbours alone. After C2 an empty cell can carry
792
+ a style (`kind: "empty"`), so a client needs a way to say "nothing at all lives here" that is
793
+ distinguishable from "this is painted yellow and holds nothing".
794
+
795
+ ⭐ ONE BAD CELL DOES NOT THROW THE COMMIT AWAY. The answer is `{rev, tab, cells, refused}`,
796
+ where `refused` is a per address list of `{addr, code, sentence}` and every other cell in the
797
+ same patch has landed. A CAP breach is the opposite: it is a whole request 413, because the
798
+ document as a whole cannot be stored and there is no partial version of that.
799
+
800
+ ⚠ `rev` IN THE BODY MAKES THE WRITE CONDITIONAL, exactly as it does on the PUT door. Omit it
801
+ and the last writer wins; send the `rev` the tab read and a concurrent change answers 409
802
+ `sheet_revision_stale` carrying `rev_current`, which is the revision to refetch.
803
+
804
+ β›”β›” C5's READ-ONLY CHECK RUNS BEFORE THAT COMPARISON AND THE ORDER IS THE CONTRACT. A viewer
805
+ is refused 403 `workbook_read_only`; a viewer holding a stale rev is ALSO refused
806
+ `workbook_read_only`, not 409, because 409 names a problem they could fix by refetching and
807
+ this one they cannot fix at all. An editor's write falls straight through to the rev guard,
808
+ which is exactly what C5 asks for.
809
+ """
810
+ from core import sheets
811
+ raw = dict(body or {})
812
+ try:
813
+ _require_editor(session, sheets.get_workbook(_store(session), workbook_id))
814
+ except sheets.SheetRefusal as exc:
815
+ raise _refuse(exc)
816
+ #: ⚠ `rev` ABSENT and `rev: null` are the same request and both opt out. A client that has
817
+ #: never read the document cannot send one, and refusing would make the first save of an
818
+ #: imported workbook impossible.
819
+ expect = raw.get("rev")
820
+ try:
821
+ out = sheets.patch_cells(_store(session), workbook_id, tab, raw.get("cells"),
822
+ expect_rev=expect)
823
+ except sheets.SheetRefusal as exc:
824
+ raise _refuse(exc)
825
+ return out
826
 
827
 
828
  @router.put("/sheets/{workbook_id}")
 
833
  ⚠ `rev` in the body makes the write CONDITIONAL. Omit it and the last writer wins; send the
834
  `rev` you read and a concurrent change answers `workbook_revision_stale` instead of being
835
  silently overwritten.
836
+
837
+ β›” C5: THE READ-ONLY CHECK RUNS FIRST, for the reason spelled out on the PATCH door.
838
  """
839
  from core import sheets
840
  raw = dict(body or {})
841
+ try:
842
+ _require_editor(session, sheets.get_workbook(_store(session), workbook_id))
843
+ except sheets.SheetRefusal as exc:
844
+ raise _refuse(exc)
845
  try:
846
  # `rev` inside the body IS the expectation; `core.sheets.put_workbook` reads it. This door
847
  # does not translate it into a second argument, because two ways to say the same thing is
 
854
 
855
  @router.delete("/sheets/{workbook_id}")
856
  def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
857
+ """Delete a workbook. THE OWNER's door, and an editor is refused by name (C5).
858
+
859
+ β›” AN `edit` GRANT IS PERMISSION TO CHANGE THE CONTENT, NOT TO DESTROY THE OBJECT, and the
860
+ fail-closed reading is the one that ships: an editor who deletes the owner's workbook has
861
+ taken it from everybody it was shared with, and nothing in this system can put it back. The
862
+ refusal is `workbook_owner_only` rather than `workbook_read_only` because the sentences send
863
+ the reader to two different places, and telling an editor their workbook is read only would be
864
+ flatly false.
865
+ """
866
  from core import sheets
867
  try:
868
+ _require_owner(session, sheets.get_workbook(_store(session), workbook_id))
869
  removed = sheets.delete_workbook(_store(session), workbook_id)
870
  except sheets.SheetRefusal as exc:
871
  raise _refuse(exc)
872
  return {"deleted": bool(removed)}
873
 
874
 
875
+ # ── C5's two share doors, and they are the OWNER's ───────────────────────────────────────────
876
+ #
877
+ # ⚠ DECLARED BELOW `/sheets/{workbook_id}` AND THAT IS SAFE: both carry a LITERAL `shares`
878
+ # segment at depth four or five, and this file declares no parameter at either depth on that
879
+ # prefix, so no `{param}` route can eat them. The two doors that DID need declaration order
880
+ # (`/sheets/index`, `/sheets/import`) are literals at depth THREE and are still first.
881
+
882
+
883
+ @router.post("/sheets/{workbook_id}/shares")
884
+ def share_sheet(workbook_id: str, body: dict = Body(default=None),
885
+ session: Session = Depends(require_session)):
886
+ """Grant one person `viewer` or `editor` on this workbook (C5, R16). Owner only.
887
+
888
+ ⭐ THE GRANT GOES INTO `core.shares`, THE ONE REGISTRY, and the answer hands back the WHOLE
889
+ list rather than the row just written: the registry replaces a grant set wholesale, so the
890
+ honest answer to "what did that do" is what the list is now.
891
+
892
+ ⚠ `expect` IS THE COMPARE-AND-SET `core.shares.set_grants` already offers, and it is passed
893
+ the list this request decided against. Two people with the sharing panel open would otherwise
894
+ silently overwrite each other, which that module measured in wave 40 and answers `409`.
895
+ """
896
+ from core import sheets, shares
897
+ raw = dict(body or {})
898
+ try:
899
+ book = sheets.get_workbook(_store(session), workbook_id)
900
+ _require_owner(session, book)
901
+ except sheets.SheetRefusal as exc:
902
+ raise _refuse(exc)
903
+
904
+ who = str(raw.get("who") or "").strip().lower()
905
+ role = store_role(raw.get("role"))
906
+ if not who:
907
+ raise err(400, "share_who_required", "Name the person to share this workbook with.")
908
+ if who == _workbook_owner(book):
909
+ raise err(400, "share_owner_redundant",
910
+ "That person already owns this workbook, so there is nothing to share.")
911
+ if not role:
912
+ raise err(400, "share_role_unknown",
913
+ "A workbook is shared as viewer or as editor, and %r is neither."
914
+ % (str(raw.get("role") or ""),))
915
+
916
+ held = shares.grants("workbook", book["id"], st=_store(session))
917
+ prior = list(held.get("entries") or [])
918
+ entries = [dict(e) for e in prior if e.get("user") != who] + [{"user": who, "role": role}]
919
+ try:
920
+ rec = shares.set_grants("workbook", book["id"], entries,
921
+ owner=(None if held.get("owner") else _workbook_owner(book)),
922
+ granter=session.uname, st=_store(session), expect=prior)
923
+ except shares.GrantsChanged as exc:
924
+ # ⚠ `grants_changed`, THE SAME CODE `routes_shares.py` ALREADY ANSWERS, and a plain 409
925
+ # rather than the `_stale` shape: there is no revision to hand back here, and a
926
+ # `rev_current: 0` would be a number the client could only misuse.
927
+ raise err(409, "grants_changed", str(exc))
928
+ return {"shares": [{"who": e["user"], "role": wire_role(e["role"])}
929
+ for e in (rec.get("entries") or [])]}
930
+
931
+
932
+ @router.delete("/sheets/{workbook_id}/shares/{who}")
933
+ def unshare_sheet(workbook_id: str, who: str, session: Session = Depends(require_session)):
934
+ """Revoke one person's access to this workbook (C5). Owner only.
935
+
936
+ ⚠ REVOKING SOMEBODY WHO WAS NEVER THERE IS A 200 WITH THE LIST UNCHANGED. The caller's
937
+ intention ("this person must not have access") is satisfied either way, and a 404 here would
938
+ make a double click on Remove look like a failure.
939
+ """
940
+ from core import sheets, shares
941
+ try:
942
+ book = sheets.get_workbook(_store(session), workbook_id)
943
+ _require_owner(session, book)
944
+ except sheets.SheetRefusal as exc:
945
+ raise _refuse(exc)
946
+
947
+ target = str(who or "").strip().lower()
948
+ held = shares.grants("workbook", book["id"], st=_store(session))
949
+ prior = list(held.get("entries") or [])
950
+ entries = [dict(e) for e in prior if e.get("user") != target]
951
+ try:
952
+ rec = shares.set_grants("workbook", book["id"], entries,
953
+ owner=(None if held.get("owner") else _workbook_owner(book)),
954
+ granter=session.uname, st=_store(session), expect=prior)
955
+ except shares.GrantsChanged as exc:
956
+ # ⚠ `grants_changed`, THE SAME CODE `routes_shares.py` ALREADY ANSWERS, and a plain 409
957
+ # rather than the `_stale` shape: there is no revision to hand back here, and a
958
+ # `rev_current: 0` would be a number the client could only misuse.
959
+ raise err(409, "grants_changed", str(exc))
960
+ return {"shares": [{"who": e["user"], "role": wire_role(e["role"])}
961
+ for e in (rec.get("entries") or [])]}
962
+
963
+
964
  # ── the doors that RESOLVE, and are therefore later tickets ──────────────────────────────────
965
  #
966
  # ⭐ Each is declared here so the surface exists and `main.py` needs no second edit, and each
 
978
 
979
  ⚠ Each distinct `view_id` is resolved ONCE. `table_store.find_view` runs a legacy migration on
980
  every call, so resolving per cell would make a forty-cell refresh do forty migrations.
981
+
982
+ β›”β›” C5 β€” THIS IS A WRITE DOOR, BECAUSE IT ENDS IN `put_workbook`, AND A VIEWER IS REFUSED
983
+ HERE FOR A REASON THAT IS NOT ABOUT PERMISSION TO SEE. A viewer whose refresh were allowed
984
+ would compute every bound cell under THEIR scope and then SAVE those numbers into the owner's
985
+ document, so a narrowly walled reader pressing Refresh would silently shrink the owner's
986
+ workbook. The reader's own re-resolve happens on the READ path, in memory, and never lands.
987
+ ⚠ An EDITOR still writes their own numbers here, which is what an edit grant means and is
988
+ booked as a residual rather than widened away.
989
  """
990
  from core import sheets
991
  from modules import sheet as sheet_mod
 
993
 
994
  try:
995
  book = sheets.get_workbook(_store(session), workbook_id)
996
+ _require_editor(session, book)
997
  except sheets.SheetRefusal as exc:
998
  raise _refuse(exc)
999
 
 
1040
  else:
1041
  cell.pop("limits", None)
1042
 
1043
+ # ⭐⭐ R4 / A1: THE RECALC IS TIMED AND THE TIME IS SHOWN. The prototype measured 2.9 s as the
1044
+ # FLOOR for the owner's 11,300 formulas (2.9 to 6.2 s observed), so a refresh is a wait a
1045
+ # person notices, and a wait nobody explains reads as a hang. `recalc_ms` is what the client
1046
+ # renders as "Recalculated in N.N s".
1047
+ #
1048
+ # ⚠ IT TIMES THE RECALC, NOT THE ROUTE. The bound-cell loop above is database work whose
1049
+ # duration says nothing about the formula engine, and the save below is store work; folding
1050
+ # either into this number would make the figure on the screen unable to answer the question it
1051
+ # exists for, which is whether the ENGINE is inside A1's 5 s target.
1052
+ from time import perf_counter
1053
+ started = perf_counter()
1054
  _recompute_formulas(book, fr, sheet_mod)
1055
+ recalc_ms = round((perf_counter() - started) * 1000.0, 1)
1056
  try:
1057
  saved = sheets.put_workbook(_store(session), workbook_id,
1058
  {"name": book.get("name"), "sheets": book.get("sheets"),
1059
  "refreshed_at": stamp, "rev": book.get("rev")})
1060
  except sheets.SheetRefusal as exc:
1061
  raise _refuse(exc)
1062
+ return {"workbook": saved, "recalc_ms": recalc_ms}
1063
 
1064
 
1065
  def _now_iso():
 
1067
  return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
1068
 
1069
 
1070
+ #: β›” THE NAME A TAB GETS WHEN IT CANNOT KEEP ITS OWN, and it is built to be UNTYPEABLE on two
1071
+ #: independent counts: it carries a NUL, and it is longer than the 64 characters `_A1_RE` allows a
1072
+ #: sheet name on either spelling. See `_tab_scope_names` for when one is handed out.
1073
+ _UNADDRESSABLE_TAB = "\x00 a tab that cannot be named inside a formula, which is the point \x00"
1074
+
1075
+
1076
+ def _tab_scope_names(tabs):
1077
+ """The name each tab is ADDRESSED BY during one workbook pass, one per tab, all distinct.
1078
+
1079
+ β›”β›” TWO TABS SHARING A NAME WOULD MERGE THEIR CELLS INTO ONE KEY SPACE, and that hazard is
1080
+ created BY the workbook pass: keying per tab, as this function's caller used to, made a
1081
+ collision impossible. `core.sheets._clean_sheet` names a blank tab `Sheet<n>` but never checks
1082
+ that two tabs differ, so a workbook holding two tabs called `Data` is an ordinary saved
1083
+ document. The second one keeps its cells, keeps its own local references and simply cannot be
1084
+ reached by name from another tab, which is the honest reading of an ambiguous name: `Data!B12`
1085
+ means the first `Data`, and nothing silently overwrites anything.
1086
+ """
1087
+ names, seen = [], set()
1088
+ for index, tab in enumerate(tabs):
1089
+ name = str(tab.get("name") or "")
1090
+ folded = name.upper()
1091
+ if not folded or folded in seen:
1092
+ name = _UNADDRESSABLE_TAB + str(index)
1093
+ folded = name.upper()
1094
+ seen.add(folded)
1095
+ names.append(name)
1096
+ return names
1097
+
1098
+
1099
  def _recompute_formulas(book, fr, sheet_mod):
1100
+ """Re-evaluate every formula cell across the WORKBOOK, in one memoized dependency pass.
1101
+
1102
+ ⭐⭐ ONE PASS OVER EVERY TAB, NOT ONE PASS PER TAB (W51-T23). Per tab, `DATA!B12` was never in
1103
+ the inputs, so all 785 cross-sheet cells in the wave-51 prototype resolved BLANK with no error.
1104
+ Here every cell in the book is keyed `TAB!ADDR` in a single spec, and each formula carries the
1105
+ tab it lives on so its own unqualified references default to that tab rather than to the first
1106
+ one. Both halves are needed: keys alone break local references, and defaults alone leave
1107
+ cross-tab keys unreachable.
1108
 
1109
  β›” A REFUSED INPUT PROPAGATES; IT DOES NOT BECOME ZERO (C2, and W49-T09 hardens it further).
1110
  A cell whose value is None because the database refused is handed to the engine as absent, so
1111
  arithmetic over it stays None rather than silently counting it as nothing.
1112
  """
1113
+ tabs = [t for t in (book.get("sheets") or ()) if isinstance(t, dict)]
1114
+ names = _tab_scope_names(tabs)
1115
+ spec = {}
1116
+ for tab, name in zip(tabs, names):
1117
+ for addr, cell in (tab.get("cells") or {}).items():
1118
  if not isinstance(cell, dict):
1119
  continue
1120
+ key = fr.a1_key(addr, name)
1121
  if cell.get("kind") == "formula" and cell.get("formula"):
1122
+ spec[key] = {"formula": cell["formula"], "sheet": name}
1123
  elif cell.get("state") == "refused":
1124
  # β›”β›” CARRIED AS A REFUSAL, NOT DROPPED (W49-T09, C2). Leaving a refused cell OUT
1125
  # of the inputs is the defect, not the safe option: MEASURED, `=SUM(B4:B8)` with B4
1126
  # merely absent answers **3.0 with no error**, while the same range with B4 REFUSED
1127
  # answers None and names the cause. Dropping it turns a refusal into a smaller
1128
  # total that looks entirely reasonable.
1129
+ spec[key] = {"refused": (cell.get("refusal") or {}).get("code") or "refused"}
1130
  else:
1131
+ spec[key] = {"value": cell.get("value")}
1132
+ if not any("formula" in v for v in spec.values()):
1133
+ return
1134
+ out = fr.evaluate_sheet(spec, sheets=names)
1135
+ errors = out.get("errors") or {}
1136
+ computed = out.get("values") or {}
1137
+ for tab, name in zip(tabs, names):
1138
+ for addr, cell in (tab.get("cells") or {}).items():
1139
  if not isinstance(cell, dict) or cell.get("kind") != "formula":
1140
  continue
1141
+ code = errors.get(fr.a1_key(addr, name))
1142
  if code:
1143
  cell["state"] = "refused"
1144
  cell["value"] = None
1145
  cell["refusal"] = {"code": code, "message": _formula_message(code)}
1146
  else:
1147
  cell["state"] = "fresh"
1148
+ cell["value"] = computed.get(fr.a1_key(addr, name))
1149
  cell["display"] = "" if cell["value"] is None else str(cell["value"])
1150
  cell.pop("refusal", None)
1151
 
 
1166
  "circular_reference": "This formula refers back to itself, so it has no value.",
1167
  "bad_formula": "This formula could not be read.",
1168
  "unknown_ref": "This formula points at a cell that is not filled in.",
1169
+ # ⭐ W51-T23. A MISSING TAB IS NOT A MISSING CELL, and the two sentences send the reader to
1170
+ # two different places: `unknown_ref` says fill the cell in, this one says the tab it names
1171
+ # is not in this workbook, which is usually a renamed or deleted tab rather than a typo.
1172
+ "unknown_sheet": "This formula points at a tab that is not in this workbook.",
1173
  "div_zero": "This formula divides by zero.",
1174
  # ── W50-T16's two diagnostic codes (lane B), worded by lane B, added by W50-T20 ────────
1175
  #
 
1244
  wall_nodes=wall_nodes, wall_conj=wall_conj, today=today)
1245
  except sheet_mod.SheetRefusal as exc:
1246
  raise err(400, exc.code, exc.message)
1247
+ except ValueError:
1248
+ # β›”β›” A CONDITION THIS COMPILER REFUSES IS A NAMED 409, NOT A 500 (W51-T26). `filter_sql`
1249
+ # RAISES rather than dropping a leaf it cannot push down - deliberately, because a dropped
1250
+ # condition widens the answer while the number beside it still looks authoritative. It was
1251
+ # arriving here as an unhandled exception, so the honest refusal became a blank error.
1252
+ # ⚠ THE LIVE CASE IS A COHORT LEAF, and W51-T26 is what makes one reachable: a purged
1253
+ # LOCKED view adopts its member set as `{colId: "__cohort__"}`, and this resolver passes
1254
+ # neither `cohort_sets` nor `id_sql`, so `_compile_cohort` refuses. Reported as a finding
1255
+ # with its own exit rather than papered over; the same branch also names a rank op and a
1256
+ # relative date with no anchor, both of which reached this door as a 500 before.
1257
+ # ⚠ THE EXCEPTION TEXT IS NOT ECHOED. `filter_sql`'s own message carries an em dash, and
1258
+ # standing rule 2 governs any string returned to the client, so the sentence is written
1259
+ # here rather than forwarded.
1260
+ raise err(409, "scope_not_applicable",
1261
+ "this cell's scope uses a condition that cannot be applied to this database's "
1262
+ "live connection, so the number is not being shown rather than shown wider "
1263
+ "than you asked for. Edit the cell's scope and try again.")
1264
 
1265
  row = cur.execute(sql, params).fetchone()
1266
  value = row[0] if row else None
api/routes_tables.py CHANGED
@@ -3394,6 +3394,101 @@ def restore_table_view(table_key: str, view_id: str, request: Request,
3394
  return {"restored": vid, "owner": owner, "name": landed.get("name")}
3395
 
3396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3397
  # ── CONTRACT C1 (W36-T20): THE MIRROR READER ──────────────────────────────────────────────────
3398
  # ⭐⭐ R6. `core.perm_scope.scoped_table` is the ONE door to any database's rows and it answers for
3399
  # a MATERIALISED `ut_*` table entirely on its own β€” deliberately, so a cold process (E's sandbox
 
3394
  return {"restored": vid, "owner": owner, "name": landed.get("name")}
3395
 
3396
 
3397
+ # ── RULING R11 (W51-T26): "DELETE FOREVER", AND THE COUNT THE CONFIRM SENTENCE NEEDS ───────────
3398
+ # ⭐⭐ R11, verbatim: *"A view-scoped cell keeps pointing at a TRASHED view for the 30 days (it
3399
+ # still resolves); its filter is copied into the cell's own scope AT PURGE (30-day purge or
3400
+ # 'Delete forever')."* The 30-day half already had a door (`trash` above, which purges on read).
3401
+ # The deliberate half had NONE - there was no way to destroy one trashed view - so R11's second
3402
+ # purge path is unbuildable without these two.
3403
+ #
3404
+ # β›”β›” THE PREVIEW IS A SEPARATE, READ-ONLY FUNCTION AND THAT IS NOT DECORATOR TASTE. One handler
3405
+ # serving GET and DELETE would have to branch on `request.method` to decide whether to run
3406
+ # `_managed_or_refuse(..., mutation=True)` - a permission decision keyed off a method string,
3407
+ # inside the one door that destroys something. Two thin functions, two walls, one shared scan.
3408
+ #
3409
+ # β›” AND THE COUNT COMES FROM THE SERVER. "N Sheet cells will keep this view's filter" is the only
3410
+ # fact the person deciding has, and a client cannot see a colleague's workbooks: a client-side or
3411
+ # hardcoded N passes every visual check and lies. It is the SAME `iter_workbooks` scan the
3412
+ # adoption itself walks (`core/sheets.py::count_view_bindings`), so the sentence and the act
3413
+ # cannot disagree.
3414
+ def _trash_owner_or_refuse(session, table_key, view_id, *, mutation):
3415
+ """`(ops, vid, owner, entry)` for a trashed view this caller may act on, or a refusal."""
3416
+ from core import table_store as ts
3417
+
3418
+ _managed_or_refuse(session, table_key, mutation=mutation)
3419
+ vid = str(view_id or "").strip()
3420
+ if not vid:
3421
+ raise err(400, "view_required", "choose a view")
3422
+ ops = _ops(session, table_key)
3423
+ # β›” AN UNREADABLE DOCUMENT IS A 503, NOT A 404 - the same rule the restore door states above.
3424
+ try:
3425
+ found = ops.find_trashed(vid, prefer_owner=session.uname)
3426
+ except Exception as exc: # noqa: BLE001
3427
+ raise err(503, "view_trash_unreadable",
3428
+ "the deleted views could not be read just now. Try again in a moment.") from exc
3429
+ if not found:
3430
+ raise err(404, "view_not_in_trash",
3431
+ "that view is not in the trash. Deleted views are kept for "
3432
+ f"{ts.TRASH_RETENTION_DAYS} days.")
3433
+ owner, entry = found
3434
+ if owner != session.uname and not session.admin:
3435
+ raise err(403, "view_not_yours", "only the owner can delete this saved view for good")
3436
+ return ops, vid, owner, entry
3437
+
3438
+
3439
+ @router.get("/tables/{table_key}/views/{view_id}/purge")
3440
+ def preview_view_purge(table_key: str, view_id: str,
3441
+ session: Session = Depends(require_session)):
3442
+ """How many Sheet cells would keep this view's filter if it were destroyed now. A pure read."""
3443
+ from core import sheets
3444
+
3445
+ _ops_unused, vid, _owner, entry = _trash_owner_or_refuse(
3446
+ session, table_key, view_id, mutation=False)
3447
+ view = entry.get("view") if isinstance(entry.get("view"), dict) else {}
3448
+ try:
3449
+ cells = sheets.count_view_bindings(session.runtime, vid)
3450
+ except Exception: # noqa: BLE001
3451
+ # ⚠ A COUNT THAT COULD NOT BE TAKEN IS `null`, NEVER 0. Zero is a claim ("nothing depends
3452
+ # on this"), and making it on an unreadable index would talk somebody into a delete.
3453
+ cells = None
3454
+ return {"viewId": vid, "name": str(view.get("name") or vid), "cells": cells}
3455
+
3456
+
3457
+ @router.delete("/tables/{table_key}/views/{view_id}/purge")
3458
+ def purge_table_view(table_key: str, view_id: str,
3459
+ rev: int = Query(default=None),
3460
+ session: Session = Depends(require_session)):
3461
+ """Destroy one trashed view now, after every cell scoped to it has taken its filter."""
3462
+ from core import view_audit
3463
+
3464
+ ops, vid, owner, _entry = _trash_owner_or_refuse(
3465
+ session, table_key, view_id, mutation=True)
3466
+ try:
3467
+ sent = None if rev is None else int(rev)
3468
+ except (TypeError, ValueError):
3469
+ raise err(400, "bad_revision", "the view revision must be a whole number")
3470
+ from core import table_store as ts
3471
+ try:
3472
+ name, adopted = ops.purge_view(owner, vid, rev=sent)
3473
+ except ts.ViewNotInTrash as missing:
3474
+ raise err(404, "view_not_in_trash", str(missing))
3475
+ except view_audit.ViewRevisionStale as stale:
3476
+ raise HTTPException(status_code=409, detail={"error": {
3477
+ "code": "view_revision_stale",
3478
+ "message": "someone else changed this view list while you had it open. "
3479
+ "Reload and try again.",
3480
+ "rev_current": stale.rev_current}})
3481
+ except view_audit.RevisionUnverifiable as unknown:
3482
+ raise err(503, "view_revision_unverifiable", str(unknown))
3483
+ except Exception as exc: # noqa: BLE001
3484
+ # β›” THE ADOPTION FAILED, SO NOTHING WAS DESTROYED. `purge_view` copies the filter before
3485
+ # it touches the bucket, so this refusal leaves the view exactly where it was.
3486
+ raise err(503, "view_purge_failed",
3487
+ "that view could not be deleted just now, so nothing was changed. "
3488
+ "Try again in a moment.") from exc
3489
+ return {"purged": vid, "owner": owner, "name": name, "adopted": adopted}
3490
+
3491
+
3492
  # ── CONTRACT C1 (W36-T20): THE MIRROR READER ──────────────────────────────────────────────────
3493
  # ⭐⭐ R6. `core.perm_scope.scoped_table` is the ONE door to any database's rows and it answers for
3494
  # a MATERIALISED `ut_*` table entirely on its own β€” deliberately, so a cold process (E's sandbox
platform/aios_grid.py CHANGED
@@ -1940,7 +1940,18 @@ FILTER_OPS = {'contains', 'doesNotContain', 'eq', 'neq', 'isEmpty', 'isNotEmpty'
1940
  # inQuartile 1..4, inDecile 1..10). Deliberately NOT in MEASURE_OPS: on a
1941
  # measure-carrying column they rank the field's own derived values.
1942
  'topN', 'bottomN', 'inTopPct', 'inBottomPct',
1943
- 'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile'}
 
 
 
 
 
 
 
 
 
 
 
1944
  #: The RESERVED pseudo-column of a cohort-membership leaf (owner item 5, 2026-07-26). It is not
1945
  #: a Field and never will be β€” a cohort is a hand-curated SET, so making it a column would mean
1946
  #: a cell per row per cohort. Mirrors customer-grid/types.ts COHORT_FIELD.
@@ -1988,6 +1999,37 @@ def parse_cohort_ids(value):
1988
  if len(out) >= MAX_COHORT_IDS:
1989
  break
1990
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1991
  # Airtable allows 3 nesting levels (root conditions -> group -> group), then grays
1992
  # the button out. MAX_FILTER_DEPTH in types.ts must stay in lock-step with this.
1993
  MAX_FILTER_DEPTH = 3
@@ -3322,6 +3364,18 @@ def clean_filter_tree(raw, valid_keys, depth=1, budget=None, cohort_ids=None,
3322
  # shape is unchanged, so every persisted view deserialises byte-identically and
3323
  # `clean_filter_tree` stays idempotent (verify_filter_engine.py asserts that by
3324
  # exact structural comparison).
 
 
 
 
 
 
 
 
 
 
 
 
3325
  rid = node.get('id')
3326
  if rid not in (None, ''):
3327
  leaf['id'] = str(rid)[:64]
 
1940
  # inQuartile 1..4, inDecile 1..10). Deliberately NOT in MEASURE_OPS: on a
1941
  # measure-carrying column they rank the field's own derived values.
1942
  'topN', 'bottomN', 'inTopPct', 'inBottomPct',
1943
+ 'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile',
1944
+ # ⭐ W51-T07 (owner instruction 25): the MULTI-VALUE operators. Their operand is
1945
+ # the leaf's `values` LIST, not `value` β€” see MULTI_VALUE_OPS below.
1946
+ 'isAnyOf', 'isNoneOf', 'hasAnyOf', 'hasAllOf', 'hasNoneOf'}
1947
+ #: ⭐ W51-T07 β€” the MULTI-VALUE subset. Mirrors types.ts MULTI_VALUE_OPS and
1948
+ #: filter_sql.MULTI_VALUE_OPS. A leaf carrying one of these persists `values` as a REAL LIST and
1949
+ #: leaves `value` blank; `clean_filter_tree` therefore emits the list beside the usual members
1950
+ #: rather than passing it through the `str(val)[:500]` coercion, which would store the literal
1951
+ #: text of a Python list and make the condition unanswerable in every engine.
1952
+ MULTI_VALUE_OPS = {'isAnyOf', 'isNoneOf', 'hasAnyOf', 'hasAllOf', 'hasNoneOf'}
1953
+ #: How many values one multi-value condition may name. Mirrors types.ts MAX_FILTER_VALUES.
1954
+ MAX_FILTER_VALUES = 100
1955
  #: The RESERVED pseudo-column of a cohort-membership leaf (owner item 5, 2026-07-26). It is not
1956
  #: a Field and never will be β€” a cohort is a hand-curated SET, so making it a column would mean
1957
  #: a cell per row per cohort. Mirrors customer-grid/types.ts COHORT_FIELD.
 
1999
  if len(out) >= MAX_COHORT_IDS:
2000
  break
2001
  return out
2002
+
2003
+
2004
+ def parse_filter_values(values):
2005
+ """The values a multi-value leaf names. Mirrors types.ts `filterValues()` and
2006
+ `harness.filter_sql.parse_filter_values`.
2007
+
2008
+ β›” A REAL LIST, and the contrast with `parse_cohort_ids` above is the decision, not an
2009
+ inconsistency: a cohort id cannot contain a comma, and a SELECT OPTION is tenant prose that
2010
+ perfectly well can ("Bouquets, mixed"). Comma-joining would split one real choice into two
2011
+ that match nothing.
2012
+
2013
+ β›” AND UNLIKE the cohort leaf, this is NOT all-or-nothing: an unknown option string is KEPT
2014
+ (the ticket's `how` line). The all-or-nothing rule exists for cohorts because a dropped
2015
+ member WIDENS a `noneOf` question against a set the caller cannot even see; here the values
2016
+ are the column's own prose, a member that no longer exists simply matches nothing, and the
2017
+ chip that still shows it is what lets somebody remove it.
2018
+
2019
+ Order preserved, blanks dropped, duplicates collapsed, members capped at 120 characters, the
2020
+ list capped at MAX_FILTER_VALUES.
2021
+ """
2022
+ out = []
2023
+ if not isinstance(values, (list, tuple)):
2024
+ return out
2025
+ for raw in values:
2026
+ val = ('' if raw is None else str(raw)).strip()[:120]
2027
+ if not val or val in out:
2028
+ continue
2029
+ out.append(val)
2030
+ if len(out) >= MAX_FILTER_VALUES:
2031
+ break
2032
+ return out
2033
  # Airtable allows 3 nesting levels (root conditions -> group -> group), then grays
2034
  # the button out. MAX_FILTER_DEPTH in types.ts must stay in lock-step with this.
2035
  MAX_FILTER_DEPTH = 3
 
3364
  # shape is unchanged, so every persisted view deserialises byte-identically and
3365
  # `clean_filter_tree` stays idempotent (verify_filter_engine.py asserts that by
3366
  # exact structural comparison).
3367
+ # ⭐ W51-T07 β€” the MULTI-VALUE operand, emitted as a REAL LIST and never through the
3368
+ # `str(val)[:500]` coercion three lines up, which would store the literal text
3369
+ # "['A', 'B']" and leave the condition unanswerable in all three engines.
3370
+ #
3371
+ # Emitted for these ops ALWAYS and for every other op NEVER, which is what keeps
3372
+ # `clean_filter_tree` idempotent (verify_filter_engine.py compares the cleaned shape
3373
+ # structurally): an ordinary column leaf is byte-identical to what it always was, and
3374
+ # a multi-value leaf whose list is EMPTY keeps an empty list rather than losing the
3375
+ # member β€” so the leaf survives as INCOMPLETE (is_rule_active answers False, the
3376
+ # builder renders it unfinished) instead of being silently dropped.
3377
+ if node['op'] in MULTI_VALUE_OPS:
3378
+ leaf['values'] = parse_filter_values(node.get('values'))
3379
  rid = node.get('id')
3380
  if rid not in (None, ''):
3381
  leaf['id'] = str(rid)[:64]
platform/core/grid_events.py CHANGED
@@ -257,6 +257,48 @@ def _ag_overview_id():
257
  EVENT_ORIGIN = {'client': 'grid-events', 'ip': None}
258
 
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  def _tops(ctx):
261
  """The table-ops object this ctx operates on β€” the customer table unless the caller chose
262
  another topic. ONE resolution point so 'which bucket does this write land in' has exactly
@@ -1358,7 +1400,24 @@ def handle_one(event, ctx):
1358
  agg = value.get('agg')
1359
  # The vocabulary is `aios_grid.SUMMARY_AGGS` plus `'none'` β€” NOT `FIELD_AGGS`, which is
1360
  # `field.agg`'s six-name write vocabulary and rejects `count_distinct`/`percentile`.
1361
- if agg != 'none' and agg not in _ag_summary.SUMMARY_AGGS:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1362
  continue
1363
  choice = {'agg': agg}
1364
  if agg == 'percentile':
@@ -1629,9 +1688,14 @@ def handle_one(event, ctx):
1629
  # the audit `owner`; `uname` is who DID it. On the foreign-owner branch above they
1630
  # differ, and a row that conflated them would name the wrong person in the one
1631
  # record whose entire job is naming the right one.
 
 
 
 
 
1632
  view = (_tops(ctx).save_view(
1633
  _save_as, view, reserved_names=_reserved_view_names,
1634
- actor=uname, origin=EVENT_ORIGIN) or view)
1635
  else:
1636
  _session_ready()
1637
  _view_names = list(_reserved_view_names)
@@ -2629,8 +2693,18 @@ def handle_one(event, ctx):
2629
  # β›” LEFT AS A CORRECTION RATHER THAN DELETED. A comment asserting a guard is dead is
2630
  # exactly what stops the next reader checking, and this one would have outlived the fix.
2631
  try:
 
 
 
 
 
 
 
 
 
2632
  _receipt = _tops(ctx).save_folders(uname, _res[0], _res[1],
2633
- actor=uname, origin=EVENT_ORIGIN)
 
2634
  except _tstore.FolderTreeError as _fte:
2635
  return _folder_refuse(ctx, kind,
2636
  str(getattr(_fte, 'reason', '') or 'folder_tree_illegal'),
 
257
  EVENT_ORIGIN = {'client': 'grid-events', 'ip': None}
258
 
259
 
260
+ def _event_rev(event):
261
+ """THE STORE REVISION THIS BROWSER DECLARED IT WAS LOOKING AT, or None if it declared none.
262
+
263
+ ⭐⭐ W51-T33 β€” THE ONE LINK THAT WAS MISSING, AND IT IS THE WHOLE TICKET.
264
+ `CustomerGrid.tsx::stampViewWrite` has put `rev` on every view write since W50-T28,
265
+ `table_store._audited_update` has enforced it on both backends since W50-T25, and
266
+ `main.py::_view_revision_stale` has answered `409 view_revision_stale {rev_current}` for any
267
+ door that raises β€” while THIS channel, the one the browser actually writes through, read the
268
+ stamp nowhere and passed no `rev=` at all. Every layer was green and the guard was inert
269
+ ([[a-rev-guard-inert-on-the-events-channel]]): two people editing one view still produced two
270
+ 200s and the first edit still vanished. Reading the value here is the only thing that was
271
+ missing, which is why this helper is four lines and not a subsystem.
272
+
273
+ β›” THE EXCEPTION IS NOT CAUGHT ANYWHERE BELOW, DELIBERATELY. `ViewRevisionStale` is a
274
+ `RuntimeError` precisely so the `except Exception` fallbacks dotted through these handlers
275
+ cannot swallow it (`view_audit.py`'s own class docstring says so), and `main.py:232`'s
276
+ handler names THIS channel as the door it exists for: *"the grid events channel above all,
277
+ which raises straight out of `table_store` with nothing between it and the client"*. Catching
278
+ it here to convert it into a toast would make a shipped, documented handler unreachable and
279
+ answer 200 for a write that was refused.
280
+
281
+ β›” ABSENT IS None, AND None IS ACCEPTED β€” the pre-C3 behaviour, unchanged. A write that
282
+ declares no revision is simply not asked the question, which is what keeps every unstamped
283
+ door (and every caller that predates the stamp) writing exactly as it does today.
284
+
285
+ ⚠ ANYTHING UNREADABLE AS AN INTEGER IS TREATED AS ABSENT RATHER THAN AS ZERO, and that is
286
+ not tidiness. `store_pg.revision()` reports a MISSING key as rev 0, so coercing junk to 0
287
+ would turn a malformed stamp into a confident claim about an empty bucket β€” the one value
288
+ most likely to disagree with the store and refuse a write nobody was racing.
289
+ ⚠ `bool` is an `int` in Python, so `True` would arrive as revision 1. Refused by name.
290
+ """
291
+ if not isinstance(event, dict):
292
+ return None
293
+ raw = event.get('rev')
294
+ if raw is None or isinstance(raw, bool):
295
+ return None
296
+ try:
297
+ return int(raw)
298
+ except (TypeError, ValueError):
299
+ return None
300
+
301
+
302
  def _tops(ctx):
303
  """The table-ops object this ctx operates on β€” the customer table unless the caller chose
304
  another topic. ONE resolution point so 'which bucket does this write land in' has exactly
 
1400
  agg = value.get('agg')
1401
  # The vocabulary is `aios_grid.SUMMARY_AGGS` plus `'none'` β€” NOT `FIELD_AGGS`, which is
1402
  # `field.agg`'s six-name write vocabulary and rejects `count_distinct`/`percentile`.
1403
+ #
1404
+ # ⭐⭐ W51-T02 / OWNER RULING R3 β€” AND PLUS `'share'`, ALLOWLISTED BY NAME RIGHT HERE
1405
+ # RATHER THAN BY WIDENING `aios_grid.SUMMARY_AGGS`.
1406
+ #
1407
+ # R3 puts "% of total" on the bottom-bar picker, so `share` is a choice a reader can
1408
+ # store and it has to survive this door β€” this whitelist REBUILDS the config from
1409
+ # named keys, so an unlisted value is not rejected loudly, it simply never gets
1410
+ # written and the choice vanishes on the next reconcile (the bug the note above
1411
+ # closed for `count_distinct`).
1412
+ # β›” IT IS NOT A WIRE AGG AND MUST NOT JOIN `aios_grid.SUMMARY_AGGS`. That tuple is
1413
+ # C1's eight-name clause, `verify_grid_ux.py::summary_bar_shape` holds it byte-for-byte
1414
+ # against the client's `iconShapes.SUMMARY_AGGS`, and it is what the `/aggregates`
1415
+ # route compiles into SQL. No engine has a "share of the view" aggregate: a share is a
1416
+ # DIVISION of two ordinary ones (a numeric column's sum, anything else's count) and
1417
+ # the client does it. So the picker's extra name is admitted where choices are STORED
1418
+ # and nowhere a query is COMPILED β€” which is also why `aios_grid.py`, another lane's
1419
+ # file, is never opened for this.
1420
+ if agg != 'none' and agg != 'share' and agg not in _ag_summary.SUMMARY_AGGS:
1421
  continue
1422
  choice = {'agg': agg}
1423
  if agg == 'percentile':
 
1688
  # the audit `owner`; `uname` is who DID it. On the foreign-owner branch above they
1689
  # differ, and a row that conflated them would name the wrong person in the one
1690
  # record whose entire job is naming the right one.
1691
+ # ⭐⭐ W51-T33 β€” `rev=` IS THE STAMP THE BROWSER ALREADY SENDS, finally read.
1692
+ # See `_event_rev`. The refusal is NOT caught: `main.py:232` turns
1693
+ # `ViewRevisionStale` into `409 view_revision_stale {rev_current}` for exactly this
1694
+ # door, and `RevisionUnverifiable` into a 503 beside it, so both reach the client in
1695
+ # the shape `routes_tables.py`'s direct view routes already answer.
1696
  view = (_tops(ctx).save_view(
1697
  _save_as, view, reserved_names=_reserved_view_names,
1698
+ actor=uname, origin=EVENT_ORIGIN, rev=_event_rev(event)) or view)
1699
  else:
1700
  _session_ready()
1701
  _view_names = list(_reserved_view_names)
 
2693
  # β›” LEFT AS A CORRECTION RATHER THAN DELETED. A comment asserting a guard is dead is
2694
  # exactly what stops the next reader checking, and this one would have outlived the fix.
2695
  try:
2696
+ # ⭐⭐ W51-T33 β€” THE SECOND STAMPED VIEW WRITE, and it is stamped by the client's
2697
+ # own decision: `CustomerGrid.tsx:10075` emits the views-rail `item_move` through
2698
+ # `stampViewWrite`, with the comment *"`move` is one of C3's seven audited actions
2699
+ # and it is a view WRITE like any other"*. `save_folders` has taken `rev=` since
2700
+ # W50-T25, so the value had a door on both sides and no line between them.
2701
+ # ⚠ THE OTHER FOUR KINDS THAT LAND HERE ARE UNAFFECTED. `folder_create`,
2702
+ # `folder_rename`, `folder_delete` and `folder_reorder` carry no stamp, and neither
2703
+ # does `ViewSidebar.tsx:2022`'s folder-nest `item_move`, so `_event_rev` answers None
2704
+ # for every one of them and the comparison is not asked β€” byte-identical behaviour.
2705
  _receipt = _tops(ctx).save_folders(uname, _res[0], _res[1],
2706
+ actor=uname, origin=EVENT_ORIGIN,
2707
+ rev=_event_rev(event))
2708
  except _tstore.FolderTreeError as _fte:
2709
  return _folder_refuse(ctx, kind,
2710
  str(getattr(_fte, 'reason', '') or 'folder_tree_illegal'),
platform/core/relations.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """relations.py β€” THE ONE DECLARATION OF WHAT IS RELATED TO WHAT (W51-T05, contract C6, ruling R2).
2
+
3
+ R2, verbatim: *"A 'Linked database' tab exists for FORWARD link fields, REVERSE links (another
4
+ table's link field pointing at this table) and the ODOO BRIDGES (customers -> orders, order lines,
5
+ open invoices; products -> order lines), one tab per related table, resolved server-side; two links
6
+ between the same pair give two tabs subtitled by the field."*
7
+
8
+ So there are exactly THREE ways one database is related to another, and this module is the single
9
+ place that can name all three:
10
+
11
+ * ``forward`` β€” a ``type: "link"`` field ON this table, pointing at another. Declared by the
12
+ tenant (``core.user_tables._clean_link``) or, for the two registry modules, by
13
+ ``aios-web/api/odoo_relational.module_link_fields``.
14
+ * ``reverse`` β€” ANOTHER table's link field pointing AT this table. Nothing declares this; it is
15
+ found by scanning every definition in the tenant, which is why it needs a function rather than
16
+ a constant.
17
+ * ``bridge`` β€” a pair of columns that joins two Odoo grains where no link field exists and no
18
+ user could create one. ``BRIDGES`` below is the whole list, and it is the only list.
19
+
20
+ β›”β›” THIS MODULE DOES NOT MOVE, RENAME OR SHADOW ``odoo_relational.module_link_fields``.
21
+ That function is reached BY STRING: ``automation_engine._module_link_fields`` calls
22
+ ``getattr(_rel, "module_link_fields", None)``, so renaming it raises no ImportError and silently
23
+ kills the pre-set relation columns on ``customer_data``. It keeps owning the pre-set link FIELDS
24
+ (the columns a grid renders); this module owns the BRIDGES (the joins that were never fields).
25
+ Neither list is copied into the other β€” ``related()`` takes the fields as an ARGUMENT rather than
26
+ importing them, so this file has no opinion about where the field list came from and there is
27
+ exactly one declaration of each edge.
28
+
29
+ β›”β›” THE TWO LISTS ARE **NOT** DISJOINT, AND AN EARLIER DRAFT OF THIS HEADER SAID THEY WERE.
30
+ ``module_link_fields('customer_data')`` declares ``orders`` on ``ut_odoo_orders``, joined
31
+ ``partner_id`` from ``pid`` β€” which is ``bridge_customer_orders``, column for column. Declaring
32
+ both and concatenating them offered ``customer_data`` two tabs, both labelled Orders, over
33
+ identical rows. ``related()`` therefore DEDUPLICATES on ``edge_identity`` and the FIELD wins; see
34
+ its docstring for why ``where`` has to be part of that identity.
35
+
36
+ β›” LAYERING. ``core`` never imports up. ``harness.filter_sql`` is imported LAZILY inside the one
37
+ function that needs it, exactly as ``core.perm_scope`` imports ``harness.filter_eval``.
38
+
39
+ β›”β›” A CORRECTION TO C6'S OWN MECHANISM, MEASURED 2026-09-03 AND REPORTED RATHER THAN WORKED
40
+ AROUND IN SILENCE. C6 says the pin is *"compiled through ``compile_filter_tree(member_ids=,
41
+ id_sql=)``"*. That call CANNOT express a pinned read, for two independent reasons in
42
+ ``platform/harness/filter_sql.py``:
43
+
44
+ 1. ``compile_filter_tree`` returns ``None`` the moment the tree is inactive (``_compile_node``
45
+ answers None for an empty node list), and the ``member_ids`` branch sits BELOW that return.
46
+ A pinned read with no client filter is exactly the inactive case, so the ids would be
47
+ dropped and the WHOLE TABLE served.
48
+ 2. When it does run, ``:588`` emits ``(tree OR id_sql IN (...))``. Its own docstring says so:
49
+ *"``member_ids`` reproduces ``members.has(r.pid) || matchFilterTree(...)``"*. That is a
50
+ UNION. A pinned read needs an INTERSECTION, and ORing a pin onto a filter WIDENS.
51
+
52
+ So the pin is compiled HERE, as ``pin_sql`` below, in the SAME spelling ``compile_filter_tree``
53
+ uses for ``member_ids`` (proven byte for byte by ``verify_pivot.py`` section 20 rather than
54
+ asserted in a comment), and ANDed into the read ahead of the client predicate.
55
+ β‡’ EXIT CONDITION: when ``filter_sql`` grows a narrowing member mode (an amendment against lane B,
56
+ booked in this ticket's handoff), ``pin_sql`` delegates to it and this note is deleted.
57
+ """
58
+
59
+ #: The three ways a database can be related to another. `via.direction` is always one of these.
60
+ DIRECTIONS = ('forward', 'reverse', 'bridge')
61
+
62
+ #: The identity column of a module grid, as the wire spells it. `customer_data.pid` IS the Odoo
63
+ #: `res.partner` id and `ut_odoo_orders.pid` IS the `sale_order` id, so a bridge hanging off `pid`
64
+ #: needs no second lookup. `product_data.pid` is NOT an Odoo id (it is `crc32(default_code)`),
65
+ #: which is why the product bridge below hangs off `product_id` instead.
66
+ IDENTITY_COL = 'pid'
67
+
68
+ #: β›” THE OPEN-INVOICE PREDICATE IS PART OF THE BRIDGE, NOT DECORATION. "Open invoices" is a
69
+ #: different edge from "invoices": a bridge that carried only the column pair would serve EVERY
70
+ #: posted document under a tab labelled Open invoices, which is a wrong number wearing the right
71
+ #: name. It is spelled here in the same SQL `odoo_relational._AR_WHERE` uses, and section 20 of
72
+ #: `verify_pivot.py` asserts the two agree rather than trusting this copy.
73
+ OPEN_INVOICE_WHERE = ("state = 'posted' AND move_type IN ('out_invoice','out_refund') "
74
+ "AND payment_state IN ('not_paid','partial')")
75
+
76
+ #: ⭐⭐ THE FIVE BRIDGES C6 NAMES, AND NOTHING ELSE MAY BE ADDED WITHOUT A RULING.
77
+ #:
78
+ #: `source_col` is the column on the SOURCE row that carries the join value; `target_col` is the
79
+ #: column on the TARGET grid it is matched against. `where` is an extra SQL predicate the edge
80
+ #: itself carries (only the open-invoice bridge has one today).
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
110
+ # against `sale_order_line.product_id` resolves zero rows on every product, silently, with a
111
+ # perfectly plausible empty tab. `product_data` carries Odoo's own id as the `product_id`
112
+ # column (W33-T43 / A2) and that is the column this bridge hangs off.
113
+ # ⚠ MEASURED LIMIT, REPORTED BY THE READ (standing rule 1's second sentence): 8 SKU codes on
114
+ # this catalogue carry two Odoo product ids each, the archived half of each pair having no
115
+ # `product_data` row. Pinning by id therefore reaches the live id's lines and not the archived
116
+ # sibling's. Joining on the CODE instead would fix it, and the line grain carries no code
117
+ # column to join to.
118
+ {'key': 'bridge_product_order_lines',
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
+
132
+ def bridges_from(source):
133
+ """Every declared bridge whose SOURCE is `source`, in declaration order."""
134
+ key = str(source or '')
135
+ return [dict(b) for b in BRIDGES if b['source'] == key]
136
+
137
+
138
+ def bridges_into(target):
139
+ """Every declared bridge whose TARGET is `target`. The other end of `bridges_from`."""
140
+ key = str(target or '')
141
+ return [dict(b) for b in BRIDGES if b['target'] == key]
142
+
143
+
144
+ def _link_bag(field):
145
+ """The `link` bag off a field, or None when the field is not a link."""
146
+ if not isinstance(field, dict) or field.get('type') != 'link':
147
+ return None
148
+ bag = field.get('link')
149
+ return bag if isinstance(bag, dict) else None
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
157
+ this ticket's handoff rather than left for the client half to discover. C6 spells its optional
158
+ keys with a `?`, so an extra optional key is additive rather than a contradiction.
159
+
160
+ * `via.key` β€” β›”β›” WITHOUT IT `via` DOES NOT IDENTIFY AN EDGE, AND THE FIRST DRAFT OF THIS FILE
161
+ SHIPPED THE WRONG-JOIN BUG BECAUSE OF IT. `customer_data` has TWO bridges whose direction is
162
+ `bridge` and whose `on` column is `partner_id` (orders, and order lines): matching on
163
+ `{direction, on}` returns whichever is declared first, so asking for a customer's order
164
+ LINES would have been answered with their ORDERS, in the right shape, with every gate green.
165
+ Two reverse links named `cust` on two different tables collide the same way. The entry key
166
+ is the only thing that is unique, so it rides inside `via` and `find` refuses an ambiguous
167
+ bag rather than guessing.
168
+ * `via.from` β€” WHICH value of the source record the edge is keyed on. Without it the caller
169
+ cannot tell an edge keyed on the row identity from one keyed on an ordinary column
170
+ (`agent_link`'s `from` is the agent NAME), and those two need different handling.
171
+ """
172
+ via = {'direction': direction, 'key': str(key)}
173
+ if field:
174
+ via['field'] = str(field)
175
+ if on:
176
+ via['on'] = str(on)
177
+ if frm:
178
+ via['from'] = str(frm)
179
+ out = {'key': str(key), 'label': str(label), 'via': via, 'target': str(target),
180
+ 'served': bool(served)}
181
+ if where:
182
+ out['where'] = str(where)
183
+ return out
184
+
185
+
186
+ def forward_links(table, fields):
187
+ """The FORWARD entries for `table`: every `type: "link"` field on it, in field order.
188
+
189
+ `fields` is whatever the caller's permission wall handed back, so a link field this account
190
+ may not see is not here and cannot become a tab. That is the point of taking it as an argument
191
+ instead of reading the store: this module never decides who may see what.
192
+
193
+ ⭐ TWO LINKS BETWEEN THE SAME PAIR GIVE TWO ENTRIES, and R2 says so in as many words. The entry
194
+ `key` is the FIELD key, not the target key, which is what keeps them apart on the wire.
195
+ """
196
+ out = []
197
+ for field in (fields or ()):
198
+ bag = _link_bag(field)
199
+ if bag is None:
200
+ continue
201
+ target = str(bag.get('table') or '')
202
+ if not target:
203
+ continue
204
+ out.append(_entry(
205
+ key=str(field.get('key') or ''),
206
+ label=str(field.get('label') or field.get('key') or target),
207
+ target=target, direction='forward',
208
+ field=field.get('key'), on=bag.get('on'),
209
+ frm=bag.get('from') or IDENTITY_COL))
210
+ return out
211
+
212
+
213
+ def reverse_links(table, defs):
214
+ """The REVERSE entries for `table`: every OTHER table's link field that points at it.
215
+
216
+ `defs` is `{key: definition}` as `core.user_tables.all_defs` returns it, already narrowed to
217
+ what this account may open. Nothing declares a reverse link, so this scan IS the declaration
218
+ and there is no second place it could be written down.
219
+
220
+ β›” A TABLE'S LINK TO ITSELF IS NOT A REVERSE LINK. It is already a forward one, and emitting
221
+ both would give the same edge two tabs pointing at the same grid, one of them labelled from
222
+ the wrong end.
223
+ """
224
+ me = str(table or '')
225
+ out = []
226
+ for key, defn in sorted((defs or {}).items()):
227
+ key = str(key)
228
+ if key == me or not isinstance(defn, dict):
229
+ continue
230
+ for field in (defn.get('fields') or ()):
231
+ bag = _link_bag(field)
232
+ if bag is None or str(bag.get('table') or '') != me:
233
+ continue
234
+ out.append(_entry(
235
+ key=f"{key}__{field.get('key') or ''}",
236
+ label=str(defn.get('label') or key),
237
+ target=key, direction='reverse',
238
+ field=field.get('key'),
239
+ # β›” THE COLUMNS SWAP WITH THE DIRECTION, AND GETTING THIS BACKWARDS IS THE
240
+ # SILENT-WRONG-JOIN BUG. Forward, the SOURCE row's `from` value is matched against
241
+ # the TARGET's `on` column. Read from the other end the roles invert: the reverse
242
+ # tab pins the OTHER table on ITS OWN link column (`bag['from']`), keyed by the
243
+ # value this table's `on` column carries. `verify_pivot.py` drives a reverse edge
244
+ # mislabelled `forward` as a negative control for exactly this.
245
+ on=bag.get('from') or IDENTITY_COL,
246
+ frm=bag.get('on') or IDENTITY_COL))
247
+ return out
248
+
249
+
250
+ def bridge_entries(table):
251
+ """The BRIDGE entries for `table`, from `BRIDGES` and from nowhere else."""
252
+ return [_entry(key=b['key'], label=b['label'], target=b['target'], direction='bridge',
253
+ on=b['target_col'], frm=b['source_col'], served=b['served'],
254
+ where=b['where'])
255
+ for b in bridges_from(table)]
256
+
257
+
258
+ def edge_identity(entry):
259
+ """WHAT MAKES TWO ENTRIES THE SAME EDGE: the target, both join columns, and the predicate.
260
+
261
+ β›” `where` IS PART OF THE IDENTITY AND DROPPING IT WOULD DELETE A REAL TAB. "Open invoices"
262
+ and "Invoices" are the same target joined on the same two columns; the ONLY thing that makes
263
+ them different questions is the AR predicate. An identity of `(target, on, from)` alone would
264
+ fold the open-invoice bridge into the pre-set `invoices` link and R2's third bridge would
265
+ silently stop existing.
266
+ """
267
+ via = entry.get('via') or {}
268
+ return (str(entry.get('target') or ''), str(via.get('on') or ''),
269
+ str(via.get('from') or ''), str(entry.get('where') or ''))
270
+
271
+
272
+ def related(table, fields=None, defs=None):
273
+ """THE `/related` ANSWER for one table: forward, then reverse, then bridge.
274
+
275
+ `[{key, label, via: {direction, key, field?, on?, from?}, target, served, where?}]`.
276
+
277
+ β›” THE ORDER IS PART OF THE ANSWER. Forward links are the ones the reader created and can see
278
+ as columns; reverse links are inferred; bridges are ours. A stable order means a tab strip
279
+ does not reshuffle between two reads of the same record.
280
+
281
+ β›”β›” A BRIDGE THAT REPEATS A LINK FIELD IS DROPPED, AND THIS FILE'S HEADER USED TO CLAIM THE
282
+ TWO LISTS WERE DISJOINT WITHOUT CHECKING. THEY ARE NOT. `module_link_fields('customer_data')`
283
+ already declares `orders` -> `ut_odoo_orders` on `partner_id` from `pid`, which is
284
+ `bridge_customer_orders` column for column, so the first build of this function offered
285
+ `customer_data` TWO tabs both labelled Orders, over the same rows, differing only in which one
286
+ the reader happened to click. R2 says *"one tab per related table"* and allows two only when
287
+ there are genuinely two links.
288
+ ⭐ THE FIELD WINS, NOT THE BRIDGE. The field is the one the grid renders as a column, the one
289
+ `automation_engine` resolves, and the one an administrator can see; the bridge exists exactly
290
+ for the edges that are NOT fields. Suppressing the bridge therefore removes a duplicate rather
291
+ than a capability, and `bridge_customer_open_invoices` survives because its predicate makes it
292
+ a different question about the same pair.
293
+ ⚠ ON A TENANT WITH NO PRE-SET LINKS the bridge is not a duplicate of anything and is offered
294
+ unchanged, which is the whole reason the suppression is computed rather than declared.
295
+ """
296
+ forward = forward_links(table, fields or ())
297
+ reverse = reverse_links(table, defs or {})
298
+ seen = {edge_identity(e) for e in forward} | {edge_identity(e) for e in reverse}
299
+ bridges = [b for b in bridge_entries(table) if edge_identity(b) not in seen]
300
+ return forward + reverse + bridges
301
+
302
+
303
+ def find(table, via, fields=None, defs=None):
304
+ """The ONE entry of `related(table, ...)` that `via` names, or None. See `pick`."""
305
+ return pick(related(table, fields, defs), via)
306
+
307
+
308
+ def pick(entries, via):
309
+ """The ONE entry `via` names out of an ALREADY-BUILT list, or None.
310
+
311
+ β›” THE LIST IS AN ARGUMENT SO THE ROUTE LAYER CAN HAND IN A **SCOPED** ONE. The read side
312
+ resolves a pin against exactly the entries the listing door would have offered this account,
313
+ which is what makes "an edge you cannot see is an edge you cannot pin" true by construction
314
+ rather than by two functions agreeing.
315
+
316
+ β›”β›” EXACTLY ONE, OR NONE. `via.key` identifies an edge on its own; a bag without one is
317
+ matched on `direction` plus whichever of `field` / `on` it carries, and **an ambiguous match
318
+ answers None**. It does NOT answer the first hit. `customer_data` really does carry two
319
+ bridges reading `{direction: "bridge", on: "partner_id"}` (orders and order lines), so
320
+ first-hit would have served one record's orders under the order-lines tab, correctly shaped
321
+ and wrong. Refusing sends the caller back with a sentence; guessing sends it a number.
322
+ """
323
+ if not isinstance(via, dict):
324
+ return None
325
+ want_dir = str(via.get('direction') or '')
326
+ if want_dir not in DIRECTIONS:
327
+ return None
328
+ want_key = str(via.get('key') or '')
329
+ want_field = str(via.get('field') or '')
330
+ want_on = str(via.get('on') or '')
331
+ if not (want_key or want_field or want_on):
332
+ return None # a direction alone names no edge; refuse rather than guess
333
+ hits = []
334
+ for entry in (entries or ()):
335
+ got = entry['via']
336
+ if got['direction'] != want_dir:
337
+ continue
338
+ if want_key:
339
+ if entry['key'] == want_key:
340
+ return entry
341
+ continue
342
+ if want_field and str(got.get('field') or '') != want_field:
343
+ continue
344
+ if want_on and str(got.get('on') or '') != want_on:
345
+ continue
346
+ hits.append(entry)
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):
370
+ """The sentence an edge earns when the source record's JOIN VALUE cannot be read.
371
+
372
+ ⭐ IT FIRES ONLY FOR AN EDGE KEYED ON A COLUMN. When `via.from` is the record identity the
373
+ value IS the record and there is nothing to resolve; when it is an ordinary column
374
+ (`agent_link` is keyed on the agent NAME, `bridge_product_order_lines` on `product_id`) the
375
+ cell is read off the source row, and it comes back missing two ways: the record is not in the
376
+ set this reader may see, or that cell is empty on that row.
377
+
378
+ β›” REFUSING BEATS FALLING BACK TO THE RECORD ID. `product_data.pid` is `crc32(default_code)`,
379
+ so a fallback would join a hash against an Odoo id, match nothing, and paint as "this product
380
+ has never been ordered" - a claim about the business made out of a missing input.
381
+ β›” AND IT NAMES NEITHER CAUSE AS THE CAUSE. Saying "you may not see that record" would leak
382
+ whether the record exists; saying "that cell is empty" would be a guess. Both are offered.
383
+ """
384
+ via = entry.get('via') or {}
385
+ frm = str(via.get('from') or '')
386
+ return (f"the relation '{entry.get('key')}' is keyed on the '{frm}' value of the record you "
387
+ f"asked to pin, and that value could not be read from '{table}' for this record, "
388
+ f"either because it is not a record this account may see or because the cell is "
389
+ f"empty on it. Open '{entry.get('target')}' on its own and filter it on "
390
+ f"'{via.get('on') or frm}', or pin a record that carries a '{frm}'")
391
+
392
+
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
407
+
408
+ def member_ids_tail(id_sql, member_ids):
409
+ """`(sql, params)` for "the row identity is one of these ids", in filter_sql's OWN spelling.
410
+
411
+ β›”β›” READ THE MODULE HEADER BEFORE CHANGING THIS. It is deliberately the SAME expression
412
+ `harness.filter_sql.compile_filter_tree` emits for its `member_ids` argument
413
+ (`f"{id_sql} IN ({','.join('?' for _ in ids)})"`, `:588`) and NOT the `COALESCE(..., FALSE)`
414
+ form `_compile_cohort` uses at `:528`. The difference is real and this is the right side of
415
+ it: a NULL row identity is not a member of any set, so SQL dropping the row is the answer we
416
+ want, whereas COALESCE-to-FALSE would matter only under a NOT.
417
+
418
+ `verify_pivot.py` proves the two spellings agree by compiling a real tree through
419
+ `compile_filter_tree(member_ids=..., id_sql=...)` and extracting its tail, rather than by this
420
+ comment. That is what stops the two drifting apart.
421
+
422
+ β›” AN EMPTY MEMBER SET IS `1=0`, NEVER "NO PIN". `compile_filter_tree` treats an empty
423
+ `member_ids` as falsy and emits nothing, which on a UNION is correct and on a pinned read is
424
+ the whole table. A record with no related rows must answer zero rows.
425
+ """
426
+ ident = str(id_sql or '')
427
+ if not ident:
428
+ raise ValueError('a pinned read needs id_sql (the row-identity column). Refusing rather '
429
+ 'than defaulting: a pin on the wrong column is a wrong answer with '
430
+ 'nothing red beside it')
431
+ ids = [int(x) for x in (member_ids or ())]
432
+ if not ids:
433
+ return ('1=0', [])
434
+ return (f"{ident} IN ({','.join('?' for _ in ids)})", ids)
435
+
436
+
437
+ def pin_sql(id_sql, member_ids):
438
+ """THE PINNED-READ PREDICATE. `(sql, params)`, to be ANDed AHEAD of any client filter.
439
+
440
+ β›” ANDED, NOT OR'ED, AND THAT IS WHY THIS FUNCTION EXISTS RATHER THAN A `member_ids=` ARGUMENT
441
+ ON `compile_filter_tree`. See the module header: that argument is a documented UNION and is
442
+ skipped entirely when the client sends no filter.
443
+ """
444
+ return member_ids_tail(id_sql, member_ids)
445
+
446
+
447
+ def compiled_pin_matches_filter_sql(id_sql, member_ids, columns=None):
448
+ """Does `pin_sql` still spell the member tail exactly as `filter_sql` spells it?
449
+
450
+ Returns `(ours, theirs)` β€” two SQL fragments a gate can compare. `theirs` is extracted from a
451
+ REAL `compile_filter_tree` call carrying `member_ids=`, so the day lane B changes that
452
+ spelling this answers two different strings instead of agreeing by assumption.
453
+
454
+ ⚠ The tree handed to `compile_filter_tree` must be ACTIVE or the call returns None before the
455
+ member branch runs at all, which is the first half of the correction in this module's header.
456
+ """
457
+ from harness import filter_sql as _fs # noqa: PLC0415 - layering
458
+
459
+ cols = dict(columns or {'__pin_probe__': {'sql': 'probe', 'type': 'text',
460
+ 'aggregate': False}})
461
+ probe = next(iter(cols))
462
+ got = _fs.compile_filter_tree([{'colId': probe, 'op': 'isNotEmpty'}],
463
+ conj='and', columns=cols,
464
+ member_ids=list(member_ids or ()), id_sql=id_sql)
465
+ ours = pin_sql(id_sql, member_ids)[0]
466
+ theirs = None
467
+ if got is not None and ' OR ' in got.sql:
468
+ # β›” EXACTLY ONE closing paren, never `rstrip(')')`. The tail is `sol.id IN (?,?,?))` β€”
469
+ # the last `)` closes `compile_filter_tree`'s own wrapper and the one before it closes the
470
+ # IN list. `rstrip` eats both and the gate then compares `sol.id IN (?,?,?` against a
471
+ # correct fragment and reports a drift that is entirely its own.
472
+ theirs = got.sql.rsplit(' OR ', 1)[1]
473
+ if theirs.endswith(')'):
474
+ theirs = theirs[:-1]
475
+ return ours, theirs
platform/core/shares.py CHANGED
@@ -80,7 +80,7 @@ SHARES_KEY = 'object_shares'
80
  #: here is this tuple member. That is the point of one registry: the new object's WALL is written
81
  #: once in `core.perm_scope`, and its DOORS once in `routes_shares.py` β€” never a fourth
82
  #: permission decision in a fourth file ([[one-evaluator-per-question]]).
83
- KINDS = ('view', 'folder', 'database', 'field', 'cohort')
84
 
85
  #: `*` is "everyone who can already open the surface". It is NOT "every account on the platform".
86
  #: Spelled as a single character so it can never collide with a username (usernames are lower-case
 
80
  #: here is this tuple member. That is the point of one registry: the new object's WALL is written
81
  #: once in `core.perm_scope`, and its DOORS once in `routes_shares.py` β€” never a fourth
82
  #: permission decision in a fourth file ([[one-evaluator-per-question]]).
83
+ KINDS = ('view', 'folder', 'database', 'field', 'cohort', 'workbook')
84
 
85
  #: `*` is "everyone who can already open the surface". It is NOT "every account on the platform".
86
  #: Spelled as a single character so it can never collide with a username (usernames are lower-case
platform/core/sheet_import.py ADDED
@@ -0,0 +1,980 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/sheet_import.py β€” the .xlsx IMPORTER (wave 51, instruction 7, ticket W51-T24, contract C4).
2
+
3
+ WHAT GOES HERE:
4
+
5
+ One pure function, `import_workbook(path)`, that turns an .xlsx file on disk into the C1/C2
6
+ document `core/sheets.py` already knows how to store, plus a REPORT of what did not survive.
7
+ It resolves nothing, writes nothing and knows no store: the job, the temp file, the thread and
8
+ the differential all belong to `aios-web/api/routes_sheet.py`, which is the one place that can
9
+ recompute a formula and persist a document.
10
+
11
+ ⭐⭐ **THE IMPORT IS TWO OPENPYXL PASSES, AND BOTH ARE NEEDED FOR THE SAME CELL.** With
12
+ `data_only=False` a formula cell hands back its FORMULA TEXT and with `data_only=True` it hands
13
+ back the value Excel last CACHED for it. R1's done-when is a differential between those two
14
+ readings and our own engine, so a one-pass import cannot be checked at all: it would store 11,336
15
+ formulas and have nothing to compare our answers against.
16
+
17
+ ⭐⭐ **THE CACHED VALUE RIDES OUT ON `imported_value` AND IS NEVER STORED.** `clean_cell` builds a
18
+ fresh dict from the keys it names, so an unnamed key is dropped by the ordinary save path anyway;
19
+ this module puts the cached reading there deliberately so the caller can run the differential in
20
+ memory and then drop it. β›” THE ALTERNATIVE WAS MEASURED AND REJECTED: parking it in `source`
21
+ (a dict `clean_cell` does carry) would persist a second copy of every formula's value, which is
22
+ about 0.9 MiB on the owner's model against a 16 MiB cap, to store a number the recalc has already
23
+ replaced.
24
+
25
+ β›”β›” **A COLOUR ARRIVES AS ARGB HEX AND MUST NOT BE STORED AS ONE.** `sheets._COLOUR` would accept
26
+ `FF1F4E78` in silence, which would freeze a palette decision into a stored document that outlives
27
+ every palette change (DESIGN.md 3, and `types.ts` is token only). So every colour is QUANTIZED to
28
+ the nearest `--lp-*` token by RGB distance, and the two defaults (ink on white) are stored as an
29
+ ABSENCE for `_clean_style`'s reason: a cell painted the colour it already is must compare equal to
30
+ the cell that was never painted. On the owner's model that absence is what keeps 43,285 explicit
31
+ font colours from becoming 43,285 stored style wrappers.
32
+
33
+ β›” **UNSUPPORTED IS A LIST, NOT A SILENCE (standing rule 1's second sentence).** Everything this
34
+ module cannot carry is named once, with a count, in the tab's `imported.unsupported` and in the
35
+ report. An importer that drops a hidden tab, a theme colour or a scatter chart without saying so
36
+ hands back a workbook that looks complete and is not.
37
+
38
+ ⚠ Every note in here reaches a screen, so none carries an em dash or an en dash (standing rule 2).
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import re
44
+ from datetime import date, datetime, time, timezone
45
+
46
+ from core import sheets
47
+
48
+ #: C4's upload ceiling. ⚠ IT IS THE FILE, NOT THE DOCUMENT. An .xlsx is zipped, so 25 MB of file
49
+ #: can be far more than `sheets.MAX_WORKBOOK_BYTES` of document; the document cap is enforced
50
+ #: where it belongs, by `_json_safe` on the save, and this one only stops an upload nothing could
51
+ #: parse in reasonable time.
52
+ MAX_IMPORT_BYTES = 25 * 1024 * 1024
53
+
54
+ #: C4's job states, in the order a job walks them. `refused` is the exit that replaces `done`.
55
+ IMPORT_STATES = ("reading", "cells", "formats", "recalc", "done", "refused")
56
+
57
+ #: β›” THE PALETTE, COPIED FROM `aios-web/web/src/index.css` `:root`, TOKEN FOR TOKEN. It is copied
58
+ #: rather than read because `platform/core` may not reach up into the web tree (ARCHITECTURE.md's
59
+ #: one-way layering), and `verify_sheet.py` section 4 parses the CSS and asserts every pair below
60
+ #: still matches it, so the copy cannot drift in silence.
61
+ #:
62
+ #: ⚠ ONLY PAINTABLE TOKENS ARE HERE. The `--lp-fs-*`, `--lp-r-*` and layout tokens in that block
63
+ #: are sizes, not colours, and quantizing a fill onto one of them would be nonsense.
64
+ PALETTE = {
65
+ "--lp-surface": "#ffffff",
66
+ "--lp-surface-2": "#f7f7f6",
67
+ "--lp-ink": "#202433",
68
+ "--lp-muted": "#6b7280",
69
+ "--lp-line": "#e6e9ef",
70
+ "--lp-wash": "#fafbfc",
71
+ "--lp-blue": "#9dbff2",
72
+ "--lp-blue-tint": "#edf3fd",
73
+ "--lp-blue-deep": "#768fb6",
74
+ "--lp-blue-solid": "#5b8fd9",
75
+ "--lp-map-selected": "#1b4f9c",
76
+ "--lp-yellow": "#f5d989",
77
+ "--lp-yellow-tint": "#fbf4e0",
78
+ "--lp-yellow-deep": "#7e6428",
79
+ "--lp-red": "#f0a8a0",
80
+ "--lp-red-tint": "#fceeec",
81
+ "--lp-red-deep": "#a3453c",
82
+ "--lp-green": "#a5d8b4",
83
+ "--lp-green-tint": "#ebf6ef",
84
+ "--lp-green-deep": "#35754e",
85
+ "--lp-purple": "#c3b3ee",
86
+ "--lp-purple-tint": "#f1eefb",
87
+ "--lp-purple-deep": "#6b57a8",
88
+ "--lp-brand": "#6e56cf",
89
+ "--lp-primary": "#5433cc",
90
+ "--lp-primary-hover": "#472bad",
91
+ "--lp-primary-tint": "#eeeafc",
92
+ }
93
+
94
+ #: ⭐ THE TWO DEFAULTS, STORED AS AN ABSENCE. Ink on white is what every unpainted cell already
95
+ #: is, so writing them would make a cell somebody coloured black compare unequal to the cell that
96
+ #: was never coloured, and would cost a style wrapper on tens of thousands of cells that look
97
+ #: exactly the same either way.
98
+ DEFAULT_INK = "--lp-ink"
99
+ DEFAULT_FILL = "--lp-surface"
100
+
101
+ #: The four font steps A1 froze, in points. A size is a STEP and never a pixel count, for
102
+ #: `_clean_style`'s reason: a stored pixel size is a layout decision that outlives the layout.
103
+ _SIZE_STEPS = ((9.5, "s"), (12.5, "m"), (16.5, "l"))
104
+
105
+ #: Excel's horizontal alignments that have a home in `CELL_ALIGNS`. Everything else is named in
106
+ #: `unsupported` rather than guessed at: `justify` and `distributed` are not `left`.
107
+ _ALIGNS = {"left": "left", "center": "center", "centre": "center", "right": "right"}
108
+ _VALIGNS = {"top": "top", "center": "middle", "centre": "middle", "bottom": "bottom"}
109
+
110
+ #: openpyxl's `cellIs` operators, mapped onto `sheets.SHEET_RULE_OPS`. β›” AN OPERATOR THAT IS NOT
111
+ #: HERE IS NAMED IN `unsupported` AND THE RULE IS DROPPED, never passed through: `_clean_rules`
112
+ #: REFUSES an op outside its ten by name, so a guess here would 400 a whole import over one rule.
113
+ _RULE_OPS = {
114
+ "lessThan": "lt", "lessThanOrEqual": "lte", "greaterThan": "gt",
115
+ "greaterThanOrEqual": "gte", "equal": "eq", "notEqual": "neq", "between": "between",
116
+ }
117
+
118
+ #: openpyxl chart classes mapped onto `sheets.SHEET_CHART_KINDS`, by class NAME so this module
119
+ #: does not import four chart classes it would then have to keep in step.
120
+ _CHART_KINDS = {"BarChart": "bar", "BarChart3D": "bar", "LineChart": "line",
121
+ "LineChart3D": "line", "AreaChart": "area", "AreaChart3D": "area",
122
+ "PieChart": "donut", "PieChart3D": "donut", "DoughnutChart": "donut"}
123
+
124
+ #: The currency symbols a number format may wear, mapped to the ISO code `CellFormat.currency`
125
+ #: carries. ⚠ AN UNKNOWN SYMBOL FALLS TO `code`, which renders it EXACTLY as the file asked;
126
+ #: guessing an ISO code from a glyph we do not know is how a number acquires the wrong currency.
127
+ _CURRENCY_SYMBOLS = {"$": "USD", "€": "EUR", "Β£": "GBP", "Β₯": "JPY",
128
+ "β‚©": "KRW", "β‚Ή": "INR", "β‚½": "RUB", "Rp": "IDR"}
129
+
130
+ _QUOTED = re.compile(r'"[^"]*"')
131
+ _BRACKET = re.compile(r"\[[^\]]*\]")
132
+ _PLAIN_NUMBER = re.compile(r"^[#0,.\s+-]+$")
133
+ _DATE_LETTERS = re.compile(r"[ymdhs]", re.I)
134
+ _A1_CELL = re.compile(r"^([A-Z]{1,3})([0-9]{1,7})$")
135
+
136
+ #: How many addresses one validation or one conditional rule may paint onto cells that do not
137
+ #: otherwise exist. ⚠ A DATA VALIDATION IS ROUTINELY ATTACHED TO A WHOLE COLUMN, so expanding
138
+ #: its `sqref` blindly would invent a million style-only cells out of one dropdown.
139
+ _MAX_SPREAD = 2000
140
+
141
+ #: How many mismatches the caller's report lists individually. Past this the count still tells the
142
+ #: truth and the list stops growing; a report is read by a person, not by a diff tool.
143
+ MAX_MISMATCHED = 500
144
+
145
+
146
+ # ── colour ───────────────────────────────────────────────────────────────────────────────────
147
+
148
+ def _rgb_of(token_hex):
149
+ h = token_hex.lstrip("#")
150
+ return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
151
+
152
+
153
+ _PALETTE_RGB = {name: _rgb_of(value) for name, value in PALETTE.items()}
154
+
155
+
156
+ def argb_of(colour):
157
+ """The six hex digits of an openpyxl colour, or "" when it is not an explicit RGB one.
158
+
159
+ ⚠ THEME AND INDEXED COLOURS ANSWER "" ON PURPOSE. Resolving a theme colour needs the
160
+ workbook's theme XML and its tint arithmetic, and a wrong resolution paints a cell a colour
161
+ nobody chose. The caller names them in `unsupported` instead.
162
+ """
163
+ if colour is None:
164
+ return ""
165
+ raw = getattr(colour, "rgb", None)
166
+ if not isinstance(raw, str):
167
+ return ""
168
+ text = raw.strip().upper()
169
+ if len(text) == 8:
170
+ # ⚠ A FULLY TRANSPARENT COLOUR IS NOT A COLOUR. `00000000` is openpyxl's "auto", which
171
+ # means "whatever the theme says", not "black".
172
+ if text[:2] == "00":
173
+ return ""
174
+ text = text[2:]
175
+ if len(text) != 6 or any(c not in "0123456789ABCDEF" for c in text):
176
+ return ""
177
+ return text
178
+
179
+
180
+ def quantize(argb):
181
+ """The nearest `--lp-*` token to six ARGB hex digits, or "" when there is nothing to quantize.
182
+
183
+ β›” NEAREST BY SQUARED RGB DISTANCE, and that is a deliberate simplification rather than an
184
+ oversight: a perceptual distance would need a colour space this layer has no business
185
+ carrying, and the palette is small and widely spaced enough that the two agree on every token
186
+ in it. What matters is that the ANSWER IS A TOKEN, so no hex reaches a stored document.
187
+ """
188
+ if not argb:
189
+ return ""
190
+ r, g, b = _rgb_of(argb)
191
+ best, best_d = "", None
192
+ for name, (pr, pg, pb) in _PALETTE_RGB.items():
193
+ d = (r - pr) ** 2 + (g - pg) ** 2 + (b - pb) ** 2
194
+ if best_d is None or d < best_d:
195
+ best, best_d = name, d
196
+ return best
197
+
198
+
199
+ # ── number formats ───────────────────────────────────────────────────────────────────────────
200
+
201
+ def classify_format(code):
202
+ """`(format_dict_or_None, note_or_empty)` for one Excel number format code.
203
+
204
+ ⭐⭐ THE FALLBACK IS `code`, NOT A GUESS, AND THAT IS WHY 53% OF THE OWNER'S MODEL SURVIVES.
205
+ `CellFormat` can say number, currency, percent and date; it cannot say accounting, cannot say
206
+ "negatives in brackets" and cannot carry a per-section branch. A code we do not recognise is
207
+ handed on VERBATIM as `{kind: "code", code}` so the client's formatter renders exactly what
208
+ the file asked for, and only a code `_clean_format_code` would refuse becomes a note.
209
+
210
+ β›” A MULTI-SECTION CODE IS NEVER CLASSIFIED. `_(* #,##0_);_(* \\(#,##0\\);...` reduces to
211
+ something that looks like a plain number pattern once its pads and escapes are stripped, and
212
+ reading it as `number` would silently stop showing negatives in brackets. Any `;` sends the
213
+ code straight to `code`.
214
+ """
215
+ text = str(code or "").strip()
216
+ if not text or text.lower() == "general":
217
+ return None, ""
218
+
219
+ def _as_code():
220
+ try:
221
+ return {"kind": "code", "code": sheets._clean_format_code(text)}, ""
222
+ except sheets.SheetRefusal as exc:
223
+ return None, "a number format could not be carried (" + exc.code + ")"
224
+
225
+ if ";" in text:
226
+ return _as_code()
227
+ #: A pad (`_x`), a fill (`*x`) or an escape (`\\x`) is layout this model does not express, so
228
+ #: the whole code goes through verbatim rather than being partly understood.
229
+ if any(ch in text for ch in ("_", "*", "\\")):
230
+ return _as_code()
231
+ if "@" in text:
232
+ return _as_code()
233
+
234
+ quoted = [q[1:-1] for q in _QUOTED.findall(text)]
235
+ bare = _BRACKET.sub("", _QUOTED.sub("", text))
236
+ brackets = _BRACKET.findall(text)
237
+
238
+ if _DATE_LETTERS.search(bare):
239
+ return {"kind": "date"}, ""
240
+
241
+ decimals = 0
242
+ dot = bare.split(".")
243
+ if len(dot) > 1:
244
+ decimals = len(re.match(r"[0#]*", dot[1]).group(0))
245
+ thousands = "#,#" in bare or "0,0" in bare or ",##" in bare
246
+
247
+ if "%" in bare:
248
+ out = {"kind": "percent"}
249
+ if decimals:
250
+ out["decimals"] = decimals
251
+ return out, ""
252
+
253
+ symbols = [s for s in quoted if s.strip()] + [b.strip("[]$-") for b in brackets if "$" in b]
254
+ symbols += [ch for ch in bare if ch in _CURRENCY_SYMBOLS]
255
+ iso = ""
256
+ for sym in symbols:
257
+ key = sym.strip()
258
+ if key in _CURRENCY_SYMBOLS:
259
+ iso = _CURRENCY_SYMBOLS[key]
260
+ break
261
+ if len(key) == 3 and key.isalpha():
262
+ iso = key.upper()
263
+ break
264
+
265
+ stripped = bare
266
+ for ch in _CURRENCY_SYMBOLS:
267
+ stripped = stripped.replace(ch, "")
268
+ if iso and _PLAIN_NUMBER.match(stripped or "0"):
269
+ out = {"kind": "currency", "currency": iso}
270
+ if decimals:
271
+ out["decimals"] = decimals
272
+ return out, ""
273
+
274
+ if not quoted and not brackets and _PLAIN_NUMBER.match(bare):
275
+ out = {"kind": "number"}
276
+ if decimals:
277
+ out["decimals"] = decimals
278
+ if thousands:
279
+ out["thousands"] = True
280
+ return out, ""
281
+
282
+ return _as_code()
283
+
284
+
285
+ # ── one cell's style ─────────────────────────────────────────────────────────────────────────
286
+
287
+ def _size_step(points):
288
+ if not isinstance(points, (int, float)):
289
+ return ""
290
+ for limit, step in _SIZE_STEPS:
291
+ if points < limit:
292
+ return step
293
+ return "xl"
294
+
295
+
296
+ def style_of(cell, notes):
297
+ """The C2 style for one openpyxl cell, or `{}` when nothing about it is worth storing.
298
+
299
+ ⚠ FONT FAMILY IS DROPPED IN SILENCE AND THAT IS THE DESIGN, not an omission: the app is Inter
300
+ everywhere (DESIGN.md), so carrying Arial would either be ignored or would put a second
301
+ typeface on a screen the design forbids. It is still NAMED in the report, once, because a
302
+ person who imported an Arial workbook should be told why it does not look like Arial.
303
+ """
304
+ out = {}
305
+ font = getattr(cell, "font", None)
306
+ if font is not None:
307
+ if font.b:
308
+ out["bold"] = True
309
+ if font.i:
310
+ out["italic"] = True
311
+ if font.u:
312
+ out["underline"] = True
313
+ step = _size_step(font.sz)
314
+ if step and step != "m":
315
+ out["size"] = step
316
+ argb = argb_of(font.color)
317
+ if argb:
318
+ token = quantize(argb)
319
+ if token and token != DEFAULT_INK:
320
+ out["color"] = token
321
+ elif font.color is not None and getattr(font.color, "type", "") in ("theme", "indexed"):
322
+ notes.add("a theme or indexed font colour was replaced by the default ink")
323
+
324
+ fill = getattr(cell, "fill", None)
325
+ if fill is not None and getattr(fill, "patternType", None) == "solid":
326
+ argb = argb_of(fill.fgColor)
327
+ if argb:
328
+ token = quantize(argb)
329
+ if token and token != DEFAULT_FILL:
330
+ out["fill"] = token
331
+ elif getattr(fill.fgColor, "type", "") in ("theme", "indexed"):
332
+ notes.add("a theme or indexed cell fill was left unpainted")
333
+ elif fill is not None and getattr(fill, "patternType", None):
334
+ notes.add("a patterned cell fill was left unpainted, because a fill is a flat colour here")
335
+
336
+ align = getattr(cell, "alignment", None)
337
+ if align is not None:
338
+ horizontal = str(align.horizontal or "")
339
+ if horizontal in _ALIGNS:
340
+ out["align"] = _ALIGNS[horizontal]
341
+ elif horizontal and horizontal != "general":
342
+ notes.add("the " + horizontal + " horizontal alignment has no equivalent here")
343
+ vertical = str(align.vertical or "")
344
+ if vertical in _VALIGNS:
345
+ if _VALIGNS[vertical] != "bottom":
346
+ out["valign"] = _VALIGNS[vertical]
347
+ elif vertical:
348
+ notes.add("the " + vertical + " vertical alignment has no equivalent here")
349
+ if align.wrapText:
350
+ out["wrap"] = True
351
+ if isinstance(align.indent, (int, float)) and int(align.indent) > 0:
352
+ out["indent"] = min(sheets._MAX_INDENT, int(align.indent))
353
+
354
+ border = getattr(cell, "border", None)
355
+ if border is not None:
356
+ sides = {}
357
+ for side in sheets._BORDER_SIDES:
358
+ edge = getattr(border, side, None)
359
+ if edge is not None and getattr(edge, "style", None):
360
+ sides[side] = True
361
+ if sides:
362
+ out["border"] = sides
363
+ notes.add("a border keeps its side but not its weight, style or colour")
364
+
365
+ fmt, note = classify_format(getattr(cell, "number_format", ""))
366
+ if fmt:
367
+ out["format"] = fmt
368
+ if note:
369
+ notes.add(note)
370
+ return out
371
+
372
+
373
+ # ── values ───────────────────────────────────────────────────────────────────────────────────
374
+
375
+ def json_value(value):
376
+ """One openpyxl value as something the store can hold, or None when it cannot be carried.
377
+
378
+ β›” A `datetime` IS NOT JSON. `_json_safe` refuses a value it cannot serialize, so a date cell
379
+ handed straight through would refuse the WHOLE workbook on save; it becomes an ISO string,
380
+ which is what every other date on the wire in this app already is.
381
+ """
382
+ if value is None or isinstance(value, (str, int, float, bool)):
383
+ #: ⚠ A float that is not finite is not JSON either, and `json.dumps` emits `NaN`, which
384
+ #: no other JSON reader accepts. It is carried as absent rather than as a number.
385
+ if isinstance(value, float) and (value != value or value in (float("inf"),
386
+ float("-inf"))):
387
+ return None
388
+ return value
389
+ if isinstance(value, datetime):
390
+ return value.replace(microsecond=0).isoformat()
391
+ if isinstance(value, (date, time)):
392
+ return value.isoformat()
393
+ return str(value)
394
+
395
+
396
+ def values_match(computed, cached, *, tolerance=1e-6):
397
+ """R1's differential test for ONE cell: numbers within `tolerance` relative, strings exact.
398
+
399
+ ⭐ A RELATIVE TOLERANCE, WITH AN ABSOLUTE FLOOR. Excel caches a double and our engine computes
400
+ one, so the last bits differ on any long sum; a relative test says that is the same number,
401
+ and the floor is what stops `0.0` versus `1e-18` from being a 100% relative miss.
402
+
403
+ ⚠ `True == 1` IN PYTHON, so booleans are compared as booleans first. Without that leg a cell
404
+ Excel cached as `TRUE` would silently match a computed `1`.
405
+ """
406
+ if computed is None and cached is None:
407
+ return True
408
+ if isinstance(computed, bool) or isinstance(cached, bool):
409
+ return bool(computed) is bool(cached) and type(computed) is type(cached)
410
+ if isinstance(computed, (int, float)) and isinstance(cached, (int, float)):
411
+ gap = abs(float(computed) - float(cached))
412
+ scale = max(abs(float(computed)), abs(float(cached)), 1.0)
413
+ return gap <= tolerance * scale
414
+ if computed is None or cached is None:
415
+ return False
416
+ return str(computed) == str(cached)
417
+
418
+
419
+ def mismatch_kind(computed, cached):
420
+ """The CLASS of a mismatch, which is what a report is read for.
421
+
422
+ ⚠ It answers what the two readings ARE, not why they differ: a class tells the reader whether
423
+ the engine got a number wrong, refused outright, or returned a different SHAPE of thing, and
424
+ those three send them to three different places.
425
+ """
426
+ if computed is None:
427
+ return "refused"
428
+ if isinstance(computed, (int, float)) and isinstance(cached, (int, float)) \
429
+ and not isinstance(computed, bool) and not isinstance(cached, bool):
430
+ return "number"
431
+ if isinstance(computed, str) and isinstance(cached, str):
432
+ return "text"
433
+ return "type"
434
+
435
+
436
+ # ── geometry helpers ─────────────────────────────────────────────────────────────────────────
437
+
438
+ def col_index(letters):
439
+ """`A` -> 0. The zero-based column a chart rectangle and a hidden column count in."""
440
+ n = 0
441
+ for ch in str(letters).upper():
442
+ if not ch.isalpha():
443
+ return -1
444
+ n = n * 26 + (ord(ch) - 64)
445
+ return n - 1
446
+
447
+
448
+ def _corner(ref):
449
+ """`$B$4` -> `(1, 3)` zero-based, or None."""
450
+ found = _A1_CELL.match(str(ref or "").replace("$", "").upper())
451
+ if not found:
452
+ return None
453
+ return col_index(found.group(1)), int(found.group(2)) - 1
454
+
455
+
456
+ def rect_of(ref):
457
+ """A zero-based inclusive rectangle for `'Tab'!$B$2:$D$40`, or None. The tab part is ignored."""
458
+ text = str(ref or "").split("!")[-1].replace("$", "").upper()
459
+ parts = text.split(":")
460
+ first = _corner(parts[0])
461
+ last = _corner(parts[-1]) if len(parts) > 1 else first
462
+ if first is None or last is None:
463
+ return None
464
+ return {"col0": min(first[0], last[0]), "row0": min(first[1], last[1]),
465
+ "col1": max(first[0], last[0]), "row1": max(first[1], last[1])}
466
+
467
+
468
+ def sheet_of_ref(ref):
469
+ """The tab a `'Tab'!$B$2` reference names, unquoted, or "" when it names none."""
470
+ text = str(ref or "")
471
+ if "!" not in text:
472
+ return ""
473
+ head = text.rsplit("!", 1)[0].strip()
474
+ if head.startswith("'") and head.endswith("'") and len(head) > 1:
475
+ head = head[1:-1].replace("''", "'")
476
+ return head
477
+
478
+
479
+ def freeze_of(anchor):
480
+ """`A2` -> `{"rows": 1}`. The anchor is the first cell BELOW and RIGHT of the frozen panes."""
481
+ corner = _corner(anchor)
482
+ if corner is None:
483
+ return {}
484
+ cols, rows = corner
485
+ out = {}
486
+ if cols > 0:
487
+ out["cols"] = cols
488
+ if rows > 0:
489
+ out["rows"] = rows
490
+ return out
491
+
492
+
493
+ def width_px(chars):
494
+ """Excel's character width to pixels, clamped into `MIN_COL_WIDTH..MAX_COL_WIDTH`.
495
+
496
+ ⚠ THE CONVERSION IS EXCEL'S OWN APPROXIMATION (7 px per character of the default face plus
497
+ 5 px of padding), not a measurement of Inter. It cannot be exact across two typefaces, and a
498
+ column that is one character too narrow is a drag away from right; a column stored in
499
+ CHARACTERS would be a unit the grid cannot lay out at all.
500
+ """
501
+ if not isinstance(chars, (int, float)) or chars <= 0:
502
+ return 0
503
+ return max(sheets.MIN_COL_WIDTH, min(sheets.MAX_COL_WIDTH, int(round(chars * 7.0 + 5))))
504
+
505
+
506
+ def _spread(sqref, limit=_MAX_SPREAD):
507
+ """Every A1 address a `sqref` covers, at most `limit` of them, plus whether it was cut."""
508
+ out = []
509
+ for part in str(sqref or "").replace("$", "").upper().split():
510
+ rect = rect_of(part)
511
+ if rect is None:
512
+ continue
513
+ for row in range(rect["row0"], rect["row1"] + 1):
514
+ for col in range(rect["col0"], rect["col1"] + 1):
515
+ if len(out) >= limit:
516
+ return out, True
517
+ out.append(_addr(col, row))
518
+ return out, False
519
+
520
+
521
+ def _addr(col, row):
522
+ """`(1, 3)` -> `B4`. Zero-based in, A1 out."""
523
+ letters, n = "", col + 1
524
+ while n > 0:
525
+ n, rem = divmod(n - 1, 26)
526
+ letters = chr(65 + rem) + letters
527
+ return letters + str(row + 1)
528
+
529
+
530
+ # ── the import ───────────────────────────────────────────────────────────────────────────────
531
+
532
+ class ImportRefusal(Exception):
533
+ """A named refusal the job reports as `state: refused` with a sentence a person can act on."""
534
+
535
+ def __init__(self, code, message):
536
+ super().__init__(message)
537
+ self.code = code
538
+ self.message = message
539
+
540
+
541
+ def _note_list(notes):
542
+ """The notes as a sorted list, capped where `_clean_imported` caps them."""
543
+ return sorted(notes)[:sheets._MAX_UNSUPPORTED]
544
+
545
+
546
+ #: β›” THE ONLY TWO STYLE KEYS A CELL WITH NO VALUE CAN SHOW. It is a shorter list than
547
+ #: `sheet/types.ts::stylePaints` on purpose, and each omission is the same argument: `format`
548
+ #: decides how a VALUE reads and there is no value; `bold`, `italic`, `underline` and `color`
549
+ #: draw GLYPHS and there are none; `align`, `wrap` and `indent` lay out text that is not there.
550
+ #: A fill and a border are the two marks a reader can actually see on an empty cell.
551
+ _PAINT_KEYS = ("fill", "border")
552
+
553
+
554
+ def _painting(style):
555
+ """The part of a style worth keeping on an EMPTY cell, or `{}` when it paints nothing."""
556
+ return {k: v for k, v in (style or {}).items() if k in _PAINT_KEYS}
557
+
558
+
559
+ def _cells_of(ws, cached, notes, counts):
560
+ """One tab's cell map, keyed A1, from the formula pass plus the cached-value pass."""
561
+ cells = {}
562
+ style_only = {}
563
+ counts["blank_styles"] = 0
564
+ max_row = min(int(ws.max_row or 1), sheets.MAX_SHEET_ROWS)
565
+ max_col = min(int(ws.max_column or 1), sheets.MAX_SHEET_COLS)
566
+ if int(ws.max_row or 1) > sheets.MAX_SHEET_ROWS or int(ws.max_column or 1) > \
567
+ sheets.MAX_SHEET_COLS:
568
+ notes.add("this tab is larger than one sheet holds, so its far rows or columns were "
569
+ "not read")
570
+ for row in ws.iter_rows(min_row=1, max_row=max_row, min_col=1, max_col=max_col):
571
+ for cell in row:
572
+ addr = cell.coordinate
573
+ raw = cell.value
574
+ has_style = bool(getattr(cell, "has_style", False))
575
+ if raw is None and not has_style:
576
+ continue
577
+ style = style_of(cell, notes) if has_style else {}
578
+ if raw is None:
579
+ #: β›”β›” A STYLE-ONLY CELL IS STORED ONLY IF ITS STYLE PAINTS, AND THAT ONE TEST IS
580
+ #: WORTH 26 MiB ON THE OWNER'S MODEL (MEASURED: 41.9 MiB before it, 15.6 after).
581
+ #: Excel stamps a number format down whole columns, so 148,327 blank cells
582
+ #: arrived carrying an accounting code and nothing else. A number format on an
583
+ #: empty cell formats NOTHING: there is no value to render, so the cell is
584
+ #: byte for byte invisible, and storing it is pure weight against a 16 MiB cap.
585
+ #: A FILL, A BORDER, AN INK OR A MARK is different: that is paint somebody can
586
+ #: see on an empty cell, and `sheets.CELL_KINDS`' `empty` exists to carry it.
587
+ paint = _painting(style)
588
+ if paint:
589
+ style_only[addr] = {"kind": "empty", "style": paint}
590
+ elif style:
591
+ #: β›” COUNTED AND SAID, NEVER SILENT (standing rule 1's second sentence). This
592
+ #: is a deliberate lossy decision, so it belongs in the DOCUMENT the person
593
+ #: keeps, not only in the notes of whoever wrote the importer.
594
+ counts["blank_styles"] += 1
595
+ continue
596
+ if isinstance(raw, str) and raw.startswith("="):
597
+ counts["formulas"] += 1
598
+ cell_out = {"kind": "formula", "state": "stale",
599
+ "formula": raw[:sheets._MAX_FORMULA]}
600
+ #: The cached reading, for the differential. Dropped before the save; see the
601
+ #: module note for why it is not parked in `source`.
602
+ cell_out["imported_value"] = json_value(cached.get(addr))
603
+ cell_out["value"] = cell_out["imported_value"]
604
+ elif type(raw).__name__ in ("ArrayFormula", "DataTableFormula"):
605
+ counts["formulas"] += 1
606
+ text = str(getattr(raw, "text", "") or "")
607
+ notes.add("an array formula was imported as an ordinary formula")
608
+ cell_out = {"kind": "formula", "state": "stale",
609
+ "formula": (text if text.startswith("=") else "=" + text
610
+ )[:sheets._MAX_FORMULA]}
611
+ cell_out["imported_value"] = json_value(cached.get(addr))
612
+ cell_out["value"] = cell_out["imported_value"]
613
+ else:
614
+ value = json_value(raw)
615
+ cell_out = {"kind": "literal", "state": "typed", "value": value}
616
+ #: ⚠ ONLY A STRING KEEPS A `text`, and a number deliberately does not. `text` is
617
+ #: what a person TYPED; for a number the value is the content and a second copy
618
+ #: of it is about 0.5 MiB of duplication on the owner's model.
619
+ if isinstance(value, str):
620
+ cell_out["text"] = value[:sheets._MAX_TEXT]
621
+ if style:
622
+ cell_out["style"] = style
623
+ cells[addr] = cell_out
624
+ counts["cells"] += len(cells)
625
+ #: β›” THE CONTENT CELLS WIN THE CAP. A tab at the ceiling drops its decoration rather than
626
+ #: refusing the import, and says so, because a style-only cell is paint and a value is data.
627
+ room = sheets._MAX_CELLS_PER_SHEET - len(cells)
628
+ if room < len(style_only):
629
+ notes.add("this tab holds more cells than one sheet does, so " +
630
+ str(len(style_only) - max(0, room)) + " cells that carried only colour were "
631
+ "left out")
632
+ for addr, blank in list(style_only.items())[:max(0, room)]:
633
+ cells[addr] = blank
634
+ if counts["blank_styles"]:
635
+ notes.add("on " + str(counts["blank_styles"]) + " cells that hold no value, a number "
636
+ "format or a text style was not kept, because it shapes a value that is not "
637
+ "there")
638
+ return cells
639
+
640
+
641
+ def _validations_of(ws, cells, notes):
642
+ """C2's in-cell lists, applied to the cells a `dataValidation` covers."""
643
+ try:
644
+ found = list(ws.data_validations.dataValidation)
645
+ except Exception: # noqa: BLE001
646
+ return
647
+ for dv in found:
648
+ if str(getattr(dv, "type", "") or "") != "list":
649
+ notes.add("a " + str(getattr(dv, "type", "") or "cell") + " validation rule was not "
650
+ "imported, because a cell carries a list of choices here")
651
+ continue
652
+ formula = str(getattr(dv, "formula1", "") or "").strip()
653
+ if not (formula.startswith('"') and formula.endswith('"')):
654
+ notes.add("a dropdown that reads its choices from a range of cells was not imported")
655
+ continue
656
+ entries = [e.strip() for e in formula[1:-1].split(",") if e.strip()]
657
+ if not entries:
658
+ continue
659
+ addrs, cut = _spread(dv.sqref)
660
+ if cut:
661
+ notes.add("a dropdown covered more cells than one import carries, so it was applied "
662
+ "to the first " + str(_MAX_SPREAD) + " of them")
663
+ for addr in addrs:
664
+ cell = cells.get(addr)
665
+ if cell is None:
666
+ cell = {"kind": "empty"}
667
+ cells[addr] = cell
668
+ cell["validation"] = {"list": entries[:sheets._MAX_VALIDATION_ENTRIES]}
669
+
670
+
671
+ def _dxf_style(dxf, notes):
672
+ """What a conditional format's differential style repaints, as C2's rule style."""
673
+ out = {}
674
+ if dxf is None:
675
+ return out
676
+ font = getattr(dxf, "font", None)
677
+ if font is not None:
678
+ if font.b:
679
+ out["bold"] = True
680
+ token = quantize(argb_of(font.color))
681
+ if token and token != DEFAULT_INK:
682
+ out["color"] = token
683
+ fill = getattr(dxf, "fill", None)
684
+ if fill is not None:
685
+ #: ⚠ A DIFFERENTIAL FILL CARRIES ITS COLOUR ON `bgColor`, not on `fgColor`, which is the
686
+ #: opposite of an ordinary cell fill. Reading only `fgColor` here yields a rule that
687
+ #: paints nothing, with nothing red anywhere.
688
+ token = quantize(argb_of(getattr(fill, "bgColor", None))) \
689
+ or quantize(argb_of(getattr(fill, "fgColor", None)))
690
+ if token and token != DEFAULT_FILL:
691
+ out["fill"] = token
692
+ if not out:
693
+ notes.add("a conditional format rule had no colour this model could carry")
694
+ return out
695
+
696
+
697
+ def _rules_of(ws, notes):
698
+ """C2's `cellIs` conditional rules for one tab, one rule per range it paints."""
699
+ out = []
700
+ try:
701
+ blocks = list(ws.conditional_formatting)
702
+ except Exception: # noqa: BLE001
703
+ return out
704
+ for block in blocks:
705
+ for rule in list(getattr(block, "rules", []) or []):
706
+ kind = str(getattr(rule, "type", "") or "")
707
+ if kind != "cellIs":
708
+ notes.add("a " + (kind or "conditional") + " conditional format rule was not "
709
+ "imported, because a rule compares a cell to a value here")
710
+ continue
711
+ op = _RULE_OPS.get(str(getattr(rule, "operator", "") or ""))
712
+ if not op:
713
+ notes.add("the " + str(getattr(rule, "operator", "") or "unnamed") + " condition "
714
+ "has no equivalent here, so that rule was not imported")
715
+ continue
716
+ operands = []
717
+ for raw in list(getattr(rule, "formula", []) or [])[:2]:
718
+ text = str(raw).strip().strip('"')
719
+ try:
720
+ operands.append(float(text))
721
+ except ValueError:
722
+ operands.append(text)
723
+ style = _dxf_style(getattr(rule, "dxf", None), notes)
724
+ for part in str(getattr(block, "sqref", "") or "").split():
725
+ rect = sheets._clean_range(part.replace("$", "").upper())
726
+ if rect is None:
727
+ continue
728
+ row = {"range": rect, "op": op, "style": style}
729
+ if operands:
730
+ row["value"] = operands[0]
731
+ if len(operands) > 1:
732
+ row["value2"] = operands[1]
733
+ out.append(row)
734
+ if len(out) >= sheets._MAX_RULES:
735
+ notes.add("this tab holds more conditional format rules than one sheet "
736
+ "carries, so the rest were not imported")
737
+ return out
738
+ return out
739
+
740
+
741
+ def _charts_of(ws, tab_name, notes):
742
+ """C2's charts for one tab, with the rectangle their series READ (R15)."""
743
+ out = []
744
+ for chart in list(getattr(ws, "_charts", []) or []):
745
+ kind = _CHART_KINDS.get(type(chart).__name__)
746
+ if not kind:
747
+ notes.add("a " + type(chart).__name__ + " chart has no equivalent here, so it was "
748
+ "not imported")
749
+ continue
750
+ rect = None
751
+ for series in list(getattr(chart, "series", []) or []):
752
+ refs = []
753
+ for holder in (getattr(series, "val", None), getattr(series, "cat", None)):
754
+ for attr in ("numRef", "strRef", "multiLvlStrRef"):
755
+ node = getattr(holder, attr, None) if holder is not None else None
756
+ if node is not None and getattr(node, "f", None):
757
+ refs.append(str(node.f))
758
+ for ref in refs:
759
+ named = sheet_of_ref(ref)
760
+ if named and named != tab_name:
761
+ #: β›” A SERIES THAT READS ANOTHER TAB CANNOT BE DRAWN AS A RECTANGLE ON THIS
762
+ #: ONE. Folding it in would give the chart a range that points at this tab's
763
+ #: cells, which is a picture of the wrong numbers.
764
+ notes.add("a chart series that reads another tab was not imported")
765
+ continue
766
+ piece = rect_of(ref)
767
+ if piece is None:
768
+ continue
769
+ rect = piece if rect is None else {
770
+ "col0": min(rect["col0"], piece["col0"]),
771
+ "row0": min(rect["row0"], piece["row0"]),
772
+ "col1": max(rect["col1"], piece["col1"]),
773
+ "row1": max(rect["row1"], piece["row1"])}
774
+ if rect is None:
775
+ notes.add("a chart whose series range could not be read was not imported")
776
+ continue
777
+ out.append({"range": rect, "kind": kind})
778
+ notes.add("a chart keeps its data range but not its title, colours or placement")
779
+ return out
780
+
781
+
782
+ def _geometry_of(ws, notes):
783
+ """`(cols, rows, colWidths, freeze, hiddenRows, hiddenCols)` for one tab.
784
+
785
+ β›”β›” HIDDEN LINES ARE STORED ONE-BASED, THE WAY A PERSON READS THEM: row 1 is `1` and column A
786
+ is `1`. Nothing in `sheet/types.ts` pinned a basis when this was written (`_clean_hidden`
787
+ admits any non negative whole number and says so), so this is the convention the importer
788
+ sets, and it is the one the address vocabulary already uses. ⚠ A CHART RECTANGLE IS STILL
789
+ ZERO-BASED, because `SheetChartSpec` says so; the two are different quantities and the
790
+ difference is stated here rather than discovered.
791
+ """
792
+ cols = max(sheets.MIN_SHEET_COLS, min(sheets.MAX_SHEET_COLS, int(ws.max_column or 1)))
793
+ rows = max(sheets.MIN_SHEET_ROWS, min(sheets.MAX_SHEET_ROWS, int(ws.max_row or 1)))
794
+ widths, hidden_cols = {}, []
795
+ for letter, dim in (ws.column_dimensions or {}).items():
796
+ first, last = col_index(letter), col_index(letter)
797
+ if getattr(dim, "min", None) and getattr(dim, "max", None):
798
+ first, last = int(dim.min) - 1, int(dim.max) - 1
799
+ if first < 0 or last - first > sheets.MAX_SHEET_COLS:
800
+ continue
801
+ px = width_px(getattr(dim, "width", None))
802
+ for index in range(first, last + 1):
803
+ if index >= sheets.MAX_SHEET_COLS:
804
+ break
805
+ if px:
806
+ widths[_addr(index, 0).rstrip("0123456789")] = px
807
+ if getattr(dim, "hidden", False):
808
+ hidden_cols.append(index + 1)
809
+ hidden_rows = []
810
+ for number, dim in (ws.row_dimensions or {}).items():
811
+ if getattr(dim, "hidden", False) and isinstance(number, int) and number > 0:
812
+ hidden_rows.append(number)
813
+ if getattr(dim, "customHeight", False):
814
+ notes.add("a row height was not imported, because a row is one height here")
815
+ freeze = freeze_of(getattr(ws, "freeze_panes", "") or "")
816
+ if getattr(ws, "merged_cells", None) and list(ws.merged_cells.ranges):
817
+ notes.add("a merged cell was imported as its top left cell alone")
818
+ return cols, rows, widths, freeze, sorted(set(hidden_rows)), sorted(set(hidden_cols))
819
+
820
+
821
+ def import_workbook(path, *, source="", progress=None):
822
+ """Read an .xlsx at `path` and return `{"workbook", "report"}`. Pure: no store, no session.
823
+
824
+ `workbook` is `{"name", "sheets": [...]}` in the C1/C2 shape `sheets.put_workbook` accepts,
825
+ with every formula cell carrying `imported_value` for the caller's differential.
826
+ `report` is C4's `{cells, formulas, matched, mismatched, unsupported}` with the differential
827
+ legs left at zero, because only the caller can recompute a formula.
828
+
829
+ ⚠ `progress(state, fraction)` IS CALLED FROM WHATEVER THREAD RUNS THIS. It must not raise and
830
+ must not block; the job's registry entry is the only thing it touches.
831
+ """
832
+ import openpyxl
833
+
834
+ def _say(state, fraction):
835
+ if progress:
836
+ try:
837
+ progress(state, fraction)
838
+ except Exception: # noqa: BLE001
839
+ pass
840
+
841
+ _say("reading", 0.02)
842
+ try:
843
+ formulas = openpyxl.load_workbook(path, data_only=False, read_only=False,
844
+ keep_links=False)
845
+ except Exception as exc: # noqa: BLE001
846
+ raise ImportRefusal("import_unreadable",
847
+ "That file could not be read as a workbook. Save it again as .xlsx "
848
+ "and try once more.") from exc
849
+ _say("reading", 0.25)
850
+ try:
851
+ values = openpyxl.load_workbook(path, data_only=True, read_only=True, keep_links=False)
852
+ except Exception as exc: # noqa: BLE001
853
+ raise ImportRefusal("import_unreadable",
854
+ "That file could not be read as a workbook. Save it again as .xlsx "
855
+ "and try once more.") from exc
856
+
857
+ names = list(formulas.sheetnames)[:sheets._MAX_SHEETS]
858
+ if len(formulas.sheetnames) > sheets._MAX_SHEETS:
859
+ skipped = len(formulas.sheetnames) - sheets._MAX_SHEETS
860
+ names_note = str(skipped) + " tabs past the first " + str(sheets._MAX_SHEETS) + \
861
+ " were not imported"
862
+ else:
863
+ names_note = ""
864
+
865
+ counts = {"cells": 0, "formulas": 0}
866
+ book_notes = set()
867
+ if names_note:
868
+ book_notes.add(names_note)
869
+ stamp = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
870
+ tabs = []
871
+ total = max(1, len(names))
872
+ for index, name in enumerate(names):
873
+ ws = formulas[name]
874
+ notes = set()
875
+ if str(getattr(ws, "sheet_state", "visible")) != "visible":
876
+ #: β›” A HIDDEN TAB HAS NO HOME IN `_clean_sheet`, which builds a fresh dict from the
877
+ #: keys it names, so a `hidden` key would be dropped on the first save with nothing
878
+ #: red anywhere. It is SHOWN and SAID rather than silently lost.
879
+ notes.add("this tab was hidden in the original file and is shown here")
880
+ _say("cells", 0.3 + 0.4 * (index / total))
881
+ cached = {}
882
+ try:
883
+ source_ws = values[name]
884
+ for row in source_ws.iter_rows():
885
+ for cell in row:
886
+ if cell.value is not None:
887
+ cached[cell.coordinate] = cell.value
888
+ except Exception: # noqa: BLE001
889
+ notes.add("this tab's stored answers could not be read, so its formulas start unfilled")
890
+ cells = _cells_of(ws, cached, notes, counts)
891
+ _say("formats", 0.7 + 0.25 * (index / total))
892
+ _validations_of(ws, cells, notes)
893
+ cols, rows, widths, freeze, hidden_rows, hidden_cols = _geometry_of(ws, notes)
894
+ tab = {"id": "", "name": name[:sheets._MAX_NAME], "cols": cols, "rows": rows,
895
+ "cells": cells}
896
+ if widths:
897
+ tab["colWidths"] = widths
898
+ if freeze:
899
+ tab["freeze"] = freeze
900
+ rules = _rules_of(ws, notes)
901
+ if rules:
902
+ tab["rules"] = rules
903
+ if hidden_rows:
904
+ tab["hiddenRows"] = hidden_rows
905
+ if hidden_cols:
906
+ tab["hiddenCols"] = hidden_cols
907
+ charts = _charts_of(ws, name, notes)
908
+ if charts:
909
+ tab["charts"] = charts
910
+ tab["imported"] = {"at": stamp, "source": source[:sheets._MAX_NAME],
911
+ "unsupported": _note_list(notes)}
912
+ book_notes.update(notes)
913
+ tabs.append(tab)
914
+
915
+ try:
916
+ values.close()
917
+ except Exception: # noqa: BLE001
918
+ pass
919
+ #: ⭐ THE FONT NOTE IS WORKBOOK-WIDE AND UNCONDITIONAL, because the answer is the same on
920
+ #: every file: the app is one typeface, so no imported font survives and the reader is told
921
+ #: once rather than per tab.
922
+ book_notes.add("every font was replaced by the app's own, which is the one typeface it uses")
923
+
924
+ name = str(source or "").rsplit(".", 1)[0] or "Imported workbook"
925
+ return {
926
+ "workbook": {"name": name[:sheets._MAX_NAME], "sheets": tabs},
927
+ "report": {"cells": counts["cells"], "formulas": counts["formulas"],
928
+ "matched": 0, "mismatched": [], "unsupported": _note_list(book_notes)},
929
+ }
930
+
931
+
932
+ def take_imported_values(book):
933
+ """Pull every `imported_value` off the document and return `{(tab, addr): cached}`.
934
+
935
+ β›”β›” IT REMOVES THE KEY AS IT READS IT, AND THAT IS THE POINT. `clean_cell` would drop the key
936
+ on save anyway, so leaving it behind would not corrupt anything; it would simply mean the
937
+ document held in memory during the job does not match the one that comes back out of the
938
+ store, and the differential would then be run against a copy nobody can reproduce.
939
+ """
940
+ out = {}
941
+ for tab in (book or {}).get("sheets") or ():
942
+ tab_name = str(tab.get("name") or "")
943
+ for addr, cell in (tab.get("cells") or {}).items():
944
+ if isinstance(cell, dict) and "imported_value" in cell:
945
+ out[(tab_name, addr)] = cell.pop("imported_value")
946
+ return out
947
+
948
+
949
+ def differential(book, cached, *, limit=MAX_MISMATCHED):
950
+ """`{matched, mismatched, compared}` for a RECOMPUTED workbook against its cached readings.
951
+
952
+ β›”β›” THE DENOMINATOR IS THE CELLS THAT CARRIED A USABLE CACHED VALUE, NOT EVERY FORMULA, and
953
+ the difference is 117 cells on the owner's model. A formula Excel never cached has nothing to
954
+ be right or wrong against, so counting it as a mismatch would report a failure of ours where
955
+ the file simply held no answer, and counting it as a match would be worse.
956
+ """
957
+ matched, mismatched, compared = 0, [], 0
958
+ for tab in (book or {}).get("sheets") or ():
959
+ tab_name = str(tab.get("name") or "")
960
+ for addr, cell in (tab.get("cells") or {}).items():
961
+ if not isinstance(cell, dict) or cell.get("kind") != "formula":
962
+ continue
963
+ key = (tab_name, addr)
964
+ if key not in cached:
965
+ continue
966
+ want = cached[key]
967
+ if want is None:
968
+ continue
969
+ compared += 1
970
+ got = cell.get("value")
971
+ if values_match(got, want):
972
+ matched += 1
973
+ elif len(mismatched) < limit:
974
+ mismatched.append({"addr": addr, "tab": tab_name,
975
+ "kind": mismatch_kind(got, want)})
976
+ else:
977
+ mismatched.append(None)
978
+ shown = [m for m in mismatched if m is not None]
979
+ return {"matched": matched, "mismatched": shown, "compared": compared,
980
+ "mismatched_total": len(mismatched)}
platform/core/sheets.py CHANGED
@@ -7,22 +7,29 @@ WHAT GOES HERE:
7
  document, its `rev`, and the CELL VOCABULARY that every later Sheet ticket consumes. It resolves
8
  nothing: no aggregate, no formula, no permission decision.
9
 
10
- ⭐ **THE VOCABULARY IS FROZEN HERE AND `verify_api.py` PROVES THE CLIENT AGREES.** `CELL_KINDS` and
11
  `CELL_STATES` are the whole of it, name for name, and `web/src/sheet/types.ts` carries the same two
12
- lists. A parity check compares them so the two halves cannot drift; adding a name on one side only
13
- is what that check exists to catch.
 
 
 
 
 
 
 
 
14
 
15
  β›” **THERE IS NO `chart` KIND, AND ADDING ONE IS A CONTRACT CHANGE, NOT A CONVENIENCE.** W49-T08
16
  stores a chart as a sibling `charts:[{range, anchor, kind}]` array on the SHEET, precisely so a
17
  chart never has to pretend to be a cell. Only the ROOT may amend C1.
18
 
19
- β›”β›” **AND `charts` DOES NOT SURVIVE A SAVE TODAY (found by W50-T20, booked, NOT fixed here).**
20
- `_clean_sheet` builds a FRESH dict from the keys it names, so every unnamed key on a tab is
21
- dropped by the ordinary PUT path: a chart created by W49-T08 is gone on the next reload. A2's four
22
- geometry keys are named below precisely because of that rule. Fixing `charts` means writing a
23
- `_clean_charts` allow-list of its own (id, range corners, kind) and shifting a chart's range on a
24
- structural insert, which is W49-T08's surface rather than this ticket's; it is booked with a
25
- testable exit condition instead of half done here.
26
 
27
  ⭐ **WHY A PER-WORKBOOK DOCUMENT NEEDS AN INDEX.** C1 names the document key, which makes a
28
  workbook cheap to read and cheap to write without touching its neighbours. It also means nothing
@@ -54,26 +61,80 @@ WORKBOOK_KEY_PREFIX = "sheet_workbook_"
54
  #: The companion pointer list. See the module note for why a per-document key needs one.
55
  INDEX_KEY = "sheet_workbooks"
56
 
57
- #: β›” THE FROZEN VOCABULARY (contract C1). `verify_api.py` asserts `web/src/sheet/types.ts` carries
58
- #: exactly these, name for name.
59
- CELL_KINDS = ("literal", "formula", "bound")
 
 
 
 
 
60
  CELL_STATES = ("fresh", "stale", "typed", "refused")
61
 
62
  #: A literal is ALWAYS this state (R19). Stated once, here, so no caller has to remember it.
 
 
 
63
  LITERAL_STATE = "typed"
64
 
65
- #: β›” A1 (wave 50, W50-T19). The NUMBER FORMATS a cell may carry. `web/src/sheet/types.ts` holds
66
- #: the same list and `verify_api.py` compares the two, exactly as it does for kinds and states.
67
- CELL_FORMAT_KINDS = ("general", "number", "currency", "percent", "date")
 
 
 
 
 
 
 
 
 
68
 
69
  #: The three horizontal alignments. Mirrored in `types.ts::CELL_ALIGNS`.
70
  CELL_ALIGNS = ("left", "center", "right")
71
 
72
- #: The style keys A1 names. Anything else is DROPPED, in silence and on purpose; see
 
 
 
 
73
  #: `_clean_style` for why that is not the same decision as an unknown `format.kind`.
74
  _STYLE_MARKS = ("bold", "italic", "underline")
75
  _BORDER_SIDES = ("top", "right", "bottom", "left")
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  #: A colour is a `--lp-*` TOKEN NAME, not a hue. Hex is allowed so a future palette door is not
78
  #: locked out, but nothing free form reaches a canvas `fillStyle` from a stored document.
79
  _COLOUR = re.compile(r"^[A-Za-z0-9#_-]{1,40}$")
@@ -110,16 +171,40 @@ _MAX_TEXT = 4000
110
  _MAX_FORMULA = 4000
111
  _MAX_DISPLAY = 400
112
  _MAX_SHEETS = 50
113
- _MAX_CELLS_PER_SHEET = 20000
 
 
 
 
 
 
 
 
 
114
 
115
  #: A client may not park an unbounded blob in the tenant store. A BYTE CAP is not interpretation:
116
  #: it never looks at a key, only at the serialized length. Mirrors `chart_system.MAX_CONFIG_BYTES`.
117
- MAX_WORKBOOK_BYTES = 4 * 1024 * 1024
 
 
 
 
 
 
 
 
 
 
118
 
119
  #: A stored address is plain A1 with no `$`. Anchoring is a property of a FORMULA's text, not of
120
  #: the cell it lands in, so a `$` here would be a second way to say the same thing.
121
  _ADDR = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
122
 
 
 
 
 
 
123
  _ID_CLEAN = re.compile(r"[^a-z0-9_-]+")
124
 
125
 
@@ -136,6 +221,26 @@ class SheetRefusal(Exception):
136
  self.message = message
137
 
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  def _now():
140
  return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
141
 
@@ -184,6 +289,23 @@ def _persist(st, key, mutate, seed=None):
184
  return result.get("value")
185
 
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  def _json_safe(payload, what):
188
  """Strictly JSON-serializable and under the byte cap, or a named refusal.
189
 
@@ -195,13 +317,49 @@ def _json_safe(payload, what):
195
  except (TypeError, ValueError):
196
  raise SheetRefusal("workbook_not_serializable",
197
  "That " + what + " holds a value the store cannot save.")
198
- if len(blob.encode("utf-8")) > MAX_WORKBOOK_BYTES:
199
- raise SheetRefusal("workbook_too_large",
200
- "That workbook is larger than the tenant store accepts.")
 
 
 
 
201
  return payload
202
 
203
 
204
- # ── the cell STYLE (A1, wave 50, W50-T19) ────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
  def _clean_format(raw):
207
  """The number format, or None. An unknown `kind` is REFUSED, never dropped.
@@ -230,6 +388,9 @@ def _clean_format(raw):
230
  if kind == "general":
231
  return None
232
 
 
 
 
233
  out = {"kind": kind}
234
  decimals = raw.get("decimals")
235
  if isinstance(decimals, bool):
@@ -274,6 +435,27 @@ def _clean_style(raw):
274
  if align in CELL_ALIGNS:
275
  out["align"] = align
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  fmt = _clean_format(raw.get("format"))
278
  if fmt:
279
  out["format"] = fmt
@@ -289,6 +471,33 @@ def _clean_style(raw):
289
 
290
  # ── the cell ─────────────────────────────────────────────────────────────────────────────────
291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  def clean_cell(raw, addr=""):
293
  """Normalize ONE cell, or raise `SheetRefusal` with a named code.
294
 
@@ -309,17 +518,30 @@ def clean_cell(raw, addr=""):
309
  "cell_kind_unknown",
310
  "A cell kind must be one of " + ", ".join(CELL_KINDS) + ".")
311
 
312
- state = _text(raw.get("state"), 40) or ("typed" if kind == "literal" else "stale")
313
  if state not in CELL_STATES:
314
  raise SheetRefusal(
315
  "cell_state_unknown",
316
  "A cell state must be one of " + ", ".join(CELL_STATES) + ".")
317
 
318
- if kind == "literal":
319
  state = LITERAL_STATE
320
 
321
  cell = {"kind": kind, "state": state}
322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  if raw.get("text") is not None:
324
  cell["text"] = _text(raw.get("text"), _MAX_TEXT)
325
  if raw.get("formula") is not None:
@@ -344,6 +566,11 @@ def clean_cell(raw, addr=""):
344
  if raw.get("refreshed_at") is not None:
345
  cell["refreshed_at"] = _text(raw.get("refreshed_at"), 120)
346
 
 
 
 
 
 
347
  #: A1: the style slot. It is normalized last because `_clean_format` can REFUSE, and a
348
  #: refusal that fires after every other key has been read names the whole cell it came from.
349
  style = _clean_style(raw.get("style"))
@@ -359,8 +586,7 @@ def _clean_cells(raw, sheet_name=""):
359
  if not isinstance(raw, dict):
360
  raise SheetRefusal("cells_not_an_object", "A sheet's cells must be an object.")
361
  if len(raw) > _MAX_CELLS_PER_SHEET:
362
- raise SheetRefusal("sheet_too_many_cells",
363
- "That sheet holds more cells than one sheet accepts.")
364
  out = {}
365
  for addr, cell in raw.items():
366
  key = _text(addr, 12).upper()
@@ -439,13 +665,193 @@ def _clean_freeze(raw, cols, rows):
439
  return out
440
 
441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442
  def _clean_sheet(raw, index=0):
443
- """ONE tab: identity, cells, and A2's geometry.
444
 
445
  β›” EVERY KEY THIS FUNCTION DOES NOT NAME IS DROPPED, and that is worth knowing before adding
446
  one: the return below is a fresh dict, not an amended copy of `raw`. A2's four geometry keys
447
- are named here for exactly that reason. See the module's own note on `charts`, which is
448
- dropped today by the same rule.
449
  """
450
  if not isinstance(raw, dict):
451
  raise SheetRefusal("sheet_not_an_object", "A sheet must be an object.")
@@ -467,6 +873,22 @@ def _clean_sheet(raw, index=0):
467
  freeze = _clean_freeze(raw.get("freeze"), cols, rows)
468
  if freeze:
469
  sheet["freeze"] = freeze
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  return sheet
471
 
472
 
@@ -574,6 +996,177 @@ def put_workbook(st, workbook_id, raw, expect_rev=None):
574
  return saved
575
 
576
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577
  def delete_workbook(st, workbook_id):
578
  """Empty the document and drop its index row. Returns True when something was there."""
579
  wid = _slug_id(workbook_id)
@@ -585,6 +1178,16 @@ def delete_workbook(st, workbook_id):
585
 
586
  _persist(st, workbook_key(wid), _apply)
587
  _index_drop(st, wid)
 
 
 
 
 
 
 
 
 
 
588
  return bool(existed.get("yes"))
589
 
590
 
@@ -617,6 +1220,75 @@ def _index_upsert(st, book):
617
  _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
618
 
619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  def _index_drop(st, workbook_id):
621
  """Drop a workbook's pointer row AND everything the rail filed against it.
622
 
@@ -635,6 +1307,8 @@ def _index_drop(st, workbook_id):
635
  starred = state.get("starred")
636
  if isinstance(starred, list):
637
  state["starred"] = [w for w in starred if w != workbook_id]
 
 
638
  return state, rows
639
 
640
  _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
@@ -665,6 +1339,163 @@ def iter_workbooks(st):
665
  continue
666
 
667
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668
  # ── the rail: folders, placements and stars (wave 50, W50-T17) ───────────────────────────────
669
  #
670
  # ⭐⭐ THE MODEL IS COPIED FROM `core/table_store.py::validate_folder_tree` / `::save_folders`,
@@ -901,13 +1732,35 @@ def _clean_starred(raw, known_ids, repairs):
901
  return out
902
 
903
 
904
- def read_index(st):
905
- """The whole rail document: `{workbooks, folders, itemFolders, starred}`.
 
 
 
 
 
 
 
 
 
906
 
907
  β›” A STORED TREE CANNOT BRICK THE RAIL. The wall runs on WRITE, so a cycle should be
908
  unreachable here; a document written before that wall existed, or edited by hand, would
909
  otherwise make every GET raise and leave the module unopenable with no way back. So a stored
910
  tree that refuses is FLATTENED to roots and revalidated, which cannot refuse a second time.
 
 
 
 
 
 
 
 
 
 
 
 
 
911
  """
912
  doc = _read(st, INDEX_KEY)
913
  rows = [dict(r) for r in (doc.get("workbooks") or [])
@@ -920,15 +1773,28 @@ def read_index(st):
920
  flat = [dict(f, parent=None) for f in (doc.get("folders") or [])
921
  if isinstance(f, dict) and f.get("id")]
922
  folders, placed, _repairs = validate_folder_tree(flat, placements)
923
- return {
924
- "workbooks": rows,
925
  "folders": folders,
926
  "itemFolders": {k: v for k, v in placed.items() if k in ids},
927
  "starred": _clean_starred(doc.get("starred"), ids, []),
 
928
  }
 
 
 
 
 
 
 
 
 
 
 
 
929
 
930
 
931
- def save_folders(st, folders, item_folders, starred=None):
932
  """Replace the folder, placement and star strata WHOLESALE, once the tree is proven legal.
933
 
934
  Wholesale rather than per folder because the three are interdependent: a placement is only
@@ -939,13 +1805,31 @@ def save_folders(st, folders, item_folders, starred=None):
939
  callback would abandon a half touched transaction; raising first means a refused tree leaves
940
  the store exactly as it was. The callback below only PRUNES, and cannot raise.
941
 
942
- RETURNS `{workbooks, folders, itemFolders, starred, repairs}`. RAISES `SheetFolderRefusal`
943
- on a cycle or an over deep chain, having written nothing.
 
 
 
 
 
 
 
 
 
 
 
 
944
  """
945
  tree, placed, repairs = validate_folder_tree(folders, item_folders)
946
  out = {}
947
 
948
  def _apply(state):
 
 
 
 
 
 
949
  rows = [r for r in (state.get("workbooks") or [])
950
  if isinstance(r, dict) and r.get("id")]
951
  ids = {r["id"] for r in rows}
@@ -959,16 +1843,23 @@ def save_folders(st, folders, item_folders, starred=None):
959
  state["itemFolders"] = kept
960
  if starred is not None:
961
  state["starred"] = _clean_starred(starred, ids, repairs)
 
 
962
  out["value"] = {
963
  "workbooks": [dict(r) for r in rows],
964
  "folders": [dict(f) for f in tree],
965
  "itemFolders": dict(kept),
966
  "starred": list(state.get("starred") or []),
 
967
  }
968
  return state, None
969
 
970
  _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
971
  result = dict(out.get("value") or {"workbooks": [], "folders": [], "itemFolders": {},
972
- "starred": []})
 
 
 
 
973
  result["repairs"] = repairs
974
  return result
 
7
  document, its `rev`, and the CELL VOCABULARY that every later Sheet ticket consumes. It resolves
8
  nothing: no aggregate, no formula, no permission decision.
9
 
10
+ ⭐ **THE VOCABULARY IS FROZEN HERE AND TWO GATES PROVE THE CLIENT AGREES.** `CELL_KINDS` and
11
  `CELL_STATES` are the whole of it, name for name, and `web/src/sheet/types.ts` carries the same two
12
+ lists. `verify_api.py` compares them and `verify_sheet.py` section 1 diffs the WHOLE wave-51
13
+ vocabulary both ways, so the two halves cannot drift; adding a name on one side only is what those
14
+ checks exist to catch.
15
+
16
+ ⭐⭐ **WAVE 51 AMENDS THE VOCABULARY (contract C2, W51-T21), AND EVERY AMENDMENT IS PAIRED.**
17
+ `CELL_KINDS` gains `empty` (a cell that carries a style and nothing else), `CELL_FORMAT_KINDS`
18
+ gains `code` (a custom number format, which is what an imported accounting format arrives as), a
19
+ style gains `valign` / `wrap` / `indent` / `size` (R8's Alignment group), a cell gains
20
+ `validation`, and a tab gains `rules` / `hiddenRows` / `hiddenCols` / `imported`. Each of those
21
+ names must appear in `sheet/types.ts` too, or `verify_sheet.py` goes red by family.
22
 
23
  β›” **THERE IS NO `chart` KIND, AND ADDING ONE IS A CONTRACT CHANGE, NOT A CONVENIENCE.** W49-T08
24
  stores a chart as a sibling `charts:[{range, anchor, kind}]` array on the SHEET, precisely so a
25
  chart never has to pretend to be a cell. Only the ROOT may amend C1.
26
 
27
+ ⭐⭐ **`charts` NOW SURVIVES A SAVE (D-640, fixed by W51-T21; it did NOT before).** `_clean_sheet`
28
+ builds a FRESH dict from the keys it names, so every unnamed key on a tab was dropped by the
29
+ ordinary PUT path and a chart created by W49-T08 was gone on the next reload. `_clean_charts`
30
+ below is the allow-list that keeps it: id, the four range corners, and the kind. ⚠ WHAT IS STILL
31
+ NOT DONE is shifting a chart's range on a structural insert; that is W49-T08's surface and stays
32
+ booked. A2's four geometry keys are named below for the same fresh-dict reason.
 
33
 
34
  ⭐ **WHY A PER-WORKBOOK DOCUMENT NEEDS AN INDEX.** C1 names the document key, which makes a
35
  workbook cheap to read and cheap to write without touching its neighbours. It also means nothing
 
61
  #: The companion pointer list. See the module note for why a per-document key needs one.
62
  INDEX_KEY = "sheet_workbooks"
63
 
64
+ #: β›” THE FROZEN VOCABULARY (contract C1, amended by C2). `verify_api.py` and `verify_sheet.py`
65
+ #: assert `web/src/sheet/types.ts` carries exactly these, name for name.
66
+ #:
67
+ #: ⭐ `empty` IS C2's STYLE ONLY CELL, and it is a KIND rather than a flag because every other way
68
+ #: of saying it lies: a `literal` with no text claims something was typed, and a cell absent from
69
+ #: the map cannot carry a fill. A person who paints an empty cell yellow has made a real edit and
70
+ #: the document has to be able to hold it.
71
+ CELL_KINDS = ("literal", "formula", "bound", "empty")
72
  CELL_STATES = ("fresh", "stale", "typed", "refused")
73
 
74
  #: A literal is ALWAYS this state (R19). Stated once, here, so no caller has to remember it.
75
+ #: ⚠ AN `empty` CELL TAKES THE SAME STATE, deliberately: it holds no binding, so `stale` would say
76
+ #: a refresh is owed for a value that does not exist, and a reader counting stale cells would
77
+ #: count decoration. Nothing computed it, nothing can refresh it, so it reads as hand made.
78
  LITERAL_STATE = "typed"
79
 
80
+ #: The kinds that hold no value of their own, and therefore take `LITERAL_STATE`.
81
+ _TYPED_KINDS = ("literal", "empty")
82
+
83
+ #: β›” A1 (wave 50, W50-T19), extended by C2 (wave 51, W51-T21). The NUMBER FORMATS a cell may
84
+ #: carry. `web/src/sheet/types.ts` holds the same list and both gates compare the two, exactly as
85
+ #: they do for kinds and states.
86
+ #:
87
+ #: ⭐�� `code` IS THE ONE C4 CANNOT SHIP WITHOUT. 49% of the owner's real treasury model uses an
88
+ #: accounting format, which arrives from openpyxl as a format CODE and not as one of the four
89
+ #: named kinds. Without this name every imported cell's format hits `cell_format_kind_unknown` and
90
+ #: the whole import REFUSES, so the trap is not a missing decoration, it is a save that fails.
91
+ CELL_FORMAT_KINDS = ("general", "number", "currency", "percent", "date", "code")
92
 
93
  #: The three horizontal alignments. Mirrored in `types.ts::CELL_ALIGNS`.
94
  CELL_ALIGNS = ("left", "center", "right")
95
 
96
+ #: C2 / R8's vertical alignments and the four font steps. Mirrored in `types.ts`.
97
+ CELL_VALIGNS = ("top", "middle", "bottom")
98
+ CELL_SIZES = ("s", "m", "l", "xl")
99
+
100
+ #: The style keys A1 and C2 name. Anything else is DROPPED, in silence and on purpose; see
101
  #: `_clean_style` for why that is not the same decision as an unknown `format.kind`.
102
  _STYLE_MARKS = ("bold", "italic", "underline")
103
  _BORDER_SIDES = ("top", "right", "bottom", "left")
104
 
105
+ #: R8's indent, in steps rather than pixels: a stored pixel count would be a layout decision that
106
+ #: outlives every layout change, exactly as a stored hex outlives a palette.
107
+ _MAX_INDENT = 8
108
+
109
+ #: C2's custom format code. ⚠ THE CAPS ARE PART OF THE VOCABULARY, not a guess: a format code is
110
+ #: interpreted by the client's formatter, so an unbounded one is an unbounded parse, and Excel's
111
+ #: own grammar holds at most four sections (positive; negative; zero; text).
112
+ _MAX_FORMAT_CODE = 64
113
+ _MAX_FORMAT_SECTIONS = 4
114
+
115
+ #: C2's in-cell list validation. The cap is on ENTRIES; the whole document still meets the byte cap.
116
+ _MAX_VALIDATION_ENTRIES = 200
117
+ _MAX_VALIDATION_ENTRY = 200
118
+
119
+ #: β›” C2's TEN conditional format operators, spelled once. An op outside this list is REFUSED by
120
+ #: name for `_clean_format`'s reason: a rule with an operator nothing can evaluate never fires, so
121
+ #: dropping it would leave a person looking at a rule they believe is painting their sheet.
122
+ SHEET_RULE_OPS = ("gt", "lt", "gte", "lte", "eq", "neq", "between", "contains", "empty",
123
+ "notEmpty")
124
+
125
+ #: The style keys a conditional format rule may repaint. A rule is a PAINT, never a format: it
126
+ #: cannot change how a number reads, so it carries no `format`.
127
+ _RULE_STYLE_MARKS = ("bold",)
128
+ _RULE_STYLE_COLOURS = ("fill", "color")
129
+
130
+ #: The chart kinds W49-T08 draws. Mirrored in `types.ts::SheetChartSpec`.
131
+ SHEET_CHART_KINDS = ("bar", "line", "area", "donut")
132
+
133
+ _MAX_RULES = 100
134
+ _MAX_HIDDEN = 5000
135
+ _MAX_CHARTS = 50
136
+ _MAX_UNSUPPORTED = 200
137
+
138
  #: A colour is a `--lp-*` TOKEN NAME, not a hue. Hex is allowed so a future palette door is not
139
  #: locked out, but nothing free form reaches a canvas `fillStyle` from a stored document.
140
  _COLOUR = re.compile(r"^[A-Za-z0-9#_-]{1,40}$")
 
171
  _MAX_FORMULA = 4000
172
  _MAX_DISPLAY = 400
173
  _MAX_SHEETS = 50
174
+
175
+ #: ⭐⭐ R4 / AMENDMENT A1 (wave 51, W51-T22). THE CAPS FIT THE MODEL, and the model is the owner's
176
+ #: real treasury workbook: 58,083 populated cells with its largest tab at 42,148, which the wave-49
177
+ #: figure of 20,000 refused outright. 100,000 leaves that tab room to grow and still sits far below
178
+ #: the byte cap, which is the one that actually binds.
179
+ #:
180
+ #: β›” DO NOT CROSS THIS WITH `MAX_SHEET_ROWS = 100000` ABOVE. They are the same digits and
181
+ #: different quantities: that one is how many ROWS a tab may address, this one is how many of its
182
+ #: cells may hold something. A tab at the row ceiling with one cell filled is one cell.
183
+ _MAX_CELLS_PER_SHEET = 100_000
184
 
185
  #: A client may not park an unbounded blob in the tenant store. A BYTE CAP is not interpretation:
186
  #: it never looks at a key, only at the serialized length. Mirrors `chart_system.MAX_CONFIG_BYTES`.
187
+ #:
188
+ #: ⭐⭐ 16 MiB IS THE BINDING CAP (A1), and it is the reason the grill's 500,000-cell figure is
189
+ #: unreachable: the recalc prototype measured 89 B for a BARE cell, so 16 MiB is about 150,000
190
+ #: styled cells and the byte cap runs out first on any real workbook. The wave-49 figure of 4 MiB
191
+ #: refused the owner's 4.92 MB model on every save, so the module could not hold its own use case.
192
+ #:
193
+ #: ⚠ IT IS NOT ONLY THE DOCUMENT CAP. `clean_cell` runs `_json_safe` over a cell's `value`,
194
+ #: `binding`, `source` and `refusal` too, so raising this raises the per-value ceiling with it.
195
+ #: That is harmless (a single value at the cap would fail the document check one line later) but
196
+ #: it is not obvious from the name.
197
+ MAX_WORKBOOK_BYTES = 16 * 1024 * 1024
198
 
199
  #: A stored address is plain A1 with no `$`. Anchoring is a property of a FORMULA's text, not of
200
  #: the cell it lands in, so a `$` here would be a second way to say the same thing.
201
  _ADDR = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
202
 
203
+ #: A stored RANGE, which is what a conditional format rule paints over. `A1` alone is the one cell
204
+ #: range and is normalized to `A1:A1`, so every stored rule reads the same way and no consumer has
205
+ #: to carry two shapes.
206
+ _RANGE = re.compile(r"^([A-Z]{1,3}[1-9][0-9]{0,6}):([A-Z]{1,3}[1-9][0-9]{0,6})$")
207
+
208
  _ID_CLEAN = re.compile(r"[^a-z0-9_-]+")
209
 
210
 
 
221
  self.message = message
222
 
223
 
224
+ class SheetStaleRefusal(SheetRefusal):
225
+ """C3's stale-revision refusal, carrying the revision that IS live.
226
+
227
+ ⭐⭐ THE SHAPE IS COPIED, NOT INVENTED. `view_audit.ViewRevisionStale` already carries
228
+ `rev_current` and `main.py::_view_revision_stale` already answers it as
229
+ `{"error": {"code", "message", "rev_current"}}`, so a Sheet 409 arrives in the shape the app
230
+ already has rather than a second one.
231
+
232
+ β›” IT IS A DIFFERENT CODE FROM `put_workbook`'s `workbook_revision_stale` AND THAT IS
233
+ DELIBERATE. The PUT door replaces a whole workbook and its client reloads the workbook; the
234
+ PATCH door replaces a range inside ONE TAB and its client reloads that tab. The two recoveries
235
+ are different, so the two refusals are named differently and the existing PUT branch in the
236
+ client keeps working untouched.
237
+ """
238
+
239
+ def __init__(self, code, message, rev_current=0):
240
+ super().__init__(code, message)
241
+ self.rev_current = int(rev_current or 0)
242
+
243
+
244
  def _now():
245
  return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
246
 
 
289
  return result.get("value")
290
 
291
 
292
+ def _mb(byte_count):
293
+ """A byte count as MB with one decimal, because a person cannot read 16777216.
294
+
295
+ ⚠ IT IS DIGITS ON PURPOSE (R16, and W51-T22's done-when). "larger than the store accepts" told
296
+ the reader nothing they could act on: they could not tell whether they were 2% over or ten
297
+ times over, and therefore could not tell whether deleting a tab would help.
298
+ """
299
+ return "%.1f MB" % (float(byte_count) / (1024.0 * 1024.0))
300
+
301
+
302
+ def _too_many_cells_message(count):
303
+ """The sentence a tab over `_MAX_CELLS_PER_SHEET` wears. Names the COUNT and the CAP."""
304
+ return ("That sheet holds " + str(int(count)) + " cells and one sheet holds at most "
305
+ + str(_MAX_CELLS_PER_SHEET) + ", so it cannot be saved. Delete some cells or move "
306
+ "them onto another tab.")
307
+
308
+
309
  def _json_safe(payload, what):
310
  """Strictly JSON-serializable and under the byte cap, or a named refusal.
311
 
 
317
  except (TypeError, ValueError):
318
  raise SheetRefusal("workbook_not_serializable",
319
  "That " + what + " holds a value the store cannot save.")
320
+ size = len(blob.encode("utf-8"))
321
+ if size > MAX_WORKBOOK_BYTES:
322
+ raise SheetRefusal(
323
+ "workbook_too_large",
324
+ "That " + what + " is " + _mb(size) + " and the tenant store holds at most "
325
+ + _mb(MAX_WORKBOOK_BYTES) + ", so it cannot be saved. Delete some cells or move "
326
+ "them into a second workbook.")
327
  return payload
328
 
329
 
330
+ # ── the cell STYLE (A1, wave 50, W50-T19; C2, wave 51, W51-T21) ──────────────────────────────
331
+
332
+ def _clean_format_code(raw):
333
+ """C2's CUSTOM number format code, or a named refusal. Never dropped, never truncated.
334
+
335
+ β›”β›” A TRUNCATED FORMAT CODE IS A WRONG NUMBER ON A SCREEN, which is why every rule here
336
+ refuses rather than repairs. `#,##0.00;(#,##0.00)` cut at its semicolon stops showing negatives
337
+ in brackets and nobody is told; a code with one quote left open swallows the rest of itself and
338
+ formats as literal text. Both read as a plausible number, and that is the one class of defect
339
+ a gate downstream cannot see.
340
+
341
+ The three rules are Excel's own, restated: at most 64 characters, at most four sections
342
+ (positive; negative; zero; text) split on `;`, and every double quote closed.
343
+ """
344
+ code = str(raw if raw is not None else "").strip()
345
+ if not code:
346
+ raise SheetRefusal("cell_format_code_missing",
347
+ "A custom number format needs a format code.")
348
+ if len(code) > _MAX_FORMAT_CODE:
349
+ raise SheetRefusal(
350
+ "cell_format_code_too_long",
351
+ "A custom number format code holds at most " + str(_MAX_FORMAT_CODE)
352
+ + " characters, so this one cannot be saved.")
353
+ if len(code.split(";")) > _MAX_FORMAT_SECTIONS:
354
+ raise SheetRefusal(
355
+ "cell_format_code_too_many_sections",
356
+ "A custom number format holds at most " + str(_MAX_FORMAT_SECTIONS)
357
+ + " sections separated by a semicolon.")
358
+ if code.count('"') % 2:
359
+ raise SheetRefusal("cell_format_code_unbalanced",
360
+ "A custom number format code has a quote that was never closed.")
361
+ return code
362
+
363
 
364
  def _clean_format(raw):
365
  """The number format, or None. An unknown `kind` is REFUSED, never dropped.
 
388
  if kind == "general":
389
  return None
390
 
391
+ if kind == "code":
392
+ return {"kind": "code", "code": _clean_format_code(raw.get("code"))}
393
+
394
  out = {"kind": kind}
395
  decimals = raw.get("decimals")
396
  if isinstance(decimals, bool):
 
435
  if align in CELL_ALIGNS:
436
  out["align"] = align
437
 
438
+ #: C2 / R8's Alignment group. ⚠ EACH ONE STORES ITS DEFAULT AS AN ABSENCE, for the falsey mark
439
+ #: reason above: `wrap: false`, `indent: 0` and the middle font step are what every cell
440
+ #: already is, so writing them would make a cell that was indented and un indented compare
441
+ #: unequal to the cell it started as.
442
+ valign = _text(raw.get("valign"), 12)
443
+ if valign in CELL_VALIGNS:
444
+ out["valign"] = valign
445
+
446
+ if raw.get("wrap") is True:
447
+ out["wrap"] = True
448
+
449
+ indent = raw.get("indent")
450
+ if not isinstance(indent, bool) and isinstance(indent, (int, float)):
451
+ steps = max(0, min(_MAX_INDENT, int(indent)))
452
+ if steps:
453
+ out["indent"] = steps
454
+
455
+ size = _text(raw.get("size"), 4)
456
+ if size in CELL_SIZES and size != "m":
457
+ out["size"] = size
458
+
459
  fmt = _clean_format(raw.get("format"))
460
  if fmt:
461
  out["format"] = fmt
 
471
 
472
  # ── the cell ─────────────────────────────────────────────────────────────────────────────────
473
 
474
+ def _clean_validation(raw):
475
+ """C2's in-cell list validation `{list: [...]}`, or None when nothing survives.
476
+
477
+ ⚠ THE LIST IS CLAMPED, NOT REFUSED, and that is the opposite decision from a format code one
478
+ screen up. A validation list is an AID: 200 entries or 500, the cell still shows the value it
479
+ holds and every entry beyond the cap is one nobody could have found in a dropdown anyway. A
480
+ format code changes what a number READS AS, which is why that one refuses.
481
+ """
482
+ if raw is None:
483
+ return None
484
+ if not isinstance(raw, dict):
485
+ raise SheetRefusal("cell_validation_invalid", "A cell validation must be an object.")
486
+ items = raw.get("list")
487
+ if not isinstance(items, list):
488
+ return None
489
+ out, seen = [], set()
490
+ for item in items[:_MAX_VALIDATION_ENTRIES]:
491
+ if isinstance(item, (dict, list)):
492
+ continue
493
+ value = _text(item, _MAX_VALIDATION_ENTRY)
494
+ if not value or value in seen:
495
+ continue
496
+ seen.add(value)
497
+ out.append(value)
498
+ return {"list": out} if out else None
499
+
500
+
501
  def clean_cell(raw, addr=""):
502
  """Normalize ONE cell, or raise `SheetRefusal` with a named code.
503
 
 
518
  "cell_kind_unknown",
519
  "A cell kind must be one of " + ", ".join(CELL_KINDS) + ".")
520
 
521
+ state = _text(raw.get("state"), 40) or (LITERAL_STATE if kind in _TYPED_KINDS else "stale")
522
  if state not in CELL_STATES:
523
  raise SheetRefusal(
524
  "cell_state_unknown",
525
  "A cell state must be one of " + ", ".join(CELL_STATES) + ".")
526
 
527
+ if kind in _TYPED_KINDS:
528
  state = LITERAL_STATE
529
 
530
  cell = {"kind": kind, "state": state}
531
 
532
+ #: ⭐ C2's STYLE ONLY CELL. `empty` says the cell holds no content, so nothing that would BE
533
+ #: content is carried out of here, whatever arrived. It is DROPPED rather than refused on
534
+ #: purpose: a client that clears a cell and leaves `text: ""` behind has done nothing wrong,
535
+ #: and refusing would 400 a whole workbook save over a blank string.
536
+ if kind == "empty":
537
+ style = _clean_style(raw.get("style"))
538
+ if style:
539
+ cell["style"] = style
540
+ validation = _clean_validation(raw.get("validation"))
541
+ if validation:
542
+ cell["validation"] = validation
543
+ return cell
544
+
545
  if raw.get("text") is not None:
546
  cell["text"] = _text(raw.get("text"), _MAX_TEXT)
547
  if raw.get("formula") is not None:
 
566
  if raw.get("refreshed_at") is not None:
567
  cell["refreshed_at"] = _text(raw.get("refreshed_at"), 120)
568
 
569
+ #: C2: the in-cell list. Normalized before the style so a refusing style still reports first.
570
+ validation = _clean_validation(raw.get("validation"))
571
+ if validation:
572
+ cell["validation"] = validation
573
+
574
  #: A1: the style slot. It is normalized last because `_clean_format` can REFUSE, and a
575
  #: refusal that fires after every other key has been read names the whole cell it came from.
576
  style = _clean_style(raw.get("style"))
 
586
  if not isinstance(raw, dict):
587
  raise SheetRefusal("cells_not_an_object", "A sheet's cells must be an object.")
588
  if len(raw) > _MAX_CELLS_PER_SHEET:
589
+ raise SheetRefusal("sheet_too_many_cells", _too_many_cells_message(len(raw)))
 
590
  out = {}
591
  for addr, cell in raw.items():
592
  key = _text(addr, 12).upper()
 
665
  return out
666
 
667
 
668
+ # ── the tab's C2 STRATA: rules, hidden lines, charts and the import record ───────────────────
669
+ #
670
+ # β›”β›” NOTHING IN THIS TREE PINNED THE SHAPE OF A RULE'S `range` WHEN THIS WAS WRITTEN
671
+ # (2026-09-03, checked across `sheet/types.ts`, the wave-51 board and every importer). The only
672
+ # `range` that exists is the CHART's zero-based `{col0,row0,col1,row1}` rectangle, and an importer
673
+ # naturally produces the A1 string `B2:D40` instead. So this accepts BOTH and stores ONE: the
674
+ # chart's rectangle, because it is the shape already on the wire and a stored document with two
675
+ # spellings of the same rectangle is a document every later reader has to branch on.
676
+ #
677
+ # ⚠ A MALFORMED RANGE IS DROPPED, NOT REFUSED, and the split from the unknown `op` beside it is
678
+ # deliberate. C2 NAMES the ten ops, so an eleventh is a request this server understands well
679
+ # enough to know it cannot serve. C2 names no range GRAMMAR at all, so refusing one would be
680
+ # refusing a whole workbook save on a guess about a peer that is not built yet.
681
+
682
+
683
+ def _col_index(letters):
684
+ """`A` -> 0, `Z` -> 25, `AA` -> 26. The zero-based column the chart rectangle counts in."""
685
+ n = 0
686
+ for ch in letters:
687
+ n = n * 26 + (ord(ch) - 64)
688
+ return n - 1
689
+
690
+
691
+ def _clean_range(raw):
692
+ """A rule's rectangle, or None. Accepts `"B2:D40"`, `"B2"` and `{col0,row0,col1,row1}`."""
693
+ if isinstance(raw, str):
694
+ text = raw.strip().upper().replace("$", "")
695
+ if ":" not in text:
696
+ text = text + ":" + text
697
+ found = _RANGE.match(text)
698
+ if not found:
699
+ return None
700
+ corners = []
701
+ for part in (found.group(1), found.group(2)):
702
+ letters = "".join(c for c in part if c.isalpha())
703
+ digits = "".join(c for c in part if c.isdigit())
704
+ corners.append((_col_index(letters), int(digits) - 1))
705
+ (c0, r0), (c1, r1) = corners
706
+ return {"col0": min(c0, c1), "row0": min(r0, r1),
707
+ "col1": max(c0, c1), "row1": max(r0, r1)}
708
+ if isinstance(raw, dict):
709
+ out = {}
710
+ for key in ("col0", "row0", "col1", "row1"):
711
+ value = raw.get(key)
712
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
713
+ return None
714
+ out[key] = max(0, int(value))
715
+ if out["col1"] < out["col0"] or out["row1"] < out["row0"]:
716
+ return None
717
+ return out
718
+ return None
719
+
720
+
721
+ def _clean_rule_style(raw):
722
+ """What a rule REPAINTS: a fill, an ink and bold. Never a format (see `SHEET_RULE_OPS`)."""
723
+ if not isinstance(raw, dict):
724
+ return {}
725
+ out = {}
726
+ for key in _RULE_STYLE_COLOURS:
727
+ token = _text(raw.get(key), 40)
728
+ if token and _COLOUR.match(token):
729
+ out[key] = token
730
+ for mark in _RULE_STYLE_MARKS:
731
+ if raw.get(mark) is True:
732
+ out[mark] = True
733
+ return out
734
+
735
+
736
+ def _clean_rules(raw):
737
+ """C2's conditional format rules for one tab, at most `_MAX_RULES` of them.
738
+
739
+ β›” AN OP OUTSIDE `SHEET_RULE_OPS` IS REFUSED BY NAME, for `_clean_format`'s reason: a rule
740
+ whose operator nothing can evaluate never fires, so dropping it would leave a person looking
741
+ at a sheet they believe is painted by a rule that is not there.
742
+
743
+ ⚠ THE COUNT IS CLAMPED rather than refused: the rules past the cap are ones nobody could see
744
+ the effect of, and refusing would make a sheet that can never be saved again.
745
+ """
746
+ if raw is None:
747
+ return []
748
+ if not isinstance(raw, list):
749
+ raise SheetRefusal("sheet_rules_not_a_list", "A sheet's rules must be a list.")
750
+ out = []
751
+ for row in raw[:_MAX_RULES]:
752
+ if not isinstance(row, dict):
753
+ continue
754
+ op = _text(row.get("op"), 20)
755
+ if op not in SHEET_RULE_OPS:
756
+ raise SheetRefusal(
757
+ "sheet_rule_op_unknown",
758
+ "A sheet rule condition must be one of " + ", ".join(SHEET_RULE_OPS) + ".")
759
+ rect = _clean_range(row.get("range"))
760
+ if rect is None:
761
+ continue
762
+ rule = {"id": _text(row.get("id"), _MAX_ID) or uuid.uuid4().hex[:12],
763
+ "range": rect, "op": op, "style": _clean_rule_style(row.get("style"))}
764
+ #: ⚠ `empty` and `notEmpty` take NO operand, and carrying one would store a rule whose
765
+ #: text says it compares against something it can never read.
766
+ if op not in ("empty", "notEmpty"):
767
+ for key in ("value", "value2"):
768
+ if row.get(key) is not None:
769
+ rule[key] = _json_safe(row.get(key), "sheet rule value")
770
+ out.append(rule)
771
+ return out
772
+
773
+
774
+ def _clean_hidden(raw, what):
775
+ """`hiddenRows` / `hiddenCols`: whole numbers, deduped and sorted, at most `_MAX_HIDDEN`.
776
+
777
+ ⚠ THE BASIS IS THE CLIENT'S AND THIS FUNCTION DOES NOT SECOND GUESS IT. Nothing in the tree
778
+ pinned whether a hidden line is counted from 0 or from 1 when this was written, and a server
779
+ that rejected `0` would silently refuse to hide column A under a zero-based client. So it
780
+ admits every non negative whole number and stores it unchanged; the two halves agree on the
781
+ basis, or `verify_sheet.py` section 1 says so.
782
+ """
783
+ if raw is None:
784
+ return []
785
+ if not isinstance(raw, list):
786
+ raise SheetRefusal("sheet_hidden_not_a_list",
787
+ "A sheet's hidden " + what + " must be a list.")
788
+ seen = set()
789
+ for item in raw[:_MAX_HIDDEN]:
790
+ if isinstance(item, bool) or not isinstance(item, (int, float)):
791
+ continue
792
+ line = int(item)
793
+ if line >= 0:
794
+ seen.add(line)
795
+ return sorted(seen)
796
+
797
+
798
+ def _clean_charts(raw):
799
+ """D-640: the allow-list that lets a chart SURVIVE a save.
800
+
801
+ β›”β›” WITHOUT THIS FUNCTION A CHART IS GONE ON THE NEXT RELOAD, and nothing goes red: the sheet
802
+ saves, the document is valid, and the picture the person made is simply not in it.
803
+ `_clean_sheet` returns a fresh dict, so a tab key that is not named here is dropped.
804
+ """
805
+ if raw is None:
806
+ return []
807
+ if not isinstance(raw, list):
808
+ raise SheetRefusal("sheet_charts_not_a_list", "A sheet's charts must be a list.")
809
+ out = []
810
+ for row in raw[:_MAX_CHARTS]:
811
+ if not isinstance(row, dict):
812
+ continue
813
+ kind = _text(row.get("kind"), 20)
814
+ rect = _clean_range(row.get("range"))
815
+ if kind not in SHEET_CHART_KINDS or rect is None:
816
+ continue
817
+ out.append({"id": _text(row.get("id"), _MAX_ID) or uuid.uuid4().hex[:12],
818
+ "range": rect, "kind": kind})
819
+ return out
820
+
821
+
822
+ def _clean_imported(raw):
823
+ """C4's import record: when, from what, and WHAT DID NOT SURVIVE.
824
+
825
+ ⭐⭐ `unsupported` IS THE HALF THAT MATTERS AND IT IS STANDING RULE 1's SECOND SENTENCE. An
826
+ importer that quietly drops a pivot, a macro or a chart type it cannot draw hands back a
827
+ workbook that looks complete and is not. The list travels with the document so the app can
828
+ say what was left behind, months after the import.
829
+ """
830
+ if raw is None:
831
+ return None
832
+ if not isinstance(raw, dict):
833
+ raise SheetRefusal("sheet_imported_invalid", "A sheet's import record must be an object.")
834
+ out = {"at": _text(raw.get("at"), 120), "source": _text(raw.get("source"), _MAX_NAME)}
835
+ items = raw.get("unsupported")
836
+ notes = []
837
+ if isinstance(items, list):
838
+ for item in items[:_MAX_UNSUPPORTED]:
839
+ if isinstance(item, (dict, list)):
840
+ continue
841
+ note = _text(item, 200)
842
+ if note:
843
+ notes.append(note)
844
+ out["unsupported"] = notes
845
+ return out if (out["at"] or out["source"] or notes) else None
846
+
847
+
848
  def _clean_sheet(raw, index=0):
849
+ """ONE tab: identity, cells, A2's geometry and C2's strata.
850
 
851
  β›” EVERY KEY THIS FUNCTION DOES NOT NAME IS DROPPED, and that is worth knowing before adding
852
  one: the return below is a fresh dict, not an amended copy of `raw`. A2's four geometry keys
853
+ and C2's five strata are named here for exactly that reason, and `charts` is named because it
854
+ was the one this rule silently ate until W51-T21 (D-640).
855
  """
856
  if not isinstance(raw, dict):
857
  raise SheetRefusal("sheet_not_an_object", "A sheet must be an object.")
 
873
  freeze = _clean_freeze(raw.get("freeze"), cols, rows)
874
  if freeze:
875
  sheet["freeze"] = freeze
876
+ #: C2's five strata. Each is written only when it holds something, for `_clean_style`'s
877
+ #: reason: a tab with no rules and a tab with `rules: []` read identically, so one of them is
878
+ #: what gets stored and a reload compares equal to the thing it saved.
879
+ rules = _clean_rules(raw.get("rules"))
880
+ if rules:
881
+ sheet["rules"] = rules
882
+ for key, what in (("hiddenRows", "rows"), ("hiddenCols", "columns")):
883
+ hidden = _clean_hidden(raw.get(key), what)
884
+ if hidden:
885
+ sheet[key] = hidden
886
+ charts = _clean_charts(raw.get("charts"))
887
+ if charts:
888
+ sheet["charts"] = charts
889
+ imported = _clean_imported(raw.get("imported"))
890
+ if imported:
891
+ sheet["imported"] = imported
892
  return sheet
893
 
894
 
 
996
  return saved
997
 
998
 
999
+ # ── C3: ONE TAB AT A TIME, and the range PATCH (wave 51, W51-T22) ────────────────────────────
1000
+ #
1001
+ # ⭐⭐ WHY A SECOND WRITE DOOR EXISTS AT ALL. `put_workbook` sends the WHOLE document on every
1002
+ # commit, and A1 raised the ceiling to 16 MiB, so a person typing into the owner's treasury model
1003
+ # would upload 5 MB per keystroke commit and the tab they are not looking at would ride along with
1004
+ # it. C3's answer is a door whose payload is the range that changed: the client sends the dirty
1005
+ # addresses and the `rev` it read, and structure (adding a tab, resizing, freezing) keeps going
1006
+ # through PUT because that is a whole-document change and honestly is one.
1007
+
1008
+
1009
+ def _tab_index(tabs, tab_ref):
1010
+ """Where `tab_ref` lives in `tabs`, matched on `id` first and then on `name`, or None.
1011
+
1012
+ ⚠ `id` FIRST, AND THE ORDER IS LOAD BEARING. Two tabs may legally share a name (nothing in
1013
+ `_clean_sheet` dedupes one) and no two may share an id, so resolving a name first would let a
1014
+ rename decide which tab a save lands in. The name fallback exists because a tab is addressed by
1015
+ the thing a person can see when a client has not read the document yet.
1016
+ """
1017
+ key = str(tab_ref if tab_ref is not None else "").strip()
1018
+ if not key:
1019
+ return None
1020
+ for i, tab in enumerate(tabs):
1021
+ if isinstance(tab, dict) and str(tab.get("id") or "") == key:
1022
+ return i
1023
+ for i, tab in enumerate(tabs):
1024
+ if isinstance(tab, dict) and str(tab.get("name") or "") == key:
1025
+ return i
1026
+ folded = key.casefold()
1027
+ for i, tab in enumerate(tabs):
1028
+ if isinstance(tab, dict) and str(tab.get("name") or "").casefold() == folded:
1029
+ return i
1030
+ return None
1031
+
1032
+
1033
+ def find_tab(book, tab_ref):
1034
+ """ONE tab of a workbook, or a named refusal. C3's `GET /sheets/{id}/tabs/{tab}`."""
1035
+ tabs = list((book or {}).get("sheets") or [])
1036
+ at = _tab_index(tabs, tab_ref)
1037
+ if at is None:
1038
+ raise SheetRefusal("tab_missing",
1039
+ "Tab " + (str(tab_ref) or "(unnamed)") + " is not in this workbook.")
1040
+ return tabs[at]
1041
+
1042
+
1043
+ def workbook_meta(book):
1044
+ """The workbook WITHOUT any cells, for C3's `?tabs=meta`.
1045
+
1046
+ ⭐ THE IDENTITIES STAY AND ONLY `cells` GOES. A tab rail has to name its tabs, and the geometry,
1047
+ the freeze, the widths and the strata are what the grid needs to draw an empty tab before its
1048
+ contents arrive; dropping them would make the meta read useless and the client would go
1049
+ straight back to fetching everything.
1050
+
1051
+ ⭐ `cellCount` REPLACES the map it removes. Without it a client that opens one tab has no way
1052
+ to say how close the workbook is to `_MAX_CELLS_PER_SHEET` short of loading every tab, which is
1053
+ the exact fetch this door exists to avoid.
1054
+ """
1055
+ meta = {k: v for k, v in (book or {}).items() if k != "sheets"}
1056
+ tabs = []
1057
+ for tab in (book or {}).get("sheets") or ():
1058
+ if not isinstance(tab, dict):
1059
+ continue
1060
+ thin = {k: v for k, v in tab.items() if k != "cells"}
1061
+ thin["cellCount"] = len(tab.get("cells") or {})
1062
+ tabs.append(thin)
1063
+ meta["sheets"] = tabs
1064
+ return meta
1065
+
1066
+
1067
+ def patch_cells(st, workbook_id, tab_ref, raw_cells, expect_rev=None):
1068
+ """Merge a RANGE of cells into ONE tab. Returns `{rev, tab, refused}` (contract C3).
1069
+
1070
+ ⭐⭐ ONE BAD CELL DOES NOT THROW THE COMMIT AWAY. Every address is cleaned on its own and a
1071
+ cell that refuses lands in `refused` as `{addr, code, sentence}` while the rest of the patch
1072
+ still commits. That is the opposite of `put_workbook`, and deliberately: a PUT is one document
1073
+ the caller assembled, so a bad cell in it means the caller's document is wrong; a PATCH is a
1074
+ range a person just typed into, and refusing forty good edits over one bad one would lose work
1075
+ somebody did.
1076
+
1077
+ ⭐ `{"A1": null}` DELETES A1. An empty cell is not the same thing as an absent one after C2
1078
+ (`kind: "empty"` carries a style), so a client needs a way to say "this address holds nothing
1079
+ at all" that is distinguishable from "this address is painted yellow".
1080
+
1081
+ β›”β›” THE CAPS ARE MEASURED ON THE MERGED DOCUMENT, NEVER ON THE PATCH, AND THAT IS THE WHOLE
1082
+ TRAP IN THIS FUNCTION. `_json_safe` weighs the WHOLE workbook on every write, so a 200 byte
1083
+ patch onto a workbook already at 15.9 MB is a write that takes it over the cap; measuring the
1084
+ patch would report 200 bytes, store the document, and leave the tenant with a workbook the
1085
+ store cannot hold. Same for the cell count: the merged TAB is what has to fit.
1086
+
1087
+ ⚠ THE MEASUREMENT RUNS INSIDE `_persist`'s CALLBACK, which is the opposite of `save_folders`'s
1088
+ rule that validation runs before the update. It has to: the merged document is only knowable
1089
+ after the current state has been read under the store's own lock. Nothing is persisted, because
1090
+ the raise happens before the callback returns its next state.
1091
+
1092
+ ⚠ `rev` BUMPS BY EXACTLY ONE ON EVERY ACCEPTED PATCH, including one where every cell refused.
1093
+ A conditional bump would leave the client holding a rev the server never issued, and the very
1094
+ next patch would then answer 409 for a conflict that never happened.
1095
+ """
1096
+ wid = _slug_id(workbook_id)
1097
+ if raw_cells is None:
1098
+ raw_cells = {}
1099
+ if not isinstance(raw_cells, dict):
1100
+ raise SheetRefusal("cells_not_an_object", "A cell patch must be an object.")
1101
+ if len(raw_cells) > _MAX_CELLS_PER_SHEET:
1102
+ raise SheetRefusal("sheet_too_many_cells", _too_many_cells_message(len(raw_cells)))
1103
+
1104
+ #: Cleaned BEFORE the lock: `clean_cell` is pure, and doing it here keeps the store's lock
1105
+ #: held for the merge alone rather than for every cell in the range.
1106
+ #: ⚠ `addr` IS ECHOED AS THE CALLER SENT IT, not as this module would store it. The client's
1107
+ #: dirty set is keyed by what it sent, so a refusal reported under a normalized address would
1108
+ #: be one the sender cannot match back to the cell the person is looking at.
1109
+ merged, deleted, refused = {}, [], []
1110
+ for addr, cell in raw_cells.items():
1111
+ sent = _text(addr, 12)
1112
+ key = sent.upper()
1113
+ if not _ADDR.match(key):
1114
+ refused.append({"addr": sent, "code": "cell_address_invalid",
1115
+ "sentence": "Cell address " + (sent or str(addr))
1116
+ + " is not an A1 address."})
1117
+ continue
1118
+ if cell is None:
1119
+ deleted.append(key)
1120
+ continue
1121
+ try:
1122
+ merged[key] = clean_cell(cell, addr=key)
1123
+ except SheetRefusal as exc:
1124
+ refused.append({"addr": sent, "code": exc.code, "sentence": exc.message})
1125
+
1126
+ saved, out = {}, {}
1127
+
1128
+ def _apply(state):
1129
+ prior = state if state.get("id") else None
1130
+ if prior is None:
1131
+ raise SheetRefusal("workbook_missing", "That workbook no longer exists.")
1132
+ current = int(prior.get("rev") or 0)
1133
+ if expect_rev is not None and current != int(expect_rev):
1134
+ raise SheetStaleRefusal(
1135
+ "sheet_revision_stale",
1136
+ "This sheet changed somewhere else while you had it open, so this save was not "
1137
+ "applied. Reload the tab and try again.",
1138
+ rev_current=current)
1139
+ book = copy.deepcopy(prior)
1140
+ tabs = book.get("sheets") or []
1141
+ at = _tab_index(tabs, tab_ref)
1142
+ if at is None:
1143
+ raise SheetRefusal(
1144
+ "tab_missing",
1145
+ "Tab " + (str(tab_ref) or "(unnamed)") + " is not in this workbook.")
1146
+ tab = tabs[at]
1147
+ cells = dict(tab.get("cells") or {})
1148
+ for key in deleted:
1149
+ cells.pop(key, None)
1150
+ cells.update(merged)
1151
+ if len(cells) > _MAX_CELLS_PER_SHEET:
1152
+ raise SheetRefusal("sheet_too_many_cells", _too_many_cells_message(len(cells)))
1153
+ tab["cells"] = cells
1154
+ book["sheets"] = tabs
1155
+ book["rev"] = current + 1
1156
+ book["updated_at"] = _now()
1157
+ _json_safe(book, "workbook")
1158
+ out["rev"] = book["rev"]
1159
+ out["tab"] = str(tab.get("id") or tab.get("name") or "")
1160
+ out["cells"] = len(cells)
1161
+ saved.update(book)
1162
+ return book, book
1163
+
1164
+ _persist(st, workbook_key(wid), _apply)
1165
+ _index_upsert(st, saved)
1166
+ out["refused"] = refused
1167
+ return out
1168
+
1169
+
1170
  def delete_workbook(st, workbook_id):
1171
  """Empty the document and drop its index row. Returns True when something was there."""
1172
  wid = _slug_id(workbook_id)
 
1178
 
1179
  _persist(st, workbook_key(wid), _apply)
1180
  _index_drop(st, wid)
1181
+ # β›” C5 / W51-T25: THE GRANTS DIE WITH THE OBJECT, and this is `core.shares.drop_objects`'s own
1182
+ # stated contract rather than an extra: "a deleted object's grants must die with it β€”
1183
+ # `shared_with` would otherwise serve ghost ids into every receiver's Shared with me forever,
1184
+ # and the ghost would 404 on open." A share record also keeps an owner HUSK after a full
1185
+ # revoke, so nothing short of dropping the record clears it.
1186
+ try:
1187
+ import core.shares as shares
1188
+ shares.drop_objects([("workbook", wid)], st=st)
1189
+ except Exception:
1190
+ pass
1191
  return bool(existed.get("yes"))
1192
 
1193
 
 
1220
  _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
1221
 
1222
 
1223
+ # ── C5: the grant join, and the rail's own revision (wave 51, W51-T25) ───────────────────────
1224
+ #
1225
+ # ⭐⭐ SHARES ARE JOINED ONTO THE ROW AT READ TIME AND ARE NEVER STORED ON IT, AND THAT IS A
1226
+ # STRUCTURAL DECISION RATHER THAN A STYLISTIC ONE. `_index_upsert`'s `_apply` above drops the
1227
+ # prior row and appends a FRESHLY REBUILT `_index_row(book)` whose seven keys are all read off the
1228
+ # DOCUMENT, and `create_workbook`, `put_workbook` and `patch_cells` all call it. A `shares` key
1229
+ # stored on that row would therefore be DELETED BY THE NEXT PATCH OF ANY CELL, with nothing going
1230
+ # red anywhere: the share door would answer 200, the registry would look right, and the mark would
1231
+ # simply be gone the next time somebody typed in a cell. That is D-640 in a different function and
1232
+ # W51-T21's own durable lesson ("a fresh dict deletes any key nobody names") arriving one layer up.
1233
+ #
1234
+ # `core.shares` is the ONE grant registry for every shareable object (wave 20, owner R10), it
1235
+ # treats `kind` as an opaque bucket key, and it already answers "what am I shared on" across
1236
+ # kinds. So the grants live there, this module reads them, and the failure above is impossible
1237
+ # rather than merely guarded against.
1238
+ #
1239
+ # ⚠ THE COST, STATED RATHER THAN DISCOVERED: `shares.grants(kind, oid)` re-reads the WHOLE grant
1240
+ # bucket per call, so a rail of N workbooks costs N reads of the tenant's registry. `granted_oids`
1241
+ # exists in that module for exactly this reason but answers a different question (which ids carry
1242
+ # ANY grant, with no roles and no owner). A `records(kind)` bulk read belongs there and is booked,
1243
+ # not written here: reaching into another module's bucket from this one is how two readers of one
1244
+ # document come apart.
1245
+
1246
+ #: C5's wire words for a share role, and the registry's. `core.shares.ROLES` is `('view', 'edit')`;
1247
+ #: C5 says `"viewer"` and `"editor"`. β›” THE TRANSLATION HAS EXACTLY ONE HOME AND IT IS
1248
+ #: `routes_sheet.py::wire_role` / `::store_role` β€” this module only ever stores and reads the
1249
+ #: registry's words, so a second spelling cannot be introduced here by accident.
1250
+
1251
+
1252
+ def workbook_shares(st, workbook_id):
1253
+ """C5's `shares` list for ONE workbook, computed from `core.shares` and never stored.
1254
+
1255
+ `[{who, role}]` with `role` in the REGISTRY's vocabulary (`view` / `edit`); the route
1256
+ translates to C5's `viewer` / `editor` at the boundary, which is the only place either
1257
+ spelling of that fact exists.
1258
+
1259
+ ⚠ C5 ALSO NAMES AN `at`, AND THERE IS NOTHING TO PUT IN IT. `core.shares._clean_entries`
1260
+ normalises an entry to `{user, role, by?}` and stores no timestamp, so the key is OMITTED
1261
+ rather than synthesised: a grant made last month would otherwise render as "shared just now",
1262
+ which is worse than absent because it looks like an answer. Booked as an amendment finding;
1263
+ the exit is a timestamp member on `_clean_entries`, which is not this ticket's fence.
1264
+ """
1265
+ try:
1266
+ import core.shares as shares
1267
+ rec = shares.grants("workbook", str(workbook_id), st=st)
1268
+ except Exception:
1269
+ return []
1270
+ return [{"who": e["user"], "role": e["role"]} for e in (rec.get("entries") or [])]
1271
+
1272
+
1273
+ def project_shares(st, rows):
1274
+ """Join `shares` onto a list of index rows. Returns NEW rows; the stored ones are untouched.
1275
+
1276
+ ⚠ Called by `read_index`, `save_folders` and `routes_sheet.list_sheets` β€” the three doors a
1277
+ client reads the rail through. `list_workbooks` itself stays a bare pointer list on purpose:
1278
+ `iter_workbooks` walks it to answer W49-T10's dependents question, and paying a grant-registry
1279
+ read per workbook there would put a permission lookup inside a scan that asks no permission
1280
+ question at all.
1281
+ """
1282
+ out = []
1283
+ for row in rows or ():
1284
+ if not isinstance(row, dict) or not row.get("id"):
1285
+ continue
1286
+ joined = dict(row)
1287
+ joined["shares"] = workbook_shares(st, row["id"])
1288
+ out.append(joined)
1289
+ return out
1290
+
1291
+
1292
  def _index_drop(st, workbook_id):
1293
  """Drop a workbook's pointer row AND everything the rail filed against it.
1294
 
 
1307
  starred = state.get("starred")
1308
  if isinstance(starred, list):
1309
  state["starred"] = [w for w in starred if w != workbook_id]
1310
+ # D-639: this write rewrites `itemFolders` and `starred`, so it MOVES the rail's revision.
1311
+ state["rev"] = _index_rev(state) + 1
1312
  return state, rows
1313
 
1314
  _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
 
1339
  continue
1340
 
1341
 
1342
+ # ── R11 / W51-T26: WHAT A PURGED VIEW LEAVES BEHIND ──────────────────────────────────────────
1343
+ #
1344
+ # ⭐⭐ R11, verbatim: *"A view-scoped cell keeps pointing at a TRASHED view for the 30 days (it
1345
+ # still resolves); its filter is copied into the cell's own scope AT PURGE (30-day purge or
1346
+ # 'Delete forever'); restoring the view re-links for free."*
1347
+ #
1348
+ # β›”β›” THE ADOPTION IS ON THE PURGE PATH ONLY, AND THAT IS THE WHOLE RULING. Adopting at TRASH
1349
+ # would make Restore a lie: the cell would already carry a copied filter, so putting the view back
1350
+ # would leave forty cells pointing at a frozen snapshot of what that view USED to say, and every
1351
+ # later edit of the view would stop reaching them. Restore re-links for free precisely because
1352
+ # nothing was copied while the view sat in the trash.
1353
+ #
1354
+ # β›” AND IT IS IDEMPOTENT BY CONSTRUCTION, because `TableStore.trash()` runs the 30-day purge ON
1355
+ # EVERY READ: this function will be called again for the same view id the next time anyone opens
1356
+ # the panel. A cell whose `scope.view_id` is already gone is not this function's subject, so the
1357
+ # second call finds nothing and writes nothing - and an `adoptedFrom` that already names THIS view
1358
+ # is KEPT, so the receipt says when the purge happened rather than when it was last re-checked.
1359
+
1360
+ #: ⚠ MUST AGREE with `aios_grid.LOCKED_VIEW_KIND`. Restated rather than imported for the same
1361
+ #: reason `MAX_FOLDER_DEPTH` below is: this module imports nothing from the grid or the harness,
1362
+ #: and a deferred import inside a hot scan is a cost paid per workbook.
1363
+ LOCKED_VIEW_KIND = "locked"
1364
+
1365
+ #: ⚠ MUST AGREE with `harness/filter_sql.COHORT_FIELD` and `types.ts`'s `COHORT_FIELD`. The
1366
+ #: reserved pseudo-column of a cohort-membership leaf.
1367
+ COHORT_FIELD = "__cohort__"
1368
+
1369
+ #: The cohort op a single-set membership leaf uses. `filter_sql.COHORT_OPS`.
1370
+ COHORT_ANY_OF = "anyOf"
1371
+
1372
+
1373
+ def adopted_scope_filter(view):
1374
+ """The filter tree a binding INHERITS from `view` at purge, as `{conj, nodes}`, or None.
1375
+
1376
+ β›”β›” A LOCKED VIEW ADOPTS ITS MEMBER SET, NEVER ITS FILTER TREE (the three locks, `DESIGN.md`
1377
+ section 4). A locked view IS a curated ROW SET: `aios_grid.locked_view_projection` says the
1378
+ lock is the view's IDENTITY, membership lives in the cohort store and is never copied into the
1379
+ view's config, and the config's `filters` are whatever the user happened to be looking at when
1380
+ the set was made. Adopting those filters would silently replace a hand-picked cohort with a
1381
+ predicate that never defined it, and the number would still look plausible. So the adopted
1382
+ shape is the cohort leaf the engine already speaks: `{colId: "__cohort__", op: "anyOf",
1383
+ value: <the cohort id>}`, which is the view's own id.
1384
+
1385
+ ⚠ THE FILTERS LIVE UNDER `config`, and reading them off the top level is silently EMPTY rather
1386
+ than an error. `(view.get("config") or view)` mirrors `routes_alerts.py:518`, which is the
1387
+ reader that gets this right; `routes_sheet.py::_view_filter` reads the top level and therefore
1388
+ resolves EVERY view-scoped cell with no filter at all today (reported, W51-T26 finding 3).
1389
+
1390
+ ⚠ AN EMPTY TREE IS A REAL ANSWER, NOT A REFUSAL. A view that filters nothing means "every row",
1391
+ and `{conj: "and", nodes: []}` is exactly how `compile_scope` spells that (None -> no
1392
+ predicate). Returning None here would leave the binding pointing at an id that no longer
1393
+ exists, which is the state this whole function exists to prevent.
1394
+ """
1395
+ record = view if isinstance(view, dict) else {}
1396
+ config = record.get("config") if isinstance(record.get("config"), dict) else record
1397
+ vid = str(record.get("id") or "").strip()
1398
+ if str(record.get("kind") or "").strip() == LOCKED_VIEW_KIND:
1399
+ cohort = str(config.get("cohortLock") or vid).strip()
1400
+ if not cohort:
1401
+ return None
1402
+ return {"conj": "and",
1403
+ "nodes": [{"colId": COHORT_FIELD, "op": COHORT_ANY_OF, "value": cohort[:120]}]}
1404
+ tree = config.get("filters")
1405
+ if isinstance(tree, dict):
1406
+ nodes, conj = tree.get("nodes"), tree.get("conj")
1407
+ else:
1408
+ nodes, conj = tree, config.get("filterConj")
1409
+ nodes = [copy.deepcopy(node) for node in nodes if isinstance(node, dict)] \
1410
+ if isinstance(nodes, list) else []
1411
+ return {"conj": "or" if conj == "or" else "and", "nodes": nodes}
1412
+
1413
+
1414
+ def _scope_of(cell):
1415
+ """One cell's binding scope, when it has one and it is an object. Else None."""
1416
+ if not isinstance(cell, dict):
1417
+ return None
1418
+ binding = cell.get("binding")
1419
+ if not isinstance(binding, dict):
1420
+ return None
1421
+ scope = binding.get("scope")
1422
+ return scope if isinstance(scope, dict) else None
1423
+
1424
+
1425
+ def _bound_to_view(book, view_id):
1426
+ """Every `(tab, addr, scope)` in one workbook document whose scope NAMES `view_id`."""
1427
+ vid = str(view_id or "").strip()
1428
+ out = []
1429
+ if not vid or not isinstance(book, dict):
1430
+ return out
1431
+ for tab in book.get("sheets") or ():
1432
+ if not isinstance(tab, dict):
1433
+ continue
1434
+ for addr, cell in (tab.get("cells") or {}).items():
1435
+ scope = _scope_of(cell)
1436
+ if scope is not None and str(scope.get("view_id") or "").strip() == vid:
1437
+ out.append((tab, str(addr), scope))
1438
+ return out
1439
+
1440
+
1441
+ def count_view_bindings(st, view_id):
1442
+ """How many Sheet cells are scoped to `view_id` RIGHT NOW. A pure read.
1443
+
1444
+ β›”β›” THIS IS THE NUMBER IN THE CONFIRM SENTENCE ("3 Sheet cells will keep this view's
1445
+ filter"), and it comes from the SERVER because a client cannot see another person's
1446
+ workbooks. A hardcoded or client-guessed count passes every visual check and lies to the one
1447
+ person who is deciding whether to destroy something.
1448
+
1449
+ ⚠ IT WALKS THE SAME `iter_workbooks` SCAN `adopt_view_filter` WALKS, so the sentence and the
1450
+ act cannot disagree by construction. An unreadable document is SKIPPED by that generator, so
1451
+ this is a floor rather than a guess; there is no second scan to drift.
1452
+ """
1453
+ return sum(len(_bound_to_view(book, view_id)) for book in iter_workbooks(st))
1454
+
1455
+
1456
+ def adopt_view_filter(st, view, at=None):
1457
+ """Copy a purged view's scope into every binding that named it. Returns cells changed.
1458
+
1459
+ β›”β›” CALL IT FROM A PURGE, NEVER FROM A TRASH OR A RESTORE. See the section note above.
1460
+
1461
+ β›” IT RAISES RATHER THAN SWALLOWING A FAILED WORKBOOK WRITE, and the caller must not purge
1462
+ when it does. A trash bucket emptied beside a workbook that never took the filter is a cell
1463
+ pointing at an id that no longer exists anywhere, with nothing to report it. Because the
1464
+ adoption is idempotent, the honest recovery is simply to retry on the next read: the workbooks
1465
+ that DID take it are already done and are not this function's subject any more.
1466
+
1467
+ `at` is injectable so a gate can pin the receipt without patching the clock.
1468
+ """
1469
+ vid = str((view or {}).get("id") or "").strip()
1470
+ if not vid:
1471
+ return 0
1472
+ adopted = adopted_scope_filter(view)
1473
+ if adopted is None:
1474
+ return 0
1475
+ receipt = {"view_id": vid[:120],
1476
+ "name": (str((view or {}).get("name") or "").strip() or vid)[:200],
1477
+ "at": str(at or _now())[:120]}
1478
+ changed = 0
1479
+ for book in iter_workbooks(st):
1480
+ hits = _bound_to_view(book, vid)
1481
+ if not hits:
1482
+ continue
1483
+ for _tab, _addr, scope in hits:
1484
+ scope["filter"] = copy.deepcopy(adopted)
1485
+ scope.pop("view_id", None)
1486
+ # ⚠ `view_name` was carried ONLY so `view_missing` could name the view. The name now
1487
+ # lives in the receipt, where it says something true; leaving it on a filter scope
1488
+ # would be a second copy that `clean_binding` drops on the next save anyway.
1489
+ scope.pop("view_name", None)
1490
+ prior = scope.get("adoptedFrom")
1491
+ if not (isinstance(prior, dict)
1492
+ and str(prior.get("view_id") or "").strip() == vid):
1493
+ scope["adoptedFrom"] = dict(receipt)
1494
+ put_workbook(st, book["id"], book, expect_rev=book.get("rev"))
1495
+ changed += len(hits)
1496
+ return changed
1497
+
1498
+
1499
  # ── the rail: folders, placements and stars (wave 50, W50-T17) ───────────────────────────────
1500
  #
1501
  # ⭐⭐ THE MODEL IS COPIED FROM `core/table_store.py::validate_folder_tree` / `::save_folders`,
 
1732
  return out
1733
 
1734
 
1735
+ def _index_rev(doc):
1736
+ """The rail document's revision, as an int, however junk the stored value is."""
1737
+ try:
1738
+ return int((doc or {}).get("rev") or 0)
1739
+ except (TypeError, ValueError):
1740
+ return 0
1741
+
1742
+
1743
+ def read_index(st, viewer=None):
1744
+ """The whole rail document: `{workbooks, folders, itemFolders, starred, rev}`, plus
1745
+ `sharedWithMe` when a `viewer` is named.
1746
 
1747
  β›” A STORED TREE CANNOT BRICK THE RAIL. The wall runs on WRITE, so a cycle should be
1748
  unreachable here; a document written before that wall existed, or edited by hand, would
1749
  otherwise make every GET raise and leave the module unopenable with no way back. So a stored
1750
  tree that refuses is FLATTENED to roots and revalidated, which cannot refuse a second time.
1751
+
1752
+ ⭐⭐ D-639 β€” `rev` RIDES THE READ, AND THAT IS ONE HALF OF A GUARD THAT NEEDS BOTH.
1753
+ `save_folders` below CHECKS an `expect_rev`, and a client cannot send one it was never given,
1754
+ so a `rev` here without the check there (or the check without this) is a guard nothing can
1755
+ reach ([[a-rev-guard-inert-on-the-events-channel]]). The pair lands together or not at all.
1756
+
1757
+ ⚠ WHICH WRITES MOVE IT IS PART OF THE CONTRACT: `save_folders` and `_index_drop`, which are
1758
+ the two that rewrite the folder, placement and star strata this guard protects.
1759
+ `_index_upsert` deliberately does NOT, because it is called by `create_workbook`,
1760
+ `put_workbook` AND `patch_cells` β€” bumping there would make every cell edit 409 a folder drag
1761
+ that touched nothing the guard is about.
1762
+
1763
+ ⚠ `viewer` IS A USERNAME AND IS OPTIONAL. Absent, this reads exactly as it did before C5.
1764
  """
1765
  doc = _read(st, INDEX_KEY)
1766
  rows = [dict(r) for r in (doc.get("workbooks") or [])
 
1773
  flat = [dict(f, parent=None) for f in (doc.get("folders") or [])
1774
  if isinstance(f, dict) and f.get("id")]
1775
  folders, placed, _repairs = validate_folder_tree(flat, placements)
1776
+ out = {
1777
+ "workbooks": project_shares(st, rows),
1778
  "folders": folders,
1779
  "itemFolders": {k: v for k, v in placed.items() if k in ids},
1780
  "starred": _clean_starred(doc.get("starred"), ids, []),
1781
+ "rev": _index_rev(doc),
1782
  }
1783
+ if viewer:
1784
+ # C5's `sharedWithMe`. ⚠ FREE, and that is the point of using the registry: `shared_with`
1785
+ # already answers "what was granted TO me" across kinds and already EXCLUDES what the
1786
+ # caller owns, so the "Shared with me" partition of the rail needs no second store and no
1787
+ # second definition of what being shared means.
1788
+ try:
1789
+ import core.shares as shares
1790
+ granted = (shares.shared_with(viewer, kind="workbook", st=st) or {}).get("workbook")
1791
+ except Exception:
1792
+ granted = []
1793
+ out["sharedWithMe"] = [w for w in (granted or []) if w in ids]
1794
+ return out
1795
 
1796
 
1797
+ def save_folders(st, folders, item_folders, starred=None, expect_rev=None):
1798
  """Replace the folder, placement and star strata WHOLESALE, once the tree is proven legal.
1799
 
1800
  Wholesale rather than per folder because the three are interdependent: a placement is only
 
1805
  callback would abandon a half touched transaction; raising first means a refused tree leaves
1806
  the store exactly as it was. The callback below only PRUNES, and cannot raise.
1807
 
1808
+ RETURNS `{workbooks, folders, itemFolders, starred, rev, repairs}`. RAISES
1809
+ `SheetFolderRefusal` on a cycle or an over deep chain, having written nothing.
1810
+
1811
+ ⭐⭐ D-639 β€” `expect_rev` IS THE OTHER HALF OF `read_index`'s `rev`, AND IT IS CHECKED INSIDE
1812
+ THE CALLBACK BECAUSE THAT IS THE ONLY PLACE THE STORED REVISION EXISTS. That is a deliberate
1813
+ exception to the paragraph above: the folder TREE is pure and can be validated before the
1814
+ update, but "is this the document you decided against" cannot be asked without reading it
1815
+ under the store's own lock, so this follows `put_workbook` and `patch_cells`, which raise from
1816
+ inside `_apply` for the same reason. `store.update` discards the callback's work when it
1817
+ raises, so a refused save still writes nothing.
1818
+
1819
+ ⚠ `expect_rev=None` OPTS OUT, exactly as `put_workbook`'s does. A client that has never read
1820
+ the rail cannot send a revision, and refusing would make the first folder ever created
1821
+ impossible.
1822
  """
1823
  tree, placed, repairs = validate_folder_tree(folders, item_folders)
1824
  out = {}
1825
 
1826
  def _apply(state):
1827
+ if expect_rev is not None and _index_rev(state) != int(expect_rev):
1828
+ raise SheetStaleRefusal(
1829
+ "index_revision_stale",
1830
+ "The Sheet rail changed somewhere else, so this save was not applied. Reload the "
1831
+ "rail and try again.",
1832
+ rev_current=_index_rev(state))
1833
  rows = [r for r in (state.get("workbooks") or [])
1834
  if isinstance(r, dict) and r.get("id")]
1835
  ids = {r["id"] for r in rows}
 
1843
  state["itemFolders"] = kept
1844
  if starred is not None:
1845
  state["starred"] = _clean_starred(starred, ids, repairs)
1846
+ # D-639: this write IS the one the guard protects, so it moves the revision.
1847
+ state["rev"] = _index_rev(state) + 1
1848
  out["value"] = {
1849
  "workbooks": [dict(r) for r in rows],
1850
  "folders": [dict(f) for f in tree],
1851
  "itemFolders": dict(kept),
1852
  "starred": list(state.get("starred") or []),
1853
+ "rev": _index_rev(state),
1854
  }
1855
  return state, None
1856
 
1857
  _persist(st, INDEX_KEY, _apply, seed={"workbooks": []})
1858
  result = dict(out.get("value") or {"workbooks": [], "folders": [], "itemFolders": {},
1859
+ "starred": [], "rev": 0})
1860
+ # ⚠ THE GRANT JOIN RUNS AFTER `_persist`, NEVER INSIDE THE CALLBACK. `shares.grants` reads the
1861
+ # store, and reading one document from inside another document's update callback puts a second
1862
+ # store call under a lock this one already holds.
1863
+ result["workbooks"] = project_shares(st, result.get("workbooks"))
1864
  result["repairs"] = repairs
1865
  return result
platform/core/table_store.py CHANGED
@@ -617,7 +617,7 @@ class TableStore:
617
  same tenant's buckets this workspace lives in (wave 21, C1)."""
618
  return self._st
619
 
620
- def find_view(self, view_id, prefer_owner=None):
621
  """`(owner_username, view)` for a view living in ANY personal stratum, else None.
622
 
623
  ⭐ Wave 21 (item 9, C1): the R10 grant registry names bare ids, so projecting a granted
@@ -631,7 +631,21 @@ class TableStore:
631
  scan therefore answered whichever stratum the dict happened to yield first - so starring
632
  `All products` wrote `important` onto a colleague's overlay record and the caller's own
633
  rail never changed, with a 200 and nothing red. A caller that names itself gets its own
634
- record when one exists; the scan below is unchanged otherwise."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
  # A direct lookup is a runtime read too. Do not leave a stale compatibility-shaped
636
  # personal record reachable merely because this caller did not first go through the grid
637
  # workspace assembler.
@@ -655,6 +669,24 @@ class TableStore:
655
  v = (ws.get('views') or {}).get(vid)
656
  if isinstance(v, dict):
657
  return str(username), dict(v)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  return None
659
 
660
  def find_folder(self, folder_id):
@@ -1675,6 +1707,98 @@ class TableStore:
1675
 
1676
  self._audited_update(_up, rev=rev, flush='async')
1677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1678
  # ------------------------------------------------------- W50-T26: the trash and its restore
1679
  def trash(self, username, now=None):
1680
  """One owner's trashed views, NEWEST DELETION FIRST, expired entries PURGED on the way.
@@ -1704,7 +1828,25 @@ class TableStore:
1704
  return []
1705
  stamp = float(now if now is not None else time.time())
1706
  expired = [vid for vid, entry in bucket.items() if trash_expired(entry, now=stamp)]
1707
- if expired:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1708
  def _purge(current):
1709
  current = current if isinstance(current, dict) else {}
1710
  ws = current.get(owner)
 
617
  same tenant's buckets this workspace lives in (wave 21, C1)."""
618
  return self._st
619
 
620
+ def find_view(self, view_id, prefer_owner=None, include_trashed=False):
621
  """`(owner_username, view)` for a view living in ANY personal stratum, else None.
622
 
623
  ⭐ Wave 21 (item 9, C1): the R10 grant registry names bare ids, so projecting a granted
 
631
  scan therefore answered whichever stratum the dict happened to yield first - so starring
632
  `All products` wrote `important` onto a colleague's overlay record and the caller's own
633
  rail never changed, with a 200 and nothing red. A caller that names itself gets its own
634
+ record when one exists; the scan below is unchanged otherwise.
635
+
636
+ ⭐⭐ `include_trashed` (wave 51, W51-T26, ruling R11) - "MISSING" AND "TRASHED" ARE
637
+ DIFFERENT ANSWERS. A deleted view is MOVED out of `views` into `<owner>.trash`, so this
638
+ scan answered None for it and every consumer reported it as gone: a Sheet cell scoped to a
639
+ view somebody deleted an hour ago refused with `view_missing` for the whole 30 days it was
640
+ still restorable. R11 says such a cell keeps working until the view is PURGED, so a caller
641
+ that wants that promise asks for it by name.
642
+
643
+ β›” IT DEFAULTS TO FALSE, AND THE DEFAULT IS THE LOAD-BEARING HALF. Nine call sites read
644
+ this method and several are permission-adjacent (`routes_shares`, `routes_starred`,
645
+ `routes_publish`, `routes_forms`): a resolver that silently starts answering for a record
646
+ it used to refuse widens every one of them with every gate still green. So the fallback is
647
+ OPT IN, the live scan always wins, an EXPIRED entry is never offered (retention is not a
648
+ display filter) and `prefer_owner` is honoured in the trash exactly as it is above."""
649
  # A direct lookup is a runtime read too. Do not leave a stale compatibility-shaped
650
  # personal record reachable merely because this caller did not first go through the grid
651
  # workspace assembler.
 
669
  v = (ws.get('views') or {}).get(vid)
670
  if isinstance(v, dict):
671
  return str(username), dict(v)
672
+ if not include_trashed:
673
+ return None
674
+ # R11's 30 days. Same preference order as above, and only an UNEXPIRED entry: an entry
675
+ # past retention is being destroyed, so answering with it would let a cell resolve
676
+ # through a view the very next read is going to purge.
677
+ order = ([mine] if mine and mine not in RESERVED_MEMBERS else [])
678
+ order += [str(who) for who in data if who not in RESERVED_MEMBERS and who != mine]
679
+ for who in order:
680
+ ws = data.get(who)
681
+ if not isinstance(ws, dict):
682
+ continue
683
+ bucket = ws.get(TRASH_KEY)
684
+ entry = bucket.get(vid) if isinstance(bucket, dict) else None
685
+ if not isinstance(entry, dict) or trash_expired(entry):
686
+ continue
687
+ record = entry.get('view')
688
+ if isinstance(record, dict):
689
+ return str(who), dict(record, id=vid)
690
  return None
691
 
692
  def find_folder(self, folder_id):
 
1707
 
1708
  self._audited_update(_up, rev=rev, flush='async')
1709
 
1710
+ # ---------------------------------------------- W51-T26 / R11: what a PURGE leaves behind
1711
+ def _adopt_purged(self, entries):
1712
+ """Copy each purged view's scope into every Sheet cell that named it. True when it held.
1713
+
1714
+ β›”β›” THE PURGE PATH ONLY, and never a trash or a restore. R11: a view-scoped cell keeps
1715
+ pointing at a TRASHED view for the whole 30 days and re-links for free if the view comes
1716
+ back; the filter is copied into the cell's own scope only when the view is destroyed.
1717
+ Adopting at trash would make Restore a lie - the cell would already hold a frozen snapshot
1718
+ of what the view used to say, and every later edit of the view would stop reaching it.
1719
+
1720
+ ⚠ A DEFERRED core-to-core IMPORT, matching `choice_removal` above. `core/sheets.py`
1721
+ imports nothing from `core` at module level and this module is imported by half the API,
1722
+ so a top-level import here is an import cycle.
1723
+
1724
+ ⚠ A MALFORMED ENTRY IS SKIPPED, NOT FAILED. `trash_expired` counts an entry with no
1725
+ restorable `view` as expired precisely so it can be dropped; it names no filter, so there
1726
+ is nothing for a binding to adopt and refusing to purge it would grow the document forever.
1727
+
1728
+ ⚠ IT RETURNS FALSE RATHER THAN RAISING BECAUSE ITS ONE CALLER IS HOUSEKEEPING ON A READ.
1729
+ `trash()` turns a False into "do not purge yet" and answers the list anyway. `purge_view`
1730
+ below deliberately does NOT come through here: a person clicked a destructive button and
1731
+ was shown a count, so a failure there has to be loud rather than quietly deferred.
1732
+
1733
+ β›” MEASURED RESIDUE, BOOKED RATHER THAN HIDDEN: the adoption writes ONE WORKBOOK AT A TIME
1734
+ and there is no transaction across documents. If the second workbook's write refuses, the
1735
+ first has already taken the filter while the view is still in the trash and still
1736
+ restorable, so a Restore in that window re-links every cell EXCEPT the ones that already
1737
+ adopted. It self-heals on the next purge (the adoption is idempotent) and it is pinned by
1738
+ its own leg in `verify_shared_views.py` section 10d rather than described here.
1739
+ """
1740
+ from core import sheets as _sheets
1741
+ try:
1742
+ for entry in entries or ():
1743
+ record = (entry or {}).get('view')
1744
+ if not isinstance(record, dict):
1745
+ continue
1746
+ record = dict(record)
1747
+ record.setdefault('id', str((entry or {}).get('id') or ''))
1748
+ _sheets.adopt_view_filter(self._st, record)
1749
+ except Exception: # noqa: BLE001
1750
+ return False
1751
+ return True
1752
+
1753
+ def purge_view(self, username, view_id, *, rev=None):
1754
+ """R11's "Delete forever": destroy one trashed view NOW. `(name, adopted_cell_count)`.
1755
+
1756
+ β›” THE ADOPTION RUNS FIRST AND A FAILURE REFUSES THE PURGE. Unlike the retention sweep on
1757
+ `trash()`, this one is a deliberate act by a person who is about to be told how many cells
1758
+ will keep the filter, so failing silently and destroying the view anyway would break the
1759
+ promise that sentence just made. It raises, the route reports it, and nothing is lost.
1760
+
1761
+ ⚠ NO AUDIT ROW, DELIBERATELY. C3 names seven actions and `purge` is not one of them;
1762
+ inventing an eighth here would widen a vocabulary two gates pin. The `delete` row written
1763
+ when the view entered the trash is still the record of its removal. Booked as a finding.
1764
+
1765
+ ⚠ IT STILL GOES THROUGH `_audited_update`, for the C3 revision guard and the one locked
1766
+ read-modify-write. `action=None` is how that door spells "no row" (see `delete_view`).
1767
+ """
1768
+ vid = str(view_id or '').strip()
1769
+ owner = str(username or '').strip().lower()
1770
+ if not vid:
1771
+ raise ValueError('view id is required')
1772
+ if not owner or owner in RESERVED_MEMBERS:
1773
+ raise ValueError('reserved username')
1774
+ data = self._st.get(self.table_key) or {}
1775
+ ws = data.get(owner)
1776
+ bucket = ws.get(TRASH_KEY) if isinstance(ws, dict) else None
1777
+ entry = bucket.get(vid) if isinstance(bucket, dict) else None
1778
+ if not isinstance(entry, dict) or trash_expired(entry):
1779
+ raise ViewNotInTrash(
1780
+ 'that view is not in the trash. Deleted views are kept for '
1781
+ f'{TRASH_RETENTION_DAYS} days.')
1782
+ record = entry.get('view') if isinstance(entry.get('view'), dict) else {}
1783
+ name = str(record.get('name') or vid)
1784
+
1785
+ from core import sheets as _sheets
1786
+ adopted = _sheets.adopt_view_filter(self._st, dict(record, id=vid))
1787
+
1788
+ def _up(current, audit):
1789
+ live = (current.get(owner) or {}).get(TRASH_KEY) if isinstance(
1790
+ current.get(owner), dict) else None
1791
+ if isinstance(live, dict):
1792
+ live.pop(vid, None)
1793
+ purge_trash(live, now=time.time())
1794
+ if not live:
1795
+ current[owner].pop(TRASH_KEY, None)
1796
+ audit(action=None, owner=owner, view_id=vid)
1797
+ return current
1798
+
1799
+ self._audited_update(_up, rev=rev, flush='async')
1800
+ return name, int(adopted)
1801
+
1802
  # ------------------------------------------------------- W50-T26: the trash and its restore
1803
  def trash(self, username, now=None):
1804
  """One owner's trashed views, NEWEST DELETION FIRST, expired entries PURGED on the way.
 
1828
  return []
1829
  stamp = float(now if now is not None else time.time())
1830
  expired = [vid for vid, entry in bucket.items() if trash_expired(entry, now=stamp)]
1831
+ # β›”β›” R11's ADOPTION RUNS BEFORE THE UPDATE AND OUTSIDE ITS CALLBACK (W51-T26).
1832
+ # `sheets.py::save_folders` states the rule for this codebase in as many words: validation
1833
+ # runs before the update, never inside its callback, because a raise from inside would
1834
+ # abandon a half touched transaction. Here it is a CROSS DOCUMENT write - the workbooks -
1835
+ # inside what is otherwise a list door, so the ordering is the whole safety property: the
1836
+ # filters land first, and only then does the bucket lose the views they came from.
1837
+ #
1838
+ # β›” AND WHEN THE ADOPTION FAILS THE PURGE DOES NOT RUN. A trash bucket emptied beside a
1839
+ # workbook that never took the filter leaves a cell pointing at an id that exists nowhere,
1840
+ # with nothing left to report it. `adopt_view_filter` is idempotent, so the honest
1841
+ # recovery is to leave the entry where it is and retry on the next read. The entry stays
1842
+ # out of the ANSWER either way: retention is a promise about what is kept, and serving a
1843
+ # 31-day-old row because housekeeping could not commit would be a second, louder bug.
1844
+ adopted = self._adopt_purged(
1845
+ [{'id': vid,
1846
+ 'view': (bucket[vid] or {}).get('view') if isinstance(bucket.get(vid), dict)
1847
+ else None}
1848
+ for vid in expired]) if expired else True
1849
+ if expired and adopted:
1850
  def _purge(current):
1851
  current = current if isinstance(current, dict) else {}
1852
  ws = current.get(owner)
platform/harness/filter_eval.py CHANGED
@@ -51,8 +51,9 @@ import math
51
  from collections import namedtuple
52
 
53
  from harness.filter_sql import ( # noqa: F401 (COHORT_OPS re-exported for callers)
54
- COHORT_FIELD, COHORT_OPS, COHORT_OP_ALIASES, FILTER_OPS, RANK_OPS,
55
- is_rule_active, parse_cohort_ids, to_num, _resolve_anchor, _window_bounds,
 
56
  )
57
 
58
  #: The CLIENT's numeric family, which is WIDER than `filter_sql.NUMERIC_TYPES`. `rating` (an
@@ -176,6 +177,61 @@ def _cmp_text(op, a, v):
176
  return True
177
 
178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  def _is_blank(raw):
180
  """The condition-builder blank contract: absent, empty choice set, or ``'(none)'``.
181
 
@@ -280,6 +336,17 @@ def _match_filter(rule, row, columns, today):
280
  if op in RANK_OPS:
281
  return False
282
 
 
 
 
 
 
 
 
 
 
 
 
283
  rhs = rule.get('rhs')
284
  has_rhs = rhs is not None
285
  other = row.get(_rhs_col(rhs) or '') if has_rhs else None
 
51
  from collections import namedtuple
52
 
53
  from harness.filter_sql import ( # noqa: F401 (COHORT_OPS re-exported for callers)
54
+ COHORT_FIELD, COHORT_OPS, COHORT_OP_ALIASES, FILTER_OPS, MULTI_VALUE_OPS, RANK_OPS,
55
+ is_rule_active, parse_cohort_ids, parse_filter_values, to_num,
56
+ _resolve_anchor, _window_bounds,
57
  )
58
 
59
  #: The CLIENT's numeric family, which is WIDER than `filter_sql.NUMERIC_TYPES`. `rating` (an
 
177
  return True
178
 
179
 
180
+ def _as_choice_text(raw):
181
+ """The client's ``String(raw ?? "")`` over a CHOICE-SET cell, lowercased.
182
+
183
+ ⚠ NOT ``_as_text``. A multi-select value can still arrive from the wire as a LIST (see
184
+ ``_is_blank``, which already carries that case), and Python's ``str(['a', 'b'])`` renders
185
+ ``"['a', 'b']"`` where JS's ``String(["a","b"])`` renders ``"a,b"`` β€” the comma-joined form
186
+ the storage layer uses and the one the membership test below has to see.
187
+ """
188
+ if isinstance(raw, (list, tuple)):
189
+ return ','.join('' if x is None else str(x) for x in raw).lower()
190
+ return _as_text(raw)
191
+
192
+
193
+ def _cell_members(raw):
194
+ """The MEMBERS of one cell, mirroring `useVisibleRows.cellMembers`.
195
+
196
+ A multi-select cell is a comma-joined set; a single-valued cell is a one-member set, so
197
+ ``hasAnyOf`` over a select column means exactly what ``isAnyOf`` does there. A BLANK cell has
198
+ NO members, which is the blank decision the three engines pin as a lock-step case.
199
+ """
200
+ return [m for m in (part.strip() for part in _as_choice_text(raw).split(',')) if m]
201
+
202
+
203
+ def _match_multi_value(op, raw, values):
204
+ """⭐ W51-T07 β€” the five multi-value operators, COMPOSED from `_cmp_text`.
205
+
206
+ β›” THIS FUNCTION IS THE POINT OF THE WHOLE AMENDMENT. This module imports ``FILTER_OPS`` from
207
+ ``filter_sql``, and its only vocabulary guard is ``op not in FILTER_OPS -> False``. The moment
208
+ the five ops joined that set, the guard began PASSING them straight into ``_cmp_text``, whose
209
+ tail returns True for an operator it does not know β€” so every row would have matched, in the
210
+ module that is BOTH the server-side display mirror (``matches``) and the PERMISSION wall
211
+ (``permits``). A bare ``return False`` would have been no better: the server would then
212
+ disagree with the browser about real rows, which is the drift this module exists to prevent.
213
+
214
+ ``isAnyOf`` is the OR of ``_cmp_text('eq', ...)`` over the values, so it is the union of the
215
+ equivalent single-value leaves by construction rather than by testing.
216
+ """
217
+ want = [v.strip().lower() for v in values]
218
+ # β›” NO VALUES = UNANSWERABLE = MATCHES NOTHING, uniformly. A SECOND layer: `_eval` already
219
+ # calls such a leaf inactive via `is_rule_active`. Written anyway because the vacuous cases
220
+ # go the WIDENING way β€” `all(... for v in [])` is True, so `hasAllOf []` would match every
221
+ # row, on a permission wall. `filter_sql` answers `1=0` for the identical input.
222
+ if not want:
223
+ return False
224
+ if op in ('isAnyOf', 'isNoneOf'):
225
+ a = _as_choice_text(raw)
226
+ hit = any(_cmp_text('eq', a, v) for v in want)
227
+ return hit if op == 'isAnyOf' else not hit
228
+ members = _cell_members(raw)
229
+ if op == 'hasAllOf':
230
+ return all(v in members for v in want)
231
+ hit = any(v in members for v in want)
232
+ return hit if op == 'hasAnyOf' else not hit
233
+
234
+
235
  def _is_blank(raw):
236
  """The condition-builder blank contract: absent, empty choice set, or ``'(none)'``.
237
 
 
336
  if op in RANK_OPS:
337
  return False
338
 
339
+ # ⭐ W51-T07 β€” the MULTI-VALUE family, ON THE OP and before the type dispatch. Every branch
340
+ # below ends in a blank-value short-circuit and these leaves carry a blank `value`; one
341
+ # fall-through and a permission wall reading `Agent is any of [...]` admits every row.
342
+ if op in MULTI_VALUE_OPS:
343
+ # Numeric and date columns REFUSE, matching the other two engines exactly: `_cmp_num`'s
344
+ # documented `default: True` would widen, and comparing a number against its own string
345
+ # form would make the three engines disagree about a rendering rather than a value.
346
+ if ftype in NUMERIC_TYPES or ftype in DATE_TYPES:
347
+ return False
348
+ return _match_multi_value(op, raw, parse_filter_values(rule.get('values')))
349
+
350
  rhs = rule.get('rhs')
351
  has_rhs = rhs is not None
352
  other = row.get(_rhs_col(rhs) or '') if has_rhs else None
platform/harness/filter_sql.py CHANGED
@@ -77,7 +77,18 @@ FILTER_OPS = frozenset({
77
  'gt', 'gte', 'lt', 'lte', 'between', 'within',
78
  'topN', 'bottomN', 'inTopPct', 'inBottomPct',
79
  'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile',
 
80
  })
 
 
 
 
 
 
 
 
 
 
81
  #: Wave 2026-08-02 (C-OPS): the RANK subset β€” set-ranked over the sibling-filtered domain.
82
  #: Vocabulary here, execution NOWHERE in this module: a per-row WHERE cannot express Top-N,
83
  #: and compiling to 1=0 would answer "nothing" to a question that has an answer, under a
@@ -107,6 +118,28 @@ def parse_cohort_ids(value):
107
  if len(out) >= MAX_COHORT_IDS:
108
  break
109
  return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  # types.ts VALUE_FREE_OPS: no value control is rendered, and they must never be judged
111
  # "inactive because the value is blank" β€” that would turn them into no-ops.
112
  VALUE_FREE_OPS = frozenset({'isEmpty', 'isNotEmpty', 'aboveAvg', 'belowAvg'})
@@ -249,6 +282,12 @@ def is_rule_active(rule, columns):
249
  if col not in columns:
250
  return False
251
  op = rule.get('op')
 
 
 
 
 
 
252
  if op in VALUE_FREE_OPS:
253
  return True
254
  if op == 'within':
@@ -375,6 +414,13 @@ def _compile_leaf(rule, columns, state):
375
  v = _value_sql(spec)
376
  t = spec['type']
377
 
 
 
 
 
 
 
 
378
  # --- CG-9: the comparand is another COLUMN, coerced through the LEFT field's type --------
379
  # `_value_sql` on a spec whose `sql` is the RIGHT column and whose `type` is the LEFT one β€”
380
  # exactly what TS does (`toNum(other)` for a numeric LHS, `String(other ?? "")` for a date,
@@ -484,6 +530,51 @@ def _resolve_anchor(mode, value, today):
484
  return _windows().resolve_anchor(mode, value, today)
485
 
486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  def _compile_cohort(rule, state):
488
  """Port of evalNode's cohort branch: membership in a SET of hand-curated sets of row ids.
489
 
 
77
  'gt', 'gte', 'lt', 'lte', 'between', 'within',
78
  'topN', 'bottomN', 'inTopPct', 'inBottomPct',
79
  'aboveAvg', 'belowAvg', 'inQuartile', 'inDecile',
80
+ 'isAnyOf', 'isNoneOf', 'hasAnyOf', 'hasAllOf', 'hasNoneOf',
81
  })
82
+ #: ⭐ W51-T07 (owner instruction 25): the MULTI-VALUE subset β€” operators whose operand is the
83
+ #: leaf's ``values`` LIST rather than its ``value`` string. Mirrors types.ts MULTI_VALUE_OPS.
84
+ #: β›” These leaves leave ``value`` BLANK, so `is_rule_active`'s tail rule ("blank value means the
85
+ #: rule is half-typed") would call a fully built one INACTIVE β€” and inactive means no predicate
86
+ #: at all, i.e. every row, under a row_count that still looks authoritative. `is_rule_active`
87
+ #: therefore answers them from ``values``, and `_compile_leaf` intercepts them on the OP before
88
+ #: any type branch can apply its own blank-value short-circuit.
89
+ MULTI_VALUE_OPS = frozenset({'isAnyOf', 'isNoneOf', 'hasAnyOf', 'hasAllOf', 'hasNoneOf'})
90
+ #: Mirrors types.ts MAX_FILTER_VALUES / aios_grid.MAX_FILTER_VALUES.
91
+ MAX_FILTER_VALUES = 100
92
  #: Wave 2026-08-02 (C-OPS): the RANK subset β€” set-ranked over the sibling-filtered domain.
93
  #: Vocabulary here, execution NOWHERE in this module: a per-row WHERE cannot express Top-N,
94
  #: and compiling to 1=0 would answer "nothing" to a question that has an answer, under a
 
118
  if len(out) >= MAX_COHORT_IDS:
119
  break
120
  return out
121
+
122
+
123
+ def parse_filter_values(values):
124
+ """The values a multi-value leaf names. Mirrors types.ts `filterValues()`.
125
+
126
+ A real LIST, never a comma-joined string: a select OPTION is tenant prose and may itself
127
+ contain a comma, so joining would split one real choice into two that match nothing. Order
128
+ preserved, blanks dropped, duplicates collapsed, members capped at 120 chars, the list capped
129
+ at MAX_FILTER_VALUES. Unknown option strings are KEPT β€” a value that no longer exists then
130
+ filters to nothing, honestly, rather than silently asking a wider question.
131
+ """
132
+ out = []
133
+ if not isinstance(values, (list, tuple)):
134
+ return out
135
+ for raw in values:
136
+ v = ('' if raw is None else str(raw)).strip()[:120]
137
+ if not v or v in out:
138
+ continue
139
+ out.append(v)
140
+ if len(out) >= MAX_FILTER_VALUES:
141
+ break
142
+ return out
143
  # types.ts VALUE_FREE_OPS: no value control is rendered, and they must never be judged
144
  # "inactive because the value is blank" β€” that would turn them into no-ops.
145
  VALUE_FREE_OPS = frozenset({'isEmpty', 'isNotEmpty', 'aboveAvg', 'belowAvg'})
 
282
  if col not in columns:
283
  return False
284
  op = rule.get('op')
285
+ # ⭐ W51-T07 β€” a MULTI-VALUE leaf is driven by the LIST it names and by nothing else, exactly
286
+ # as the cohort arm above is driven by its set. FIRST among the op tests, because these
287
+ # leaves carry a BLANK `value` and the tail rule below ("blank value = inactive") would
288
+ # otherwise IGNORE a fully built condition, emitting no predicate and showing every row.
289
+ if op in MULTI_VALUE_OPS:
290
+ return bool(parse_filter_values(rule.get('values')))
291
  if op in VALUE_FREE_OPS:
292
  return True
293
  if op == 'within':
 
414
  v = _value_sql(spec)
415
  t = spec['type']
416
 
417
+ # --- ⭐ W51-T07: the MULTI-VALUE family, ON THE OP and before every type branch ----------
418
+ # Placed with the value-free ops above rather than inside the text branch, and for the same
419
+ # reason: every type branch below ends in a blank-value short-circuit, and these leaves carry
420
+ # a blank `value`. One fall-through and `Agent is any of [A, B, C]` compiles to `1=1`.
421
+ if op in MULTI_VALUE_OPS:
422
+ return _compile_multi_value(op, v, t, rule, used)
423
+
424
  # --- CG-9: the comparand is another COLUMN, coerced through the LEFT field's type --------
425
  # `_value_sql` on a spec whose `sql` is the RIGHT column and whose `type` is the LEFT one β€”
426
  # exactly what TS does (`toNum(other)` for a numeric LHS, `String(other ?? "")` for a date,
 
530
  return _windows().resolve_anchor(mode, value, today)
531
 
532
 
533
+ def _compile_multi_value(op, v, t, rule, used):
534
+ """⭐ W51-T07 β€” the five multi-value operators, as bound-parameter SQL.
535
+
536
+ ``isAnyOf`` is COMPOSED from the very fragment ``eq`` compiles to (``{v} = LOWER(?)``),
537
+ OR-joined. That is the ticket's correctness target expressed in code rather than in a test:
538
+ ``Agent is any of [A, B, C]`` is the union of three ``Agent eq`` leaves by construction, with
539
+ the same folding, the same COALESCE of a NULL cell and the same treatment of the connector's
540
+ ``'(none)'`` sentinel. ``isNoneOf`` is its negation.
541
+
542
+ The three ``has*`` operators answer a ``multiselect`` cell, which is a comma-joined SET, so
543
+ they compare whole MEMBERS: ``list_contains(list_transform(str_split(...), trim), needle)``
544
+ mirrors the client's split/trim/fold exactly. ⚠ NOT ``strpos``: substring membership is what
545
+ makes ``contains`` find *Done* inside *Not done*, and removing that is half of why these
546
+ operators exist. ``hasAllOf`` is the AND of the memberships, per the ticket's `how` line.
547
+
548
+ BLANKS, decided once for all three engines: a blank cell has NO members and equals no listed
549
+ value, so ``isNoneOf`` / ``hasNoneOf`` answer TRUE over it and the other three answer FALSE.
550
+ ``str_split('', ',')`` yields one empty member, which ``list_contains`` never matches because
551
+ `parse_filter_values` drops empty values.
552
+
553
+ NUMERIC and DATE columns REFUSE (``1=0``, matches nothing) rather than compare. They do not
554
+ offer these operators, but a saved view whose column later changed type can carry one, and
555
+ the alternatives are both wrong: SQL_TRUE would widen exactly as the client's documented
556
+ ``default: true`` would, and stringifying the number would compare against a RENDERING the
557
+ three engines do not spell the same way.
558
+
559
+ Every value is BOUND, never interpolated: these strings are tenant prose.
560
+ """
561
+ if t in NUMERIC_TYPES or t in ('date', 'created_time'):
562
+ return ('1=0', [])
563
+ vals = parse_filter_values(rule.get('values'))
564
+ if not vals:
565
+ # Unreachable: `is_rule_active` already demanded a non-empty list. Never SQL_TRUE.
566
+ return ('1=0', [])
567
+ if op in ('isAnyOf', 'isNoneOf'):
568
+ union = '(' + ' OR '.join(f"({v} = LOWER(?))" for _ in vals) + ')'
569
+ return used((f"(NOT {union})" if op == 'isNoneOf' else union), vals)
570
+ members = f"list_transform(str_split({v}, ','), x -> trim(x))"
571
+ parts = [f"list_contains({members}, TRIM(LOWER(?)))" for _ in vals]
572
+ if op == 'hasAllOf':
573
+ return used('(' + ' AND '.join(parts) + ')', vals)
574
+ union = '(' + ' OR '.join(parts) + ')'
575
+ return used((f"(NOT {union})" if op == 'hasNoneOf' else union), vals)
576
+
577
+
578
  def _compile_cohort(rule, state):
579
  """Port of evalNode's cohort branch: membership in a SET of hand-curated sets of row ids.
580
 
platform/modules/sheet.py CHANGED
@@ -31,10 +31,30 @@ The only SQL this module writes itself is the aggregate wrapper and the spec's o
31
 
32
  from __future__ import annotations
33
 
 
 
34
  #: C2's aggregate vocabulary. `metric_key` is the other arm of that union and is resolved by the
35
  #: route against the same catalogue `routes_query.py::_compatible_metric_dtos` serves.
36
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  #: C2's refusal codes, spelled once. ⚠ Each message reaches a screen, so none carries an em dash or
39
  #: an en dash (standing rule 2) and each names both the cause and the subject.
40
  REFUSALS = {
@@ -48,6 +68,21 @@ REFUSALS = {
48
  "binding_invalid": "That cell's source is not set up correctly.",
49
  "aggregate_unknown": "{subject} is not an aggregate this cell can compute.",
50
  "field_unknown": "{subject} is not a column on this database.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  }
52
 
53
 
@@ -62,11 +97,96 @@ class SheetRefusal(Exception):
62
  super().__init__(self.message)
63
 
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  def clean_binding(raw):
66
  """Normalize a C2 `Binding`, or raise `SheetRefusal`.
67
 
68
- `Binding = {database, aggregate:{fn, field?} | {metric_key}, scope:{view_id} | {filter},
69
- period?: {ref} | {window}}`
 
70
  """
71
  if not isinstance(raw, dict):
72
  raise SheetRefusal("binding_invalid")
@@ -111,12 +231,20 @@ def clean_binding(raw):
111
  else:
112
  raise SheetRefusal("binding_invalid")
113
 
 
 
 
 
114
  out = {"database": database, "aggregate": out_agg, "scope": out_scope}
115
 
116
- period = raw.get("period")
117
- if isinstance(period, dict) and (period.get("ref") or period.get("window")):
118
- out["period"] = ({"ref": str(period["ref"]).strip()} if period.get("ref")
119
- else {"window": period["window"]})
 
 
 
 
120
  return out
121
 
122
 
 
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
41
+ #: its window starts in. `web/src/sheet/types.ts` carries the same three names.
42
+ PERIOD_UNITS = ("month", "quarter", "year")
43
+
44
+ #: `YYYY-MM`. A period starts in a MONTH whatever its unit, because a quarter and a year are both
45
+ #: named by the month they open on, and one spelling means a copied cell cannot mean two things.
46
+ _PERIOD_START = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
47
+
48
+ #: A `period.ref` points at a cell that holds the period, so it is a plain A1 address with no `$`,
49
+ #: exactly as `core/sheets.py::_ADDR` spells one.
50
+ _PERIOD_REF = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
51
+
52
+ #: ⭐ R10's DRAG, and it is TWO settings rather than one because the two axes answer different
53
+ #: questions. Across columns a drag walks the PERIOD; down rows it walks the next value of a
54
+ #: chosen field. Defaults: across "period", down "none".
55
+ DRAG_ACROSS = ("period", "none")
56
+ DRAG_DOWN_NONE = "none"
57
+
58
  #: C2's refusal codes, spelled once. ⚠ Each message reaches a screen, so none carries an em dash or
59
  #: an en dash (standing rule 2) and each names both the cause and the subject.
60
  REFUSALS = {
 
68
  "binding_invalid": "That cell's source is not set up correctly.",
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
75
+ # WORDED. `routes_sheet._refuse` decides the STATUS from the code and `_formula_message`
76
+ # reads this table for a sentence, so a code worded at the route would arrive with two
77
+ # spellings depending on which door refused ([[one-question-two-normalizers]]).
78
+ #
79
+ # ⚠ `{subject}` IS THE WORKBOOK'S OWNER, so the sentence tells the reader who to ask rather
80
+ # than only that they were stopped. `SheetRefusal(code, subject)` falls back to "this
81
+ # database" when no subject is given, which reads wrongly here, so both doors pass one.
82
+ "workbook_read_only": "This workbook was shared with you to read, so it cannot be changed "
83
+ "here. Ask {subject} for permission to edit it.",
84
+ "workbook_owner_only": "Only the person who created this workbook can do that. Ask "
85
+ "{subject}.",
86
  }
87
 
88
 
 
97
  super().__init__(self.message)
98
 
99
 
100
+ def clean_period(raw):
101
+ """R9's period, or None. `{unit, start, locked, ref?}`, with `{ref}` / `{window}` still read.
102
+
103
+ β›” AN UNKNOWN UNIT OR A MALFORMED START IS REFUSED BY NAME, and that is not the same call as
104
+ the cosmetic keys next door. A period decides WHICH ROWS ARE COUNTED. Dropping `unit: "week"`
105
+ would answer for every row the binding can see and hand back a bigger number with nobody told,
106
+ which is standing rule 1's second sentence turned into a defect.
107
+
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
114
+ out = {}
115
+
116
+ unit = str(raw.get("unit") or "").strip().lower()
117
+ if unit:
118
+ if unit not in PERIOD_UNITS:
119
+ raise SheetRefusal("period_invalid", unit)
120
+ out["unit"] = unit
121
+
122
+ start = str(raw.get("start") or "").strip()
123
+ if start:
124
+ if not _PERIOD_START.match(start):
125
+ raise SheetRefusal("period_invalid", start)
126
+ out["start"] = start
127
+
128
+ if raw.get("locked") is True:
129
+ out["locked"] = True
130
+
131
+ ref = str(raw.get("ref") or "").strip().upper().replace("$", "")
132
+ if ref:
133
+ if not _PERIOD_REF.match(ref):
134
+ raise SheetRefusal("period_invalid", ref)
135
+ out["ref"] = ref
136
+
137
+ #: ⚠ The wave-49 spelling, kept so a binding written before R9 still round trips. It is not a
138
+ #: second dialect for the same thing: `window` is a raw relative window, `unit` + `start` is a
139
+ #: named calendar period, and a document carrying the old one is not rewritten on read.
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):
147
+ """R10's two directional drag settings, or None when the caller sent none.
148
+
149
+ ⚠ BOTH KEYS COME OUT WHENEVER ONE WENT IN. The two axes are answered together or a drag has
150
+ to guess one of them, and a guess is exactly what R10 replaced. The defaults are R10's own:
151
+ across "period", down "none".
152
+ """
153
+ if not isinstance(raw, dict):
154
+ return None
155
+ across = str(raw.get("across") or "").strip().lower()
156
+ if across not in DRAG_ACROSS:
157
+ across = "period"
158
+ down = raw.get("down")
159
+ if isinstance(down, dict) and str(down.get("field") or "").strip():
160
+ out_down = {"field": str(down["field"]).strip()}
161
+ else:
162
+ out_down = DRAG_DOWN_NONE
163
+ return {"across": across, "down": out_down}
164
+
165
+
166
+ def clean_adopted_from(raw):
167
+ """W51-T26's adoption receipt, or None. `{view_id, name, at}`.
168
+
169
+ ⭐⭐ IT IS WHAT A PURGED VIEW LEAVES BEHIND. When a view is purged the binding keeps that
170
+ view's FILTER, so the number stays right; without this receipt the cell would show a number
171
+ with no way to say where its scope came from, and the person would find a filter they never
172
+ wrote. It rides on the FILTER scope for exactly that reason, not only on the view scope.
173
+ """
174
+ if not isinstance(raw, dict):
175
+ return None
176
+ out = {}
177
+ for key, limit in (("view_id", 120), ("name", 200), ("at", 120)):
178
+ value = str(raw.get(key) or "").strip()[:limit]
179
+ if value:
180
+ out[key] = value
181
+ return out or None
182
+
183
+
184
  def clean_binding(raw):
185
  """Normalize a C2 `Binding`, or raise `SheetRefusal`.
186
 
187
+ `Binding = {database, aggregate:{fn, field?} | {metric_key},
188
+ scope:{view_id} | {filter} (+ adoptedFrom?),
189
+ period?: {unit, start, locked, ref?} | {window}, onDrag?: {across, down}}`
190
  """
191
  if not isinstance(raw, dict):
192
  raise SheetRefusal("binding_invalid")
 
231
  else:
232
  raise SheetRefusal("binding_invalid")
233
 
234
+ adopted = clean_adopted_from(scope.get("adoptedFrom"))
235
+ if adopted:
236
+ out_scope["adoptedFrom"] = adopted
237
+
238
  out = {"database": database, "aggregate": out_agg, "scope": out_scope}
239
 
240
+ period = clean_period(raw.get("period"))
241
+ if period:
242
+ out["period"] = period
243
+
244
+ on_drag = clean_on_drag(raw.get("onDrag"))
245
+ if on_drag:
246
+ out["onDrag"] = on_drag
247
+
248
  return out
249
 
250
 
web/src/assistant/AssistantPage.tsx CHANGED
@@ -11,6 +11,8 @@ import {
11
  answerSourceFooter, deleteQuery, deleteThread, fetchQueries, rateMessage, submitChat, type QueryCitation,
12
  type QueryIndex, type QueryMessage, type SavedQuery,
13
  } from "../query/queryApi";
 
 
14
  import "./assistant.css";
15
  import "../styles/wave45/agent-operator.css";
16
 
@@ -186,6 +188,12 @@ export function AssistantMessage({
186
  const [slackOpen, setSlackOpen] = useState(false);
187
  const [artifacts, setArtifacts] = useState<QueryToolArtifacts | null>(governedArtifacts || null);
188
  const [artifactStatus, setArtifactStatus] = useState("");
 
 
 
 
 
 
189
  const matching = citations.filter((citation) => (message.citationIds || []).includes(citation.id));
190
  if (message.role === "user") {
191
  return (
@@ -237,7 +245,8 @@ export function AssistantMessage({
237
  </div>
238
  {artifactStatus ? <p className="w45-safe" role="status">{artifactStatus}</p> : null}
239
  {slackOpen ? (
240
- <div className="w45-contract-card" role="dialog" aria-label="Slack correction">
 
241
  <h4>Slack correction</h4>
242
  <p>Slack can correct Filter, Sort, and Group after the Query capability check. Complex edits open the exact server-returned Query in Loopable.</p>
243
  {(["filters", "sorts", "group"] as const).map((key) => <label className="w45-artifact" key={key}>
 
11
  answerSourceFooter, deleteQuery, deleteThread, fetchQueries, rateMessage, submitChat, type QueryCitation,
12
  type QueryIndex, type QueryMessage, type SavedQuery,
13
  } from "../query/queryApi";
14
+ // W51-T31 β€” the ONE Escape arbiter (C8). See the registration in `AssistantMessage`.
15
+ import { useEscapeClose } from "../ui/useEscapeClose";
16
  import "./assistant.css";
17
  import "../styles/wave45/agent-operator.css";
18
 
 
188
  const [slackOpen, setSlackOpen] = useState(false);
189
  const [artifacts, setArtifacts] = useState<QueryToolArtifacts | null>(governedArtifacts || null);
190
  const [artifactStatus, setArtifactStatus] = useState("");
191
+ const slackRef = useRef<HTMLDivElement | null>(null);
192
+ // W51-T31 β€” the Slack correction card calls itself a `role="dialog"`, so it owes a dialog's
193
+ // dismissal: Escape closes it, through the ONE stack (C8 / DESIGN.md Β§4). Registered here at
194
+ // the top level rather than beside the markup, because the markup sits behind a conditional
195
+ // and the early return for a user message is two lines below.
196
+ useEscapeClose(slackOpen, () => setSlackOpen(false), { container: () => slackRef.current });
197
  const matching = citations.filter((citation) => (message.citationIds || []).includes(citation.id));
198
  if (message.role === "user") {
199
  return (
 
245
  </div>
246
  {artifactStatus ? <p className="w45-safe" role="status">{artifactStatus}</p> : null}
247
  {slackOpen ? (
248
+ <div className="w45-contract-card" role="dialog" aria-label="Slack correction"
249
+ ref={slackRef}>
250
  <h4>Slack correction</h4>
251
  <p>Slack can correct Filter, Sort, and Group after the Query capability check. Complex edits open the exact server-returned Query in Loopable.</p>
252
  {(["filters", "sorts", "group"] as const).map((key) => <label className="w45-artifact" key={key}>
web/src/connectors/ViewDeleteDisclosure.tsx CHANGED
@@ -1,5 +1,6 @@
1
  // ---------------------------------------------------------------------------
2
- // connectors/ViewDeleteDisclosure.tsx β€” W49-T16, ruling R32, contract C3.
 
3
  //
4
  // ⭐⭐ R32, second half, verbatim: *"deleting a view must first disclose who it
5
  // is shared to and which Sheet cells depend on it."* So this is not a generic
@@ -7,39 +8,28 @@
7
  //
8
  // Shared with Anna and 2 others Β· used by 3 Sheet cells
9
  //
10
- // β›” THIS TICKET SHIPS THE COMPONENT, NOT ITS MOUNT. `CustomerGrid.tsx`'s
11
- // `deleteView` is wired in W49-T17, a declared handover owned by the combine
12
- // session, and that file lives in another lane's fence. Shipping unmounted is
13
- // the plan, not an omission.
 
 
14
  //
15
- // ⭐ REUSED, NOT HAND-ROLLED. `customer-grid/OverlaySurface` already owns the
16
- // dismissal/focus contract (Escape, outside-pointer dismiss, Tab focus trap,
17
- // focus restored on unmount) and `ConnectorModal.tsx` next door is the in-repo
18
- // precedent for using it from this directory. ⚠ `trapFocus` DEFAULTS TO FALSE,
19
- // so a confirm dialog must pass it explicitly.
20
- //
21
- // β›”β›” TWO TRAPS, BOTH PAID FOR ALREADY:
22
- // (a) a portalled overlay paints its OWN background or it renders transparent
23
- // over whatever it covers ([[a-portal-overlay-carries-its-own-surface]]);
24
- // (b) z-order is a THREE-WAY order, so this sits on the DIALOG step
25
- // (`--cg-z-record`) and the portal step (`--cg-z-overlay`) stays above it
26
- // ([[z-layering-is-a-three-way-order]]). A token, never a number.
27
  //
28
  // ⚠ STYLES ARE INLINE `var(--lp-*)` RATHER THAN A STYLESHEET, and that is a
29
- // FENCE fact rather than a preference: W49-T16 owns five files and no CSS file
30
- // is among them. The discipline DESIGN.md Β§5 asks for is unchanged β€” every
31
- // colour, size, radius and z-index below is a token, there is not one literal
32
- // hex and not one literal font-size. If this component later earns a stylesheet,
33
- // the rules lift out of `S` unchanged.
34
- //
35
- // β›” DESTRUCTIVE MEANS RED (DESIGN.md Β§3). The confirming action wears
36
- // `--lp-red-deep` on `--lp-red-tint`, never `--lp-primary`, and every button
37
- // resets native chrome (appearance / border / background / font / color).
38
  //
39
  // β›” STANDING RULE 2 β€” NO EM DASH AND NO EN DASH IN ANY STRING THAT REACHES A
40
  // SCREEN. The separator between the two facts is a MIDDOT (Β·), which the ruling
41
- // quotes itself. Sentence case throughout, no ALL-CAPS chrome, no emojis: the
42
- // one icon is inline SVG.
43
  //
44
  // ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law). A dependent's
45
  // `kind` and `label` arrive as STRINGS from `/api/v1/dependents`, so a kind the
@@ -47,9 +37,7 @@
47
  // with no change here.
48
  // ---------------------------------------------------------------------------
49
 
50
- import { useCallback, useRef, useState } from "react";
51
  import type { CSSProperties } from "react";
52
- import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
53
 
54
  /** One row of C3's `Dependent`. `kind` and `label` are read as strings, never a union. */
55
  export interface ViewDependent {
@@ -68,9 +56,12 @@ export interface ViewShareAudience {
68
  sentence?: string;
69
  }
70
 
 
 
 
 
 
71
  export interface ViewDeleteDisclosureProps {
72
- /** The saved view's name, as the user knows it. */
73
- viewName: string;
74
  /** Everything that depends on the view. Zero-count kinds are ABSENT, never zero. */
75
  dependents: ViewDependent[];
76
  /** Who the view is shared with, or undefined while it is still loading. */
@@ -79,10 +70,7 @@ export interface ViewDeleteDisclosureProps {
79
  loading?: boolean;
80
  /** A kind the server could not answer, so the dialog does not imply it is empty. */
81
  unanswered?: string[];
82
- busy?: boolean;
83
  error?: string;
84
- onConfirm: () => void;
85
- onCancel: () => void;
86
  }
87
 
88
  /**
@@ -123,176 +111,62 @@ export function disclosureLine(share: ViewShareAudience | undefined,
123
  return [audienceSentence(share), usageSentence(dependents)].filter(Boolean).join(" Β· ");
124
  }
125
 
126
- /** Token-only rules. No literal hex, no literal font-size, no literal z-index. */
 
 
 
 
 
 
 
 
127
  const S: Record<string, CSSProperties> = {
128
- backdrop: {
129
- position: "fixed",
130
- inset: 0,
131
- zIndex: "var(--cg-z-record)" as unknown as CSSProperties["zIndex"],
132
- display: "grid",
133
- placeItems: "center",
134
- padding: "24px",
135
- // (a) the portal paints its own scrim, or it renders transparent.
136
- background: "color-mix(in srgb, var(--lp-ink) 34%, transparent)",
137
- },
138
- panel: {
139
- width: "min(420px, calc(100vw - 48px))",
140
- display: "flex",
141
- flexDirection: "column",
142
- gap: "12px",
143
- padding: "20px",
144
- borderRadius: "var(--lp-r-lg)",
145
- border: "1px solid color-mix(in srgb, var(--lp-line) 82%, var(--lp-muted))",
146
- background: "var(--lp-surface)",
147
- color: "var(--lp-ink)",
148
- fontFamily: 'Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif',
149
- fontSize: "var(--lp-fs-sm)",
150
- lineHeight: "var(--lp-lh)",
151
- boxShadow: "0 30px 80px color-mix(in srgb, var(--lp-ink) 22%, transparent)",
152
- outline: "none",
153
- },
154
- head: { display: "flex", alignItems: "center", gap: "10px" },
155
- mark: { display: "inline-flex", color: "var(--lp-red-deep)" },
156
- title: { margin: 0, fontSize: "var(--lp-fs-md)", lineHeight: "var(--lp-lh-tight)" },
157
  facts: { margin: 0, color: "var(--lp-muted)" },
158
  note: { margin: 0, color: "var(--lp-muted)", fontSize: "var(--lp-fs-2xs)" },
159
  alert: { margin: 0, color: "var(--lp-red-deep)", fontSize: "var(--lp-fs-2xs)" },
160
- actions: { display: "flex", justifyContent: "flex-end", gap: "8px", marginTop: "4px" },
161
- button: {
162
- // DESIGN.md Β§4: a button resets native chrome before it is styled.
163
- appearance: "none",
164
- border: "1px solid transparent",
165
- background: "transparent",
166
- font: "inherit",
167
- color: "inherit",
168
- padding: "7px 14px",
169
- borderRadius: "var(--lp-r-md)",
170
- cursor: "pointer",
171
- },
172
- };
173
-
174
- const cancelStyle: CSSProperties = {
175
- ...S.button,
176
- borderColor: "var(--lp-line)",
177
- background: "var(--lp-surface)",
178
- color: "var(--lp-ink)",
179
  };
180
 
181
- const confirmStyle: CSSProperties = {
182
- ...S.button,
183
- // Red is the destructive hue. Never --lp-primary on a delete confirm.
184
- borderColor: "color-mix(in srgb, var(--lp-red-deep) 40%, transparent)",
185
- background: "var(--lp-red-tint)",
186
- color: "var(--lp-red-deep)",
187
- };
188
-
189
- function TrashMark() {
190
- // NO EMOJIS. Icons are inline SVG (DESIGN.md Β§4).
191
- return (
192
- <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
193
- <path
194
- d="M3 4.5h10M6.5 4.5V3.2h3v1.3M4.6 4.5l.6 8.1h5.6l.6-8.1M6.7 7v3.4M9.3 7v3.4"
195
- fill="none"
196
- stroke="currentColor"
197
- strokeWidth="1.2"
198
- strokeLinecap="round"
199
- strokeLinejoin="round"
200
- />
201
- </svg>
202
- );
203
- }
204
-
205
  /**
206
- * R32's pre-delete disclosure: the facts, then the action.
207
  *
208
- * ⭐ NEVER OVER-EXPLAIN (DESIGN.md §4). One line of facts, one line of scope when
209
- * there is something to say, and two buttons. There is no paragraph explaining
210
- * what deleting means.
 
 
211
  */
212
  export function ViewDeleteDisclosure({
213
- viewName,
214
  dependents,
215
  share,
216
  loading = false,
217
  unanswered = [],
218
- busy = false,
219
  error = "",
220
- onConfirm,
221
- onCancel,
222
  }: ViewDeleteDisclosureProps) {
223
- const panelRef = useRef<HTMLDivElement | null>(null);
224
- const [confirming, setConfirming] = useState(false);
225
-
226
- useOverlayLayer({
227
- panelRef,
228
- onDismiss: onCancel,
229
- // ⚠ EXPLICIT: the shared hook defaults `trapFocus` to false, which is right
230
- // for an anchored menu and wrong for a confirm dialog.
231
- trapFocus: true,
232
- initialFocus: "first",
233
- restoreFocus: true,
234
- });
235
-
236
- const confirm = useCallback(() => {
237
- if (busy || confirming) return;
238
- setConfirming(true);
239
- onConfirm();
240
- }, [busy, confirming, onConfirm]);
241
-
242
  const facts = disclosureLine(share, dependents);
243
- const pending = busy || confirming;
244
-
245
  return (
246
- <BodyPortal>
247
- <div style={S.backdrop}>
248
- <div
249
- ref={panelRef}
250
- style={S.panel}
251
- role="dialog"
252
- aria-modal="true"
253
- aria-label={`Delete the view ${viewName}`}
254
- tabIndex={-1}
255
- >
256
- <div style={S.head}>
257
- <span style={S.mark}>
258
- <TrashMark />
259
- </span>
260
- <h2 style={S.title}>Delete {viewName}?</h2>
261
- </div>
262
-
263
- {loading ? (
264
- <p style={S.facts} role="status" aria-live="polite">
265
- Checking what depends on this view
266
- </p>
267
- ) : facts ? (
268
- <p style={S.facts}>{facts}</p>
269
- ) : (
270
- <p style={S.facts}>Nothing else depends on this view.</p>
271
- )}
272
-
273
- {unanswered.length > 0 ? (
274
- <p style={S.note}>
275
- {unanswered.join(", ")} could not be checked, so this list may be incomplete.
276
- </p>
277
- ) : null}
278
-
279
- {error ? (
280
- <p style={S.alert} role="alert">
281
- {error}
282
- </p>
283
- ) : null}
284
-
285
- <div style={S.actions}>
286
- <button type="button" style={cancelStyle} onClick={onCancel} disabled={pending}>
287
- Keep it
288
- </button>
289
- <button type="button" style={confirmStyle} onClick={confirm} disabled={pending}>
290
- {pending ? "Deleting" : "Delete view"}
291
- </button>
292
- </div>
293
- </div>
294
- </div>
295
- </BodyPortal>
296
  );
297
  }
298
 
 
1
  // ---------------------------------------------------------------------------
2
+ // connectors/ViewDeleteDisclosure.tsx β€” W49-T16 (ruling R32, contract C3),
3
+ // re-cut by W51-T03 (ruling R6, contract C8).
4
  //
5
  // ⭐⭐ R32, second half, verbatim: *"deleting a view must first disclose who it
6
  // is shared to and which Sheet cells depend on it."* So this is not a generic
 
8
  //
9
  // Shared with Anna and 2 others Β· used by 3 Sheet cells
10
  //
11
+ // β›”β›” IT IS A DIALOG **BODY** NOW, NOT A DIALOG. R6: *"ONE ConfirmDialog for
12
+ // every destructive action … the view-delete panel"*. So the scrim, the panel,
13
+ // the trash mark, the title, the two buttons and the focus/Escape contract all
14
+ // moved to `ui/ConfirmDialog.tsx`, and what is left here is the only thing that
15
+ // was ever unique to a view delete: the DISCLOSURE. `CustomerGrid.tsx` renders
16
+ // `<ConfirmDialog … body={<ViewDeleteDisclosure … />} />`.
17
  //
18
+ // β›” AND THAT IS WHY THE PORTAL LEFT WITH THEM. This used to call `BodyPortal`
19
+ // and `useOverlayLayer` itself; nested inside a dialog that does both, two
20
+ // surfaces would claim Escape and focus for one visible panel β€” the exact
21
+ // "topmost wins" race the wave-51 kit exists to end, and the thing
22
+ // `verify_overlay.py` pins. One overlay, one claim.
 
 
 
 
 
 
 
23
  //
24
  // ⚠ STYLES ARE INLINE `var(--lp-*)` RATHER THAN A STYLESHEET, and that is a
25
+ // FENCE fact rather than a preference: neither W49-T16 nor W51-T03 owns a CSS
26
+ // file this component could import. The discipline DESIGN.md Β§5 asks for is
27
+ // unchanged β€” every colour and size below is a token, there is not one literal
28
+ // hex and not one literal font-size.
 
 
 
 
 
29
  //
30
  // β›” STANDING RULE 2 β€” NO EM DASH AND NO EN DASH IN ANY STRING THAT REACHES A
31
  // SCREEN. The separator between the two facts is a MIDDOT (Β·), which the ruling
32
+ // quotes itself. Sentence case throughout, no ALL-CAPS chrome, no emojis.
 
33
  //
34
  // ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law). A dependent's
35
  // `kind` and `label` arrive as STRINGS from `/api/v1/dependents`, so a kind the
 
37
  // with no change here.
38
  // ---------------------------------------------------------------------------
39
 
 
40
  import type { CSSProperties } from "react";
 
41
 
42
  /** One row of C3's `Dependent`. `kind` and `label` are read as strings, never a union. */
43
  export interface ViewDependent {
 
56
  sentence?: string;
57
  }
58
 
59
+ /**
60
+ * β›” NO `viewName`, NO `busy`, NO `onConfirm`/`onCancel` ANY MORE (W51-T03). Those four belonged
61
+ * to a panel that owned its own title and buttons; `ConfirmDialog` owns them now, and leaving
62
+ * duplicates here would let the dialog's title and this body's title drift apart by one edit.
63
+ */
64
  export interface ViewDeleteDisclosureProps {
 
 
65
  /** Everything that depends on the view. Zero-count kinds are ABSENT, never zero. */
66
  dependents: ViewDependent[];
67
  /** Who the view is shared with, or undefined while it is still loading. */
 
70
  loading?: boolean;
71
  /** A kind the server could not answer, so the dialog does not imply it is empty. */
72
  unanswered?: string[];
 
73
  error?: string;
 
 
74
  }
75
 
76
  /**
 
111
  return [audienceSentence(share), usageSentence(dependents)].filter(Boolean).join(" Β· ");
112
  }
113
 
114
+ /**
115
+ * Token-only rules. No literal hex, no literal font-size, no literal z-index.
116
+ *
117
+ * β›” THREE ENTRIES, DOWN FROM ELEVEN (W51-T03). `backdrop`, `panel`, `head`, `mark`, `title`,
118
+ * `actions`, `button` and the two button variants described a SURFACE, and this component is no
119
+ * longer a surface β€” `.lp-dialog` in `styles/wave51/kit.css` is. Keeping them would have left a
120
+ * second, unreachable statement of the dialog's width, radius, shadow and red, which is exactly
121
+ * the "second shape for the same act" DESIGN.md Β§4 refuses.
122
+ */
123
  const S: Record<string, CSSProperties> = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  facts: { margin: 0, color: "var(--lp-muted)" },
125
  note: { margin: 0, color: "var(--lp-muted)", fontSize: "var(--lp-fs-2xs)" },
126
  alert: { margin: 0, color: "var(--lp-red-deep)", fontSize: "var(--lp-fs-2xs)" },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  };
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  /**
130
+ * R32's pre-delete disclosure: the facts a reader needs before the button they already see.
131
  *
132
+ * ⭐ NEVER OVER-EXPLAIN (DESIGN.md §4). One line of facts, and a second line only when the
133
+ * server could not answer or the delete already failed. There is no paragraph explaining what
134
+ * deleting means, and there is no confirmation control here at all: this renders INSIDE
135
+ * `ConfirmDialog`, which owns the title, Cancel, the red "Delete view", the focus trap and
136
+ * Escape.
137
  */
138
  export function ViewDeleteDisclosure({
 
139
  dependents,
140
  share,
141
  loading = false,
142
  unanswered = [],
 
143
  error = "",
 
 
144
  }: ViewDeleteDisclosureProps) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  const facts = disclosureLine(share, dependents);
 
 
146
  return (
147
+ <>
148
+ {loading ? (
149
+ <p style={S.facts} role="status" aria-live="polite">
150
+ Checking what depends on this view
151
+ </p>
152
+ ) : facts ? (
153
+ <p style={S.facts}>{facts}</p>
154
+ ) : (
155
+ <p style={S.facts}>Nothing else depends on this view.</p>
156
+ )}
157
+
158
+ {unanswered.length > 0 ? (
159
+ <p style={S.note}>
160
+ {unanswered.join(", ")} could not be checked, so this list may be incomplete.
161
+ </p>
162
+ ) : null}
163
+
164
+ {error ? (
165
+ <p style={S.alert} role="alert">
166
+ {error}
167
+ </p>
168
+ ) : null}
169
+ </>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  );
171
  }
172
 
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -356,9 +356,19 @@ interface ColumnMenuProps {
356
  * wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
357
  * no row, rather than a row that does nothing. */
358
  onEnrich?: (scope: "blank" | "always") => void;
359
- /** W48-T17 / R8 β€” duplicate any non-identity field as a tenant-owned custom field. The
360
- * caller deliberately chooses whether its currently readable cell values come along. */
361
- onDuplicate?: (copyValues: boolean) => void;
 
 
 
 
 
 
 
 
 
 
362
  /** Wave-5 item 10 β€” save a display format. Supplied for number/currency/formula and
363
  * date/created_time fields. */
364
  onFormat?: (format: FieldFormat) => void;
@@ -4966,18 +4976,19 @@ export default function ColumnMenu({
4966
 
4967
  <div className="cg-menu-sep" role="separator" aria-hidden />
4968
 
4969
- {/* W48-T17 / R8 β€” cloning a source-backed definition is safe because the result is a
4970
- new tenant-owned custom field. The two verbs make the value-copy choice explicit;
4971
- the host independently intersects any submitted cells with this viewer's scope. */}
 
 
 
 
 
 
4972
  {onDuplicate && (
4973
- <>
4974
- <button type="button" onClick={() => { onDuplicate(false); onClose(); }}>
4975
- <MenuLabel icon="duplicate" text="Duplicate definition" />
4976
- </button>
4977
- <button type="button" onClick={() => { onDuplicate(true); onClose(); }}>
4978
- <MenuLabel icon="duplicate" text="Duplicate with permitted values" />
4979
- </button>
4980
- </>
4981
  )}
4982
  {onMoveLeft && (
4983
  <button type="button" onClick={() => { onMoveLeft(); onClose(); }}>
 
356
  * wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
357
  * no row, rather than a row that does nothing. */
358
  onEnrich?: (scope: "blank" | "always") => void;
359
+ /**
360
+ * ⭐⭐ W51-T03 / OWNER RULING R6 β€” duplicate this field as a tenant-owned custom field, through
361
+ * ONE door.
362
+ *
363
+ * β›” IT TAKES NO ARGUMENT ANY MORE, AND THE MISSING ARGUMENT IS THE FEATURE. The prop used to
364
+ * be `(copyValues: boolean) => void`, which forced this menu to state the copy choice as two
365
+ * separate verbs before the reader had even seen the column. Owner, instruction 5: *"'Duplicate
366
+ * definition' and 'Duplicate permitted value' are confusing: one button."* The choice survives
367
+ * where it can be answered β€” the host counts what the column actually holds and either opens the
368
+ * shared confirm dialog with a "Duplicate cells" toggle or, when the column holds nothing,
369
+ * duplicates at once. A menu cannot make that decision because it cannot see the rows.
370
+ */
371
+ onDuplicate?: () => void;
372
  /** Wave-5 item 10 β€” save a display format. Supplied for number/currency/formula and
373
  * date/created_time fields. */
374
  onFormat?: (format: FieldFormat) => void;
 
4976
 
4977
  <div className="cg-menu-sep" role="separator" aria-hidden />
4978
 
4979
+ {/* ⭐⭐ W51-T03 / OWNER RULING R6 + INSTRUCTION 5 β€” ONE DOOR, NOT TWO VERBS.
4980
+ W48-T17 shipped "Duplicate definition" and "Duplicate with permitted values" side by
4981
+ side, which made the reader answer a question about copy semantics before they had
4982
+ seen the column. Cloning a source-backed definition is still safe for W48-T17's
4983
+ reason (the result is a new tenant-owned custom field, and the host independently
4984
+ intersects any submitted cells with this viewer's scope) β€” what changed is WHERE the
4985
+ value question is asked. The host opens the shared confirm dialog with a "Duplicate
4986
+ cells" toggle when the column holds values, and duplicates in one click when it holds
4987
+ none: a dialog with only one possible answer is a click tax, not a safeguard. */}
4988
  {onDuplicate && (
4989
+ <button type="button" onClick={() => { onDuplicate(); onClose(); }}>
4990
+ <MenuLabel icon="duplicate" text="Duplicate field" />
4991
+ </button>
 
 
 
 
 
4992
  )}
4993
  {onMoveLeft && (
4994
  <button type="button" onClick={() => { onMoveLeft(); onClose(); }}>
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -51,6 +51,10 @@ import { useRecordStars } from "./recordStars";
51
  // noun, already both in this file β€” importing the second under its own name would have shadowed
52
  // the first and silently repainted every rating picker.
53
  import { StarIcon as RecordStarMark } from "../ui/icons";
 
 
 
 
54
  import "./rowStar.css";
55
  /* ⭐⭐ W37-T29 / CONTRACT C6 β€” E's chat panel. β›” THE DEFAULT EXPORT, NEVER `GridChatView`:
56
  E-6 says the named one is the presentational half, split out so a gate can render its in-flight
@@ -73,7 +77,7 @@ import { defaultViewConfig, headerMarksFor, useGridColumns } from "./useGridColu
73
  import { activeMeasureRuleIds, pendingMeasures, runPipeline,
74
  unresolvedConditions, useVisibleRows } from "./useVisibleRows";
75
  import { cleanPercent, computeAggNumbers, computeAggs, formatServerAgg, formatShare,
76
- groupHeaderAggs, resolveSummary, sharesTheTotal } from "./aggregations";
77
  // ⭐⭐ W50-T03 (owner instruction 1, R2) β€” THE SUMMARY BAR. A component rather than a canvas
78
  // row, because R2's choice is per COLUMN and per VIEW, and a glide cell can carry a value but
79
  // never a menu. See its header for how it borrows the canvas's own column layout.
@@ -84,7 +88,18 @@ import { useGetCellContent } from "./useGetCellContent";
84
  import { useGridSelection } from "./useGridSelection";
85
  import Toolbar from "./Toolbar";
86
  import { DatePicker } from "./DatePicker";
87
- import { FieldDeleteImpactDialog } from "../filter-kit/FieldsHidePanel";
 
 
 
 
 
 
 
 
 
 
 
88
  // W49-T17: R32's pre-delete disclosure. A static import is safe here -- nothing else in the
89
  // tree imports this component, so it joins THIS chunk rather than pinning another one open
90
  // [[tsc-cannot-see-a-broken-code-split]].
@@ -103,7 +118,7 @@ type PendingViewDelete = {
103
  };
104
  import JsonViewer from "./JsonViewer";
105
  import RecordDetail from "./RecordDetail";
106
- import ViewSidebar from "./ViewSidebar";
107
  import ColumnMenu from "./ColumnMenu";
108
  import type { ColumnMenuState } from "./ColumnMenu";
109
  import { HEADER_ICONS } from "./iconShapes";
@@ -235,6 +250,8 @@ import type {
235
  PivotResponse,
236
  PivotRefusal,
237
  PivotWindow,
 
 
238
  Row,
239
  RowHeightMode,
240
  SavedView,
@@ -1370,8 +1387,13 @@ export function foldGroups(rows: VisibleRow[], expanded: ReadonlySet<string>): V
1370
  * i.e. `field.agg` or nothing β€” so a header showed a blank where the summary bar showed a Sum,
1371
  * and R3's "the SAME summary bar as the footer" was false by construction. Both the header's
1372
  * aggregate and the footer's are recomputed here under the map, so all three rows agree.
1373
- * ⚠ The SHARE rides the HEADER ONLY. A footer is the group's subtotal sitting under its own
1374
- * rows; repeating the header's share there says the same thing twice on one screen.
 
 
 
 
 
1375
  *
1376
  * ⚠ A MULTI-VALUE group column puts one record in several buckets (`groupRows`' own rule, owner
1377
  * 2026-07-27), so those groups' counts sum to more than the view's row count and their shares
@@ -1383,9 +1405,18 @@ export function foldGroups(rows: VisibleRow[], expanded: ReadonlySet<string>): V
1383
  * it may reuse the pipeline's map instead of walking every row on every render.
1384
  */
1385
  export interface GroupAnalytics {
1386
- /** groupKey -> the HEADER's per-column string: the aggregate the bar shows, then its share. */
 
 
 
 
1387
  head: Map<string, Record<string, string>>;
1388
- /** groupKey -> the FOOTER's per-column string: the same aggregate, and no share. */
 
 
 
 
 
1389
  foot: Map<string, Record<string, string>>;
1390
  /** groupKey -> the group's ROW COUNT as a share of the view's grand row count. */
1391
  share: Map<string, string>;
@@ -1424,11 +1455,16 @@ export function groupAnalytics(
1424
  const grandRows = all.length;
1425
 
1426
  for (const [key, bucket] of buckets) {
1427
- const groupText = computeAggs(bucket, fields, summary);
 
 
 
 
 
1428
  const groupNums = computeAggNumbers(bucket, fields, summary);
1429
  out.nums.set(key, groupNums);
1430
  out.foot.set(key, groupText);
1431
- out.head.set(key, groupHeaderAggs(fields, summary, groupText, groupNums, grandNums));
1432
  /* The ROW COUNT's own share, and it rides the LABEL because the count does. The painter
1433
  draws `β–Ό <label> (<count>)` off `vr.count`, so the share sits immediately before the
1434
  count it qualifies: `β–Ό Miami 12.4% (2)`. ⚠ Two spaces, no separator glyph, and no dash
@@ -1578,13 +1614,15 @@ export function serverGroupHeaders(
1578
  for (const f of fields) {
1579
  const choice = resolveSummary(f, summary);
1580
  if (choice.agg === "none") continue;
1581
- const text = formatServerAgg(f, choice, g.aggregates[f.key]);
1582
- if (text === undefined) continue;
 
 
 
1583
  const whole = overall[f.key];
1584
- const share = sharesTheTotal(choice)
1585
- ? formatShare(g.aggregates[f.key] ?? undefined, whole ?? undefined)
1586
- : undefined;
1587
- aggs[f.key] = share === undefined ? text : `${text} ${share}`;
1588
  }
1589
  const rowShare = formatShare(g.count, totalRows);
1590
  const label = g.label || "(empty)";
@@ -1625,6 +1663,55 @@ interface CustomerGridProps {
1625
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
1626
  /** Source record withheld from an editable picker over its own database. */
1627
  embeddedExcludeRecordId?: number;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1628
  }
1629
 
1630
  /** Exact client mirror of core.user_tables.is_linkable_target. */
@@ -1779,6 +1866,25 @@ function stampViewWrite<T extends HostEvent>(
1779
  return Object.keys(extra).length ? ({ ...event, ...extra } as T) : event;
1780
  }
1781
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1782
  function CustomerGrid(props: CustomerGridProps = {}) {
1783
  const scope = props.scope ?? "customer";
1784
  const queryRoute = isQueryPreviewRoute();
@@ -1839,8 +1945,29 @@ function CustomerGridSurface({
1839
  embeddedSelectedIds = [],
1840
  onEmbeddedSelectionChange,
1841
  embeddedExcludeRecordId,
 
 
 
 
1842
  }: CustomerGridProps = {}) {
1843
  const isQueryPreview = queryBinding !== undefined;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1844
  /**
1845
  * ⭐⭐ W35-T23 (owner item 4 / R2) β€” **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.**
1846
  *
@@ -1889,6 +2016,10 @@ function CustomerGridSurface({
1889
  includeWorkspace: hostWorkspace,
1890
  // `writable: false` blocks `patchOverlay`, i.e. every cell edit. R2 wants them in Query.
1891
  writable: !embedded,
 
 
 
 
1892
  });
1893
  const payloadFields = useMemo(() => {
1894
  if (!payload?.workspace?.auditTimestamps || payloadFieldsRaw.some((field) => field.key === "_updated"))
@@ -2223,6 +2354,18 @@ function CustomerGridSurface({
2223
  const [timeSeriesDetailPids, setTimeSeriesDetailPids] = useState<number[] | null>(null);
2224
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
2225
  const [columnDelete, setColumnDelete] = useState<{ field: Field; confirm: () => void } | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
2226
  const [viewActionsAnchor, setViewActionsAnchor] = useState<HTMLElement | null>(null);
2227
  /** Open choice list for a `select` / `user` cell β€” see onCellClicked. */
2228
  const [picker, setPicker] = useState<{
@@ -2541,10 +2684,33 @@ function CustomerGridSurface({
2541
  * copy (`table_store.save_active_view`), so "where the user left off survives a new browser"
2542
  * β€” the 2026-07-31 owner item β€” is served by rung 2 and by rung 3 when the store had nothing.
2543
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2544
  const requested = resolveActiveView(
2545
  { id: local?.activeViewId, at: local?.activeViewAt },
2546
  payload.workspace?.activeViewId, ALL_VIEW_ID, Date.now());
2547
- const active = initialViews.find((view) => view.id === requested) ?? initialViews[0];
 
 
 
 
 
 
 
 
 
2548
  /**
2549
  * ⭐ W36-T03 β€” seed the bound's two refs from what we just RESOLVED, and stamp nothing here.
2550
  * β›” Stamping at init would refresh the window on every mount, so a browser that reloads
@@ -2620,6 +2786,26 @@ function CustomerGridSurface({
2620
  activeViewAtRef.current = Date.now();
2621
  }, [workspaceReady, hostWorkspace, activeViewId]);
2622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2623
  useEffect(() => {
2624
  // β›” `hostWorkspace`, and a Query surface is deliberately EXCLUDED (W35-T23 + T25). Its spec
2625
  // lives on the server, which is the only copy β€” writing a second one here would be a store
@@ -3670,9 +3856,19 @@ function CustomerGridSurface({
3670
  if (!field) return [];
3671
  const choice = resolveSummary(field, summaryMap);
3672
  if (choice.agg === "none") return [];
 
 
 
 
 
 
 
 
 
 
3673
  return [{
3674
  colId: field.key,
3675
- agg: choice.agg,
3676
  ...(choice.agg === "percentile" ? { p: cleanPercent(choice.p) } : {}),
3677
  }];
3678
  }),
@@ -3689,6 +3885,13 @@ function CustomerGridSurface({
3689
  filters: config.filters,
3690
  filterConj: config.filterConj,
3691
  search,
 
 
 
 
 
 
 
3692
  /* ⭐⭐ W50-T04 / C1 β€” THE GROUPING RIDES THE SAME REQUEST. A windowed table cannot bucket
3693
  the rows in hand (they are one page), so the ONLY honest source of its group aggregates
3694
  is the server folding the whole predicate. Absent `groupBy` this is the table-wide
@@ -3708,7 +3911,10 @@ function CustomerGridSurface({
3708
  // ⚠ W50-T04 β€” `config.groupBy` JOINS THE DEPS. The grouping is part of the question now, so
3709
  // re-grouping must re-ask; without it the groups on screen would keep describing the column
3710
  // the reader has just moved off, which is a wrong answer rather than a missing one.
3711
- }, [serverWindowed, topic.key, summaryRequestKey, windowPredicate, config.groupBy]);
 
 
 
3712
  /**
3713
  * What the bar actually paints: C1's numbers when the server answered, this browser's fold
3714
  * over the loaded window otherwise β€” and the two are never mixed within one paint, because a
@@ -3721,7 +3927,11 @@ function CustomerGridSurface({
3721
  for (const col of visibleCols) {
3722
  const field = fieldByKey.get(String(col.id));
3723
  if (!field) continue;
 
 
 
3724
  const text = formatServerAgg(field, resolveSummary(field, summaryMap),
 
3725
  serverAggs.aggregates[field.key]);
3726
  if (text !== undefined) out[field.key] = text;
3727
  }
@@ -4509,6 +4719,36 @@ function CustomerGridSurface({
4509
  [overlayEdits, rowByPid]
4510
  );
4511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4512
  const recordCells = useCallback(
4513
  (changes: CellChange[], label: string) => {
4514
  if (applyingUndo.current || changes.length === 0) return;
@@ -5785,10 +6025,13 @@ function CustomerGridSurface({
5785
  const row = displayRows[cell[1]];
5786
  const column = visibleCols[cell[0]];
5787
  const field = column ? fieldByKey.get(column.id!) : undefined;
 
 
 
5788
  if (row?.kind === "data" && field && !canEditField(field))
5789
- setDetailPid(row.record.pid);
5790
  },
5791
- [displayRows, visibleCols, fieldByKey, canEditField]
5792
  );
5793
  const onCellEdited = useCallback(
5794
  (cell: Item, value: EditableGridCell) => {
@@ -5939,6 +6182,64 @@ function CustomerGridSurface({
5939
  },
5940
  [groupSummaryOn, visibleCols, onGroupSortColumn, openHeaderMenu]
5941
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5942
  /**
5943
  * ⭐ W40-T23 / owner item 6 β€” ONE door for "open the picker on the cell the keyboard is on".
5944
  *
@@ -8222,6 +8523,33 @@ function CustomerGridSurface({
8222
  [fieldByKey, saveField, scope, isUserTable]
8223
  );
8224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8225
  /**
8226
  * W48-T17 / R8 β€” Duplicate any non-identity field as a tenant-owned custom field. The menu
8227
  * makes the value-copy choice explicit; when chosen, this sends only the values already in the
@@ -8764,7 +9092,12 @@ function CustomerGridSurface({
8764
  // `detailPid` change (clicking a card) re-renders the modal and skips the board entirely β€”
8765
  // which is the whole of "laggy record-open". Everything else KanbanView takes was already
8766
  // stable: `modeDataRows`/`fieldByKey` are useMemos, `kanbanField` is a reference INTO the
8767
- // `stackFieldChoices` useMemo, and `onOpen={setDetailPid}` is a setState identity.
 
 
 
 
 
8768
  const kanbanCardKeys = useMemo(
8769
  () =>
8770
  kanbanField
@@ -9709,6 +10042,25 @@ function CustomerGridSurface({
9709
  );
9710
  return;
9711
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9712
  stampFolder((p) => ({
9713
  ...p,
9714
  moved: { ...p.moved, [viewId]: { at: Date.now(), folderId } },
@@ -9796,6 +10148,35 @@ function CustomerGridSurface({
9796
  ) : (
9797
  <>
9798
  <div className="cg-drawer-launchers" aria-label="Workspace details">{isUserTable && <button type="button" className="cg-btn" aria-expanded={workspaceDrawer === "history"} onClick={() => setWorkspaceDrawer((open) => open === "history" ? null : "history")}>History</button>}</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9799
  <Toolbar
9800
  manager={true}
9801
  nouns={topic.nouns}
@@ -9955,6 +10336,7 @@ function CustomerGridSurface({
9955
  notesUnread={notesUnread.length}
9956
  onNotes={() => setWorkspaceDrawer((open) => (open === "notes" ? null : "notes"))}
9957
  />
 
9958
  {/* ⭐ R11's SECOND ROW β€” live, on the pivoted database. It renders only once the pivot has
9959
  actually been SERVED, which is the house posture for a control whose other half may
9960
  not be wired yet: absent beats present-and-inert. A control row over a database whose
@@ -10264,7 +10646,12 @@ function CustomerGridSurface({
10264
  drawCell={drawGridCell}
10265
  onHeaderMenuClick={(column, bounds) => openHeaderMenu(column, bounds)}
10266
  onHeaderClicked={onHeaderClicked}
10267
- onHeaderContextMenu={onHeaderClicked}
 
 
 
 
 
10268
  onKeyDown={onGridKeyDown}
10269
  maxColumnWidth={600}
10270
  getCellsForSelection={true}
@@ -10382,7 +10769,7 @@ function CustomerGridSurface({
10382
  fieldByKey={fieldByKey}
10383
  visibleKeys={visibleKeys}
10384
  titleKey={lockedKey}
10385
- onOpen={setDetailPid}
10386
  onToggleGroup={onListToggleGroup}
10387
  />
10388
  )}
@@ -10400,7 +10787,7 @@ function CustomerGridSurface({
10400
  /* wave17 item 9 / R4 β€” the surface the day-grain measure channel is asked
10401
  about (C-CAL). The server refuses `product` in words. */
10402
  scope={scope}
10403
- onOpen={setDetailPid}
10404
  /* owner item 3 β€” the summary month, so the view menu's Export can carry it. */
10405
  onSheet={onCalSheet}
10406
  />
@@ -10415,7 +10802,7 @@ function CustomerGridSurface({
10415
  fields={fields}
10416
  visibleKeys={visibleKeys}
10417
  titleKey={lockedKey}
10418
- onOpen={setDetailPid}
10419
  />
10420
  )}
10421
  {displayMode === "timeline" &&
@@ -10426,7 +10813,7 @@ function CustomerGridSurface({
10426
  visibleKeys={visibleKeys}
10427
  field={calendarField}
10428
  titleKey={lockedKey}
10429
- onOpen={setDetailPid}
10430
  />
10431
  ) : (
10432
  <div className="cg-mode-empty">
@@ -10445,7 +10832,7 @@ function CustomerGridSurface({
10445
  readOnlyReason={kanbanReason}
10446
  clamped={displaySpec?.kanbanClamp !== false}
10447
  onMove={onKanbanMove}
10448
- onOpen={setDetailPid}
10449
  /* Item 12 (R8). ⚠ A `useCallback` or the literal `null` β€” NEVER an inline arrow.
10450
  KanbanView is memo'd and every prop here is referentially stable on purpose
10451
  (see the note above `kanbanCardKeys`); a fresh closure each render undoes that
@@ -10481,7 +10868,7 @@ function CustomerGridSurface({
10481
  canBind={!!activeView && mayEditView(activeView, viewer)}
10482
  onSpec={setSwipeSpec}
10483
  onSwipe={onSwipeDecide}
10484
- onOpen={setDetailPid}
10485
  /* ⭐⭐ WAVE-29 T26 (owner R9) β€” the card renders the RECORD, so the deck now gets
10486
  what the modal gets: the view's visible fields (not the three-key kanban
10487
  summary), this surface's scope so comments can key on it, and the document
@@ -10686,7 +11073,7 @@ function CustomerGridSurface({
10686
  allRows={scopedRows}
10687
  selectedPids={selectedPids}
10688
  onSelectPids={selectPids}
10689
- onOpen={setDetailPid}
10690
  />
10691
  )}
10692
  {/* Owner item 19 β€” the hover-only Expand. The COUNTERPART to item 17: the single
@@ -10713,7 +11100,7 @@ function CustomerGridSurface({
10713
  title="Expand record"
10714
  aria-label="Expand record"
10715
  onMouseDown={(event) => event.preventDefault()}
10716
- onClick={() => setDetailPid(expandAt.pid)}
10717
  >
10718
  {/* Airtable's expand mark: two corner brackets pushing apart. SVG, never a
10719
  glyph β€” no emojis in this UI, and a unicode arrow renders differently on
@@ -10900,7 +11287,12 @@ function CustomerGridSurface({
10900
  (delArmed && delArmed === [...selectedPids].join(",") ? " is-armed" : "")
10901
  }
10902
  style={ONE_LINE}
10903
- onClick={() => void deleteRecords([...selectedPids])}
 
 
 
 
 
10904
  >
10905
  {delArmed && delArmed === [...selectedPids].join(",")
10906
  ? "Delete anyway?"
@@ -11254,22 +11646,33 @@ function CustomerGridSurface({
11254
  : /**
11255
  * ⭐⭐ 2026-08-10 β€” the DEFINITION stratum's own delete.
11256
  *
11257
- * β›” NARROWED TO THE THREE KINDS THAT HOLD NO DATA OF THEIR OWN, which is
11258
- * `preset_editable`'s argument reused rather than a new one: a link, a rollup and
11259
- * a formula are all QUESTIONS asked of other cells, so removing one destroys no
11260
- * measurement and can be undone by asking it again. Every other definition column
11261
- * on a `ut_*` database holds real values, and offering a type-blind Delete over
11262
- * those is a destructive widening this change has no mandate for (booked as
11263
- * D-114). It is also exactly the three kinds `createField` now routes to the
11264
- * definition β€” so what a user can make here, a user can unmake.
 
 
 
 
 
 
 
 
 
 
 
11265
  * ⚠ `schemaLocked` still gates the button inside ColumnMenu, so a pre-set link
11266
- * never shows it; a pre-set ROLLUP does, by the same owner ruling that made it
11267
- * editable, and the confirm says it will come back.
11268
  */
11269
  isUserTable &&
11270
  !menuField.custom &&
11271
  menuField.key !== lockedKey &&
11272
- (menuField.type === "link" || menuField.type === "rollup" ||
 
11273
  menuField.type === "formula")
11274
  ? () => {
11275
  setColumnDelete({ field: menuField, confirm: () => deleteDefinitionField(menuField.key) });
@@ -11295,8 +11698,20 @@ function CustomerGridSurface({
11295
  onDuplicate={
11296
  // R8: any non-identity field may become a tenant custom field. The identity
11297
  // column exposes no duplicate affordance, and the server names that refusal too.
 
 
 
 
 
 
 
 
11298
  menuField.key !== lockedKey
11299
- ? (copyValues) => duplicateField(menuField, copyValues)
 
 
 
 
11300
  : undefined
11301
  }
11302
  onMoveLeft={
@@ -11427,15 +11842,68 @@ function CustomerGridSurface({
11427
  locked identity column (only its position matters β€” the create form never shows it).
11428
  The action/pane handlers below are unreachable in this mode (create-only; Cancel
11429
  closes), supplied inert to satisfy the surface. */}
11430
- {columnDelete && <FieldDeleteImpactDialog field={columnDelete.field} onCancel={() => setColumnDelete(null)} onConfirm={() => { columnDelete.confirm(); setColumnDelete(null); }} />}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11431
  {pendingViewDelete && (
11432
- <ViewDeleteDisclosure
11433
- viewName={pendingViewDelete.name}
11434
- dependents={pendingViewDelete.dependents}
11435
- share={pendingViewDelete.share}
11436
- loading={pendingViewDelete.loading}
11437
- unanswered={pendingViewDelete.unanswered}
11438
- error={pendingViewDelete.error}
 
 
 
 
 
 
 
 
 
11439
  onCancel={() => setPendingViewDelete(null)}
11440
  onConfirm={() => {
11441
  const id = pendingViewDelete.id;
@@ -11444,6 +11912,25 @@ function CustomerGridSurface({
11444
  }}
11445
  />
11446
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11447
 
11448
  {plusMenu && fieldByKey.get(lockedKey) && (
11449
  <ColumnMenu
 
51
  // noun, already both in this file β€” importing the second under its own name would have shadowed
52
  // the first and silently repainted every rating picker.
53
  import { StarIcon as RecordStarMark } from "../ui/icons";
54
+ /* ⭐ W51-T06 clause 5 β€” THE SHARED LOCK GLYPH, never a second drawing of one. DESIGN.md section
55
+ 4 ("THE THREE LOCKS") gives the product ONE mark, which is exactly why whatever wears it must
56
+ say in words WHICH lock applies: "the marks are indistinguishable otherwise". */
57
+ import { LockMark } from "./icons";
58
  import "./rowStar.css";
59
  /* ⭐⭐ W37-T29 / CONTRACT C6 β€” E's chat panel. β›” THE DEFAULT EXPORT, NEVER `GridChatView`:
60
  E-6 says the named one is the presentational half, split out so a gate can render its in-flight
 
77
  import { activeMeasureRuleIds, pendingMeasures, runPipeline,
78
  unresolvedConditions, useVisibleRows } from "./useVisibleRows";
79
  import { cleanPercent, computeAggNumbers, computeAggs, formatServerAgg, formatShare,
80
+ resolveSummary, sharesTheTotal } from "./aggregations";
81
  // ⭐⭐ W50-T03 (owner instruction 1, R2) β€” THE SUMMARY BAR. A component rather than a canvas
82
  // row, because R2's choice is per COLUMN and per VIEW, and a glide cell can carry a value but
83
  // never a menu. See its header for how it borrows the canvas's own column layout.
 
88
  import { useGridSelection } from "./useGridSelection";
89
  import Toolbar from "./Toolbar";
90
  import { DatePicker } from "./DatePicker";
91
+ /**
92
+ * ⭐⭐ W51-T03 / OWNER RULING R6 + CONTRACT C8 β€” THE ONE CONFIRM DIALOG, for every destructive
93
+ * act this grid can start: a field delete, a view delete and a record delete, plus the duplicate
94
+ * dialog which is the same shell with a primary button.
95
+ *
96
+ * β›” IMPORTED FROM THE MODULE, NOT THE `ui` BARREL. `ui/index.ts` does not re-export either of
97
+ * these (measured), so `from "../ui"` does not compile.
98
+ * β›” AND THIS REPLACES `FieldDeleteImpactDialog`, which was this file's field-delete door and
99
+ * still lives in `filter-kit/FieldsHidePanel.tsx` for the Fields manager's own row. Two confirm
100
+ * shapes for one act is what R6 retires; the manager's copy is another lane's fence.
101
+ */
102
+ import { ConfirmDialog, DialogToggle } from "../ui/ConfirmDialog";
103
  // W49-T17: R32's pre-delete disclosure. A static import is safe here -- nothing else in the
104
  // tree imports this component, so it joins THIS chunk rather than pinning another one open
105
  // [[tsc-cannot-see-a-broken-code-split]].
 
118
  };
119
  import JsonViewer from "./JsonViewer";
120
  import RecordDetail from "./RecordDetail";
121
+ import ViewSidebar, { viewMoveRefusal } from "./ViewSidebar";
122
  import ColumnMenu from "./ColumnMenu";
123
  import type { ColumnMenuState } from "./ColumnMenu";
124
  import { HEADER_ICONS } from "./iconShapes";
 
250
  PivotResponse,
251
  PivotRefusal,
252
  PivotWindow,
253
+ RelatedPin,
254
+ RelatedVia,
255
  Row,
256
  RowHeightMode,
257
  SavedView,
 
1387
  * i.e. `field.agg` or nothing β€” so a header showed a blank where the summary bar showed a Sum,
1388
  * and R3's "the SAME summary bar as the footer" was false by construction. Both the header's
1389
  * aggregate and the footer's are recomputed here under the map, so all three rows agree.
1390
+ * ⭐⭐ W51-T02 / R3 β€” **AND THE HEADER AND THE FOOTER NOW CARRY THE SAME ONE VALUE.** W50-T04's
1391
+ * note here said the share rode the header only, because the header composed an aggregate AND an
1392
+ * automatic share while the footer showed the aggregate alone. R3 removed the composition, so
1393
+ * both rows paint the picker's single choice; a reader who wants a share picks "% of total" and
1394
+ * gets it in both places, which is the ruling's "the picker OWNS group headers and the bar".
1395
+ * ⚠ The group's ROW-COUNT share still rides the header's LABEL alone (`out.share` below) β€” that
1396
+ * is a property of the grouping, not of a column, and a footer has no label to carry it.
1397
  *
1398
  * ⚠ A MULTI-VALUE group column puts one record in several buckets (`groupRows`' own rule, owner
1399
  * 2026-07-27), so those groups' counts sum to more than the view's row count and their shares
 
1405
  * it may reuse the pipeline's map instead of walking every row on every render.
1406
  */
1407
  export interface GroupAnalytics {
1408
+ /**
1409
+ * groupKey -> the HEADER's per-column string: ⭐ W51-T02 / R3 β€” ONE VALUE PER COLUMN, and it
1410
+ * is the bottom bar's picker's choice, "% of total" included. Under W50-T04 this map carried
1411
+ * the aggregate AND an automatic share; instruction 1 is that second number.
1412
+ */
1413
  head: Map<string, Record<string, string>>;
1414
+ /**
1415
+ * groupKey -> the FOOTER's per-column string. ⚠ THE SAME CONTENT AS `head` SINCE W51-T02, and
1416
+ * the two maps are kept apart anyway: R3 makes a header and a footer say the same thing today,
1417
+ * and folding them into one field would make the next divergence a refactor rather than an
1418
+ * assignment. `applyGroupAnalytics` stamps each onto its own row kind.
1419
+ */
1420
  foot: Map<string, Record<string, string>>;
1421
  /** groupKey -> the group's ROW COUNT as a share of the view's grand row count. */
1422
  share: Map<string, string>;
 
1455
  const grandRows = all.length;
1456
 
1457
  for (const [key, bucket] of buckets) {
1458
+ /* ⭐⭐ W51-T02 / R3 β€” THE VIEW'S TOTALS RIDE INTO THE SAME FOLD, AND THAT IS THE WHOLE
1459
+ MECHANISM. W50-T04 folded the bucket, folded it again raw, then composed an automatic
1460
+ second number on top. R3 retired the composition: "% of total" is now one of the picker's
1461
+ choices, so a share is produced BY the fold rather than beside it, and `grandNums` is the
1462
+ denominator it divides by. One value per column, and it is the reader's own choice. */
1463
+ const groupText = computeAggs(bucket, fields, summary, grandNums);
1464
  const groupNums = computeAggNumbers(bucket, fields, summary);
1465
  out.nums.set(key, groupNums);
1466
  out.foot.set(key, groupText);
1467
+ out.head.set(key, groupText);
1468
  /* The ROW COUNT's own share, and it rides the LABEL because the count does. The painter
1469
  draws `β–Ό <label> (<count>)` off `vr.count`, so the share sits immediately before the
1470
  count it qualifies: `β–Ό Miami 12.4% (2)`. ⚠ Two spaces, no separator glyph, and no dash
 
1614
  for (const f of fields) {
1615
  const choice = resolveSummary(f, summary);
1616
  if (choice.agg === "none") continue;
1617
+ /* ⭐⭐ W51-T02 / R3 β€” ONE VALUE, THE PICKER'S CHOICE, AND THE DENOMINATOR RIDES IN WITH IT.
1618
+ W50-T04 painted `${text} ${share}` here, which is instruction 1's second number on the
1619
+ windowed path. A share is now a CHOICE: `summaryRequest` asks the server for its base
1620
+ (a numeric column's `sum`, anything else's `count`) under the same colId, and
1621
+ `formatServerAgg` divides that by C1's top-level answer for the column. */
1622
  const whole = overall[f.key];
1623
+ const text = formatServerAgg(f, choice, g.aggregates[f.key], whole);
1624
+ if (text === undefined) continue;
1625
+ aggs[f.key] = text;
 
1626
  }
1627
  const rowShare = formatShare(g.count, totalRows);
1628
  const label = g.label || "(empty)";
 
1663
  onEmbeddedSelectionChange?: (recordIds: number[]) => void;
1664
  /** Source record withheld from an editable picker over its own database. */
1665
  embeddedExcludeRecordId?: number;
1666
+ /**
1667
+ * ⭐⭐ W51-T06 Β· RULING R5 Β· CONTRACT C6 β€” **THE THIRD MODE.**
1668
+ *
1669
+ * There are three now, and they are not variations of each other:
1670
+ *
1671
+ * | | rail | fetch | rows |
1672
+ * |---|---|---|---|
1673
+ * | normal | shown | server-windowed | all |
1674
+ * | `embedded` | HIDDEN (`hostViews = []`) | the WHOLE table | filtered CLIENT-side |
1675
+ * | **`related`** | **SHOWN, the target's own** | **server, PRE-FILTERED** | **only linked** |
1676
+ *
1677
+ * β›”β›” `related` IS NOT ROUTED THROUGH `embedded`, AND THAT IS THE WHOLE TICKET. `embedded`
1678
+ * keeps hiding the rail and keeps fetching whole tables; R5 asks for the OTHER DATABASE'S OWN
1679
+ * SAVED VIEWS, its rail included, with the record pinned. So this mode leaves every
1680
+ * `embedded` guard alone and narrows the READ instead.
1681
+ *
1682
+ * `label` is the pinned record's NAME and is display-only: the chip reads "Linked to
1683
+ * <label>". β›” It never reaches the wire (`RelatedPin` has no `label`) and it is never
1684
+ * serialised into a saved view β€” see `pinnedChip` below for why that one is load-bearing.
1685
+ */
1686
+ related?: { table: string; record: number; via: RelatedVia; label: string };
1687
+ /**
1688
+ * ⭐ W51-T06 clause 9 β€” a row click NAVIGATES the record view instead of opening this grid's
1689
+ * own drawer.
1690
+ *
1691
+ * ⚠ THE SIGNATURE IS A SUPERSET OF THE TICKET'S `onOpenRecord?(pid, table)`, and the two
1692
+ * extra members are declared rather than smuggled. The host (`RecordDetail`) has no way to
1693
+ * resolve a row of ANOTHER database on its own: `routes_tables.table_rows` takes no
1694
+ * predicate, and a filter leaf naming `pid` is dropped on the way in (`filter_sql` compiles
1695
+ * against DECLARED columns), which is a filter that silently matches everything. This grid
1696
+ * already holds the row and the field contract, so it hands them over rather than making the
1697
+ * caller invent a read that cannot narrow. A caller that wants only the first two arguments
1698
+ * still typechecks.
1699
+ */
1700
+ onOpenRecord?: (pid: number, table: string, record?: Row, fields?: Field[]) => void;
1701
+ /**
1702
+ * ⭐ W51-T06 clause 10 β€” the view this surface should OPEN ON, remembered per person and per
1703
+ * TAB by the host in `localStorage`.
1704
+ *
1705
+ * β›” PER TAB, NOT PER DATABASE, WHICH IS WHY IT IS A PROP AND NOT THIS FILE'S OWN
1706
+ * `readLocal(storageKey)`. R2 gives two links between the same pair two tabs, so two tabs can
1707
+ * target one database; a memory keyed by `storageKey` would make them share one answer and
1708
+ * each would reopen on the other's view.
1709
+ * β›” AND NOTHING NEW IS STORED SERVER-SIDE (R5's load-bearing clause): the view itself is the
1710
+ * target database's own saved view, and what is remembered is only WHICH of them was last
1711
+ * open, in this browser.
1712
+ */
1713
+ relatedViewId?: string;
1714
+ onRelatedViewChange?: (viewId: string) => void;
1715
  }
1716
 
1717
  /** Exact client mirror of core.user_tables.is_linkable_target. */
 
1866
  return Object.keys(extra).length ? ({ ...event, ...extra } as T) : event;
1867
  }
1868
 
1869
+ /**
1870
+ * ⭐⭐ W51-T03 Β· D-217 β€” WHAT A FIELD DELETE COSTS, IN ONE LINE, AND NEVER A BARE ZERO.
1871
+ *
1872
+ * β›” `null` IS NOT "NONE", IT IS "NOT HELD HERE", and the distinction is the whole defect.
1873
+ * `GET /tables/{key}/footprint` answers `rows: 0` for a read-through database, and a server
1874
+ * windowed grid has loaded a PAGE rather than a table. Rendering either as "0 cells will be
1875
+ * cleared" beside a red button, over a source with roughly 975,000 rows behind it, is a confident
1876
+ * lie; a dialog that says it does not know is merely unhelpful. Same law as C1's "no server
1877
+ * answer, no denominator".
1878
+ *
1879
+ * ⚠ A PURE FUNCTION OF ONE NUMBER, so the sentence can be read (and mutated) by a source scan
1880
+ * without standing up a grid. The counting itself is `columnCellValues` inside the component,
1881
+ * which is the only place that can see the rows.
1882
+ */
1883
+ function fieldDeleteImpactLine(cells: number | null): string {
1884
+ if (cells === null) return "The count is not held for this database.";
1885
+ return `${cells.toLocaleString()} cell${cells === 1 ? "" : "s"} will be cleared.`;
1886
+ }
1887
+
1888
  function CustomerGrid(props: CustomerGridProps = {}) {
1889
  const scope = props.scope ?? "customer";
1890
  const queryRoute = isQueryPreviewRoute();
 
1945
  embeddedSelectedIds = [],
1946
  onEmbeddedSelectionChange,
1947
  embeddedExcludeRecordId,
1948
+ related,
1949
+ onOpenRecord,
1950
+ relatedViewId,
1951
+ onRelatedViewChange,
1952
  }: CustomerGridProps = {}) {
1953
  const isQueryPreview = queryBinding !== undefined;
1954
+ /**
1955
+ * ⭐⭐ W51-T06 / C6 β€” THE WIRE HALF OF `related`, WITHOUT ITS DISPLAY HALF.
1956
+ *
1957
+ * β›” `label` IS STRIPPED HERE, ON PURPOSE. `RelatedPin` is `{table, record, via}` and nothing
1958
+ * else, and the pin is part of the rows path (`windowRowsPath`) and therefore of the rows
1959
+ * CACHE KEY. Letting the record's NAME ride along would fork that key on a rename: two reads
1960
+ * of one edge, both correct, one of them paid for twice.
1961
+ * ⚠ Serialised-then-parsed so the object's IDENTITY is stable across renders. `useCustomerData`
1962
+ * takes it as an effect dependency and a fresh object per render is an infinite refetch.
1963
+ */
1964
+ const relatedPinKey = related
1965
+ ? JSON.stringify({ table: related.table, record: related.record, via: related.via })
1966
+ : "";
1967
+ const relatedPin = useMemo<RelatedPin | null>(
1968
+ () => (relatedPinKey ? (JSON.parse(relatedPinKey) as RelatedPin) : null),
1969
+ [relatedPinKey]
1970
+ );
1971
  /**
1972
  * ⭐⭐ W35-T23 (owner item 4 / R2) β€” **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.**
1973
  *
 
2016
  includeWorkspace: hostWorkspace,
2017
  // `writable: false` blocks `patchOverlay`, i.e. every cell edit. R2 wants them in Query.
2018
  writable: !embedded,
2019
+ /* ⭐⭐ W51-T06 / C6 / R5 β€” THE PINNED READ. Not a fourth flag beside the three above: those
2020
+ three answer "may this surface write / whose workspace is this / may cells be edited",
2021
+ and all three keep their normal answers here. What `related` changes is the READ. */
2022
+ related: relatedPin,
2023
  });
2024
  const payloadFields = useMemo(() => {
2025
  if (!payload?.workspace?.auditTimestamps || payloadFieldsRaw.some((field) => field.key === "_updated"))
 
2354
  const [timeSeriesDetailPids, setTimeSeriesDetailPids] = useState<number[] | null>(null);
2355
  const [columnMenu, setColumnMenu] = useState<ColumnMenuState | null>(null);
2356
  const [columnDelete, setColumnDelete] = useState<{ field: Field; confirm: () => void } | null>(null);
2357
+ /**
2358
+ * ⭐⭐ W51-T03 / INSTRUCTION 5 β€” THE DUPLICATE QUESTION, ASKED ONCE AND ONLY WHEN IT HAS TWO
2359
+ * ANSWERS. `copyValues` lives here rather than inside the dialog because it IS the payload
2360
+ * field: whatever this holds when the primary button is pressed is what `field_duplicate`
2361
+ * carries. A toggle that owned its own state would let the dialog show "on" while the event
2362
+ * said otherwise, which is the failure a screenshot cannot see.
2363
+ */
2364
+ const [fieldDuplicate, setFieldDuplicate] =
2365
+ useState<{ field: Field; copyValues: boolean } | null>(null);
2366
+ /** ⭐ W51-T03 / R6 β€” the selection bar's delete, pending its one confirm dialog. The pids are
2367
+ * captured at click time, so re-selecting behind the dialog cannot widen what it deletes. */
2368
+ const [recordDelete, setRecordDelete] = useState<number[] | null>(null);
2369
  const [viewActionsAnchor, setViewActionsAnchor] = useState<HTMLElement | null>(null);
2370
  /** Open choice list for a `select` / `user` cell β€” see onCellClicked. */
2371
  const [picker, setPicker] = useState<{
 
2684
  * copy (`table_store.save_active_view`), so "where the user left off survives a new browser"
2685
  * β€” the 2026-07-31 owner item β€” is served by rung 2 and by rung 3 when the store had nothing.
2686
  */
2687
+ /**
2688
+ * ⭐⭐ W51-T06 CLAUSE 10 β€” A RELATED TAB OPENS ON THE VIEW **THIS TAB** WAS LAST LEFT ON.
2689
+ *
2690
+ * β›” IT OVERRIDES THE THREE-RUNG RESOLUTION ABOVE, DELIBERATELY, AND ONLY IN THIS MODE.
2691
+ * Those rungs answer "where did this PERSON leave this DATABASE" β€” the right question for
2692
+ * the Data module and the wrong one here: R2 gives two links between the same pair two
2693
+ * tabs, so two tabs can target one database and a per-database memory would make each one
2694
+ * reopen on the other's view. The host (`RecordDetail`) keys the memory by EDGE and hands
2695
+ * the answer down; this is the one place it can be honoured, because it has to be resolved
2696
+ * against `initialViews` like every other rung (a remembered view that has since been
2697
+ * deleted falls through to `initialViews[0]` rather than showing an empty grid).
2698
+ * β›” AND NOTHING NEW IS STORED (R5): the memory is `localStorage`, per person, per browser.
2699
+ * No server record learns which tab anybody last looked at.
2700
+ */
2701
  const requested = resolveActiveView(
2702
  { id: local?.activeViewId, at: local?.activeViewAt },
2703
  payload.workspace?.activeViewId, ALL_VIEW_ID, Date.now());
2704
+ /**
2705
+ * β›” THE THREE-RUNG RESOLUTION ABOVE IS LEFT EXACTLY AS IT WAS, AND THE OVERRIDE IS A
2706
+ * SEPARATE LINE, WHICH IS NOT A STYLE CHOICE. `_test/gridUx.test.ts` pins those three lines
2707
+ * as SOURCE TEXT (`T01_PINS`, "W36-T03's BOUNDED view preference"), and that file is in no
2708
+ * lane's fence this wave. Folding the override into the expression reds the node suite,
2709
+ * which in this gate SKIPS all 72 compiled-artifact controls with it β€” one ticket's
2710
+ * convenience blinding a whole battery [[a-relabel-ruling-is-a-repo-wide-gate-grep]].
2711
+ */
2712
+ const wanted = related && relatedViewId ? relatedViewId : requested;
2713
+ const active = initialViews.find((view) => view.id === wanted) ?? initialViews[0];
2714
  /**
2715
  * ⭐ W36-T03 β€” seed the bound's two refs from what we just RESOLVED, and stamp nothing here.
2716
  * β›” Stamping at init would refresh the window on every mount, so a browser that reloads
 
2786
  activeViewAtRef.current = Date.now();
2787
  }, [workspaceReady, hostWorkspace, activeViewId]);
2788
 
2789
+ /**
2790
+ * ⭐⭐ W51-T06 CLAUSE 10, THE OTHER HALF β€” TELL THE HOST WHICH VIEW THIS TAB IS ON.
2791
+ *
2792
+ * β›” A SEPARATE EFFECT, NOT A LINE ADDED TO THE ONE ABOVE, and the note on that one says why:
2793
+ * `verify_grid_ux.py` pins its neighbour's guard as immediately followed by
2794
+ * `writeLocal(storageKey`, and that gate is in no lane's fence to repair.
2795
+ * ⚠ IT REPORTS EVERY SETTLED VALUE, including the one init resolved. Reporting only user
2796
+ * MOVES would leave a tab that fell back to `initialViews[0]` (its remembered view deleted)
2797
+ * remembering the dead id forever, so the memory would never heal.
2798
+ */
2799
+ useEffect(() => {
2800
+ if (!workspaceReady || !relatedPinKey || !onRelatedViewChange) return;
2801
+ onRelatedViewChange(activeViewId);
2802
+ // ⚠ THE **KEY**, NOT THE OBJECT. `related` is rebuilt by the host on every one of its
2803
+ // renders, so depending on it would fire this on every render; the serialised key changes
2804
+ // only when the pin does. The host's callback also returns its previous state object on a
2805
+ // no-op, so even a spurious call cannot become a render loop β€” two independent brakes,
2806
+ // because either one alone is a loop the day the other is refactored away.
2807
+ }, [workspaceReady, relatedPinKey, onRelatedViewChange, activeViewId]);
2808
+
2809
  useEffect(() => {
2810
  // β›” `hostWorkspace`, and a Query surface is deliberately EXCLUDED (W35-T23 + T25). Its spec
2811
  // lives on the server, which is the only copy β€” writing a second one here would be a store
 
3856
  if (!field) return [];
3857
  const choice = resolveSummary(field, summaryMap);
3858
  if (choice.agg === "none") return [];
3859
+ /* ⭐⭐ W51-T02 / R3 β€” **`share` IS NOT A WIRE AGG, SO IT ASKS FOR ITS BASE INSTEAD.** C1's
3860
+ vocabulary is the eight names `platform/aios_grid.SUMMARY_AGGS` compiles, and no SQL
3861
+ engine has a "share of the view" aggregate: a share is a division of two of them. A
3862
+ numeric column's base is its `sum`, every other column's is the row `count` β€” the same
3863
+ rule `aggregations.ts::shareBase` applies client-side, so a table that crosses into
3864
+ read-through keeps answering the same question. The division happens on the client,
3865
+ against C1's own top-level total for the column. */
3866
+ const agg = choice.agg === "share"
3867
+ ? (isNumericFieldType(field.type) ? "sum" : "count")
3868
+ : choice.agg;
3869
  return [{
3870
  colId: field.key,
3871
+ agg,
3872
  ...(choice.agg === "percentile" ? { p: cleanPercent(choice.p) } : {}),
3873
  }];
3874
  }),
 
3885
  filters: config.filters,
3886
  filterConj: config.filterConj,
3887
  search,
3888
+ /* ⭐⭐ W51-T06 / C6 β€” THE SAME PIN THE ROWS WINDOW CARRIES, AND THIS ONE LINE IS THE HALF
3889
+ THAT GETS LEFT OUT. Wire only the rows and a related tab shows one record's rows under
3890
+ a summary bar folded over the ENTIRE database: a number that looks right, that no
3891
+ `validate()` ties to anything, and that this repo has paid for twice
3892
+ [[no-unverifiable-aggregates]]. `_compiled_read` is shared between the two doors on the
3893
+ server, so they can only pin differently if this argument is missing. */
3894
+ related: relatedPin,
3895
  /* ⭐⭐ W50-T04 / C1 β€” THE GROUPING RIDES THE SAME REQUEST. A windowed table cannot bucket
3896
  the rows in hand (they are one page), so the ONLY honest source of its group aggregates
3897
  is the server folding the whole predicate. Absent `groupBy` this is the table-wide
 
3911
  // ⚠ W50-T04 β€” `config.groupBy` JOINS THE DEPS. The grouping is part of the question now, so
3912
  // re-grouping must re-ask; without it the groups on screen would keep describing the column
3913
  // the reader has just moved off, which is a wrong answer rather than a missing one.
3914
+ // ⚠ W51-T06 β€” `relatedPin` JOINS THE DEPS for the same reason `config.groupBy` did: the pin
3915
+ // is part of the question, so moving between two tabs on one target table must re-ask. Its
3916
+ // identity is stable (see `relatedPinKey`), so this cannot loop.
3917
+ }, [serverWindowed, topic.key, summaryRequestKey, windowPredicate, config.groupBy, relatedPin]);
3918
  /**
3919
  * What the bar actually paints: C1's numbers when the server answered, this browser's fold
3920
  * over the loaded window otherwise β€” and the two are never mixed within one paint, because a
 
3927
  for (const col of visibleCols) {
3928
  const field = fieldByKey.get(String(col.id));
3929
  if (!field) continue;
3930
+ /* ⭐ W51-T02 / R3 β€” the BAR is the whole view, so under "% of total" its numerator and its
3931
+ denominator are the same server number and the cell reads 100.0%, which is the
3932
+ done-when's own sentence. Every other aggregate ignores the fourth argument. */
3933
  const text = formatServerAgg(field, resolveSummary(field, summaryMap),
3934
+ serverAggs.aggregates[field.key],
3935
  serverAggs.aggregates[field.key]);
3936
  if (text !== undefined) out[field.key] = text;
3937
  }
 
4719
  [overlayEdits, rowByPid]
4720
  );
4721
 
4722
+ /**
4723
+ * ⭐⭐ W51-T06 CLAUSE 9 β€” **THE ONE DOOR TO A RECORD, AND WHERE IT LEADS DEPENDS ON THE HOST.**
4724
+ *
4725
+ * Every row-activation path in this file used to call `setDetailPid` directly. A grid mounted
4726
+ * inside a related TAB must not open a second drawer on top of the drawer it is already
4727
+ * inside; it navigates the record view it lives in, and a back arrow returns. So the decision
4728
+ * is made ONCE, here, rather than at the eight call sites β€” which is what stops a ninth
4729
+ * arriving next wave that still opens a nested modal.
4730
+ *
4731
+ * β›” THE ROW AND THE FIELD CONTRACT TRAVEL WITH THE PID, and that is not convenience. The
4732
+ * host cannot resolve a row of another database on its own: `routes_tables.table_rows` takes
4733
+ * no predicate, and a filter leaf naming `pid` is compiled against DECLARED columns and
4734
+ * dropped on the way in β€” a filter that matches everything, i.e. every record's neighbours
4735
+ * presented as this one's. This grid is already holding the answer.
4736
+ * ⚠ The OVERLAY stratum is layered in, exactly as `detailRecord` does it: the record that
4737
+ * opens must be the record on screen, not the payload copy underneath it.
4738
+ */
4739
+ const openRecord = useCallback(
4740
+ (pid: number) => {
4741
+ if (!onOpenRecord) {
4742
+ setDetailPid(pid);
4743
+ return;
4744
+ }
4745
+ const row = rowByPid.get(pid);
4746
+ const merged = row && overlayEdits[pid] ? { ...row, ...overlayEdits[pid] } : row;
4747
+ onOpenRecord(pid, topic.key, merged, fields);
4748
+ },
4749
+ [onOpenRecord, rowByPid, overlayEdits, topic.key, fields]
4750
+ );
4751
+
4752
  const recordCells = useCallback(
4753
  (changes: CellChange[], label: string) => {
4754
  if (applyingUndo.current || changes.length === 0) return;
 
6025
  const row = displayRows[cell[1]];
6026
  const column = visibleCols[cell[0]];
6027
  const field = column ? fieldByKey.get(column.id!) : undefined;
6028
+ // ⭐ W51-T06 clause 9 β€” `openRecord`, never `setDetailPid`: inside a related tab this
6029
+ // activation navigates the record view it is mounted in rather than stacking a second
6030
+ // drawer over the one already on screen. Every row-activation path shares that decision.
6031
  if (row?.kind === "data" && field && !canEditField(field))
6032
+ openRecord(row.record.pid);
6033
  },
6034
+ [displayRows, visibleCols, fieldByKey, canEditField, openRecord]
6035
  );
6036
  const onCellEdited = useCallback(
6037
  (cell: Item, value: EditableGridCell) => {
 
6182
  },
6183
  [groupSummaryOn, visibleCols, onGroupSortColumn, openHeaderMenu]
6184
  );
6185
+ /**
6186
+ * ⭐⭐ W51-T04 / R14 β€” RIGHT-CLICKING A FIELD HEADER OPENS THAT FIELD'S COLUMN MENU, AT THE
6187
+ * POINTER.
6188
+ *
6189
+ * R14, verbatim: *"the Data grid gets a right-click on a field header that opens that field's
6190
+ * column menu; rows keep the checkbox selection."*
6191
+ *
6192
+ * ⚠ `onHeaderContextMenu` WAS ALREADY WIRED, TO `onHeaderClicked` β€” which is why this needed a
6193
+ * handler of its own rather than a one-word prop change. Three things were wrong with reusing
6194
+ * the left-click handler for the right button:
6195
+ * - in Summary mode `onHeaderClicked` REORDERS THE GROUPS (W50-T04 / R3) and never reaches
6196
+ * the menu at all, so a right-click there re-sorted the strip instead of opening anything;
6197
+ * - it returns on `event.isEdge` BEFORE calling `preventDefault()`, so a right-click on the
6198
+ * five-pixel resize strip left the BROWSER's own menu sitting over the header. glide's
6199
+ * contextmenu path does not filter `isEdge` (`data-editor.js::onContextMenu` forwards every
6200
+ * header hit), so that guard cannot come along;
6201
+ * - it anchors on `event.bounds`, the whole header cell. That is the CARET's anchor, and the
6202
+ * caret is a fixed target; a pointer is not.
6203
+ *
6204
+ * `event.preventDefault()` here is the closure glide builds over the real DOM event
6205
+ * (`data-grid.js::onContextMenuImpl` calls `ev.preventDefault()` through it), so calling it is
6206
+ * what suppresses the browser's menu. It is called FIRST and UNCONDITIONALLY: every return
6207
+ * below is a decision not to open OUR menu, never a decision to let the browser open ITS one.
6208
+ *
6209
+ * β›” `column < 0` IS THE ROW-NUMBER GUTTER, AND IT KEEPS THE CHECKBOX SELECTION. glide hands
6210
+ * this callback `args.location[0] - rowMarkerOffset`, so the marker column arrives as -1 rather
6211
+ * than as a column that happens to have no field. It opens no column menu, and because the
6212
+ * gutter's own cells are `kind: "cell"` they never reach this callback in the first place.
6213
+ *
6214
+ * THE ANCHOR IS A ZERO-SIZE RECT AT THE POINTER, handed to the SAME `openHeaderMenu` the caret
6215
+ * uses: two doors, one menu component, one state atom, one placement path. `event.bounds` is in
6216
+ * VIEWPORT coordinates (`getBoundsForItem` adds the canvas `rect.x`) and `localEventX` is
6217
+ * `ev.clientX - bounds.x`, so the sum is the pointer's client position β€” the same space
6218
+ * `openHeaderMenu` already writes into `ColumnMenuState.anchor`.
6219
+ *
6220
+ * ⚠ VIEWPORT CLAMPING IS WHY IT IS A RECT AND NOT A BARE POINT. `ColumnMenu` renders through
6221
+ * `AnchoredOverlay`, whose `updatePosition` puts every anchor through
6222
+ * `overlayPlacement.ts::computeOverlayPosition`: the left edge is clamped into
6223
+ * `[viewport.left + OVERLAY_MARGIN, viewport.right - OVERLAY_MARGIN - panel.width]` and the
6224
+ * panel flips ABOVE the anchor when there is no room below it. A degenerate rect is a case that
6225
+ * arithmetic already handles by construction (D-20's null anchor degrades to exactly one), so a
6226
+ * right-click at the far right or the bottom of the grid still opens a fully visible menu
6227
+ * without a second placement rule living here.
6228
+ */
6229
+ const onHeaderContextMenu = useCallback(
6230
+ (column: number, event: HeaderClickedEventArgs) => {
6231
+ event.preventDefault();
6232
+ if (column < 0) return;
6233
+ const pointerAnchor: Rectangle = {
6234
+ x: event.bounds.x + event.localEventX,
6235
+ y: event.bounds.y + event.localEventY,
6236
+ width: 0,
6237
+ height: 0,
6238
+ };
6239
+ openHeaderMenu(column, pointerAnchor);
6240
+ },
6241
+ [openHeaderMenu]
6242
+ );
6243
  /**
6244
  * ⭐ W40-T23 / owner item 6 β€” ONE door for "open the picker on the cell the keyboard is on".
6245
  *
 
8523
  [fieldByKey, saveField, scope, isUserTable]
8524
  );
8525
 
8526
+ /**
8527
+ * ⭐⭐ W51-T03 · THE ONE ANSWER TO "DOES THIS COLUMN HOLD ANYTHING", read by BOTH doors that
8528
+ * need it: the duplicate dialog (ask, or duplicate at once) and the delete dialog (how many
8529
+ * cells are cleared). Two independent blank tests for one question is how the number in the
8530
+ * body and the decision to show the body come to disagree.
8531
+ *
8532
+ * β›” `isBlankValue`, NOT `!== ""`. It is this repo's blank contract and it knows the
8533
+ * connector's own sentinel: the Odoo-derived pools write the literal `"(none)"` for a missing
8534
+ * attribute (D-394), so a naive emptiness test would report a whole column of blanks as
8535
+ * populated and copy 5,872 copies of the word "(none)" into a duplicate.
8536
+ *
8537
+ * β›” `null` MEANS THE COUNT IS NOT HELD HERE, and it is NOT zero. A server-windowed table has
8538
+ * loaded a page, not a table, so "this column is empty" is not a fact this browser has; a
8539
+ * read-through database's records belong to its connector and its footprint answers 0 for a
8540
+ * table with a million rows (D-217). Both cases ASK rather than assume, and both print the
8541
+ * sentence rather than a number.
8542
+ */
8543
+ const columnCellValues = useCallback(
8544
+ (key: string): number | null => {
8545
+ if (serverWindowed || !recordsMutable) return null;
8546
+ let held = 0;
8547
+ for (const row of computedRows) if (!isBlankValue(row[key])) held += 1;
8548
+ return held;
8549
+ },
8550
+ [serverWindowed, recordsMutable, computedRows]
8551
+ );
8552
+
8553
  /**
8554
  * W48-T17 / R8 β€” Duplicate any non-identity field as a tenant-owned custom field. The menu
8555
  * makes the value-copy choice explicit; when chosen, this sends only the values already in the
 
9092
  // `detailPid` change (clicking a card) re-renders the modal and skips the board entirely β€”
9093
  // which is the whole of "laggy record-open". Everything else KanbanView takes was already
9094
  // stable: `modeDataRows`/`fieldByKey` are useMemos, `kanbanField` is a reference INTO the
9095
+ // `stackFieldChoices` useMemo, and `onOpen` was a bare setState identity.
9096
+ // ⚠ W51-T06 β€” IT IS NOW `openRecord`, A `useCallback`, AND THE STABILITY CLAIM ABOVE SURVIVES
9097
+ // ONLY BECAUSE OF ITS DEPENDENCY LIST. It re-creates when the rows, the overlay edits, the
9098
+ // fields or the host's `onOpenRecord` change β€” none of which happens on a card click, which
9099
+ // is the case this note is about. A future dependency that moves per render would put the
9100
+ // kanban board back in the lag path without anything erroring.
9101
  const kanbanCardKeys = useMemo(
9102
  () =>
9103
  kanbanField
 
10042
  );
10043
  return;
10044
  }
10045
+ /**
10046
+ * ⭐⭐ W51-T35 (R18) β€” THE READ-ONLY SHARE REFUSES HERE TOO, for exactly the reason
10047
+ * the guard above is here rather than in the rail: this callback is the single
10048
+ * choke point every filing surface reaches through, and a future caller that
10049
+ * forgot the rail's own check would otherwise inherit no client-side refusal at
10050
+ * all. The rail refuses at all three of its doors; this is the third layer.
10051
+ *
10052
+ * β›” BEFORE THE OPTIMISM AND BEFORE THE EMIT. `stampFolder` and `setViews` below
10053
+ * move the row in this browser and `emitHostEvent` puts an `item_move` on the
10054
+ * wire; refusing after either would be the revert-after shape D-636 warns about,
10055
+ * which looks identical on screen and still writes. Nothing is sent, so the snap
10056
+ * back is that the view never left.
10057
+ */
10058
+ const moving = views.find((view) => view.id === viewId);
10059
+ const refusal = moving ? viewMoveRefusal(moving, viewer) : null;
10060
+ if (refusal) {
10061
+ signal(TOAST_EVENT, refusal);
10062
+ return;
10063
+ }
10064
  stampFolder((p) => ({
10065
  ...p,
10066
  moved: { ...p.moved, [viewId]: { at: Date.now(), folderId } },
 
10148
  ) : (
10149
  <>
10150
  <div className="cg-drawer-launchers" aria-label="Workspace details">{isUserTable && <button type="button" className="cg-btn" aria-expanded={workspaceDrawer === "history"} onClick={() => setWorkspaceDrawer((open) => open === "history" ? null : "history")}>History</button>}</div>
10151
+ {/* ⭐⭐ W51-T06 CLAUSE 5 β€” THE PINNED RECORD IS THE **FIRST CHIP IN THE FILTER BAR**.
10152
+ β›”β›” IT IS DRAWN FROM A PROP AND IS NEVER IN THE FILTER TREE, WHICH IS WHAT KEEPS
10153
+ CLAUSE 8 TRUE. `config.filters` is what `persistView` serialises into the target
10154
+ database's OWN saved view; a pin written there would travel to every reader of that
10155
+ view, on every record, forever. The pin is the READ's premise (`related`), and the
10156
+ filter tree stays the reader's own.
10157
+ β›” NO REMOVE CONTROL, and that is the same statement: you are looking at one
10158
+ record's linked rows, so "which rows" is settled by the record, not by a condition
10159
+ you could lift. A dismissible chip would promise a state this surface cannot reach.
10160
+ ⭐ THE `title` NAMES **WHICH** LOCK. DESIGN.md section 4 has three and one glyph, so
10161
+ a `LockMark` that does not say which one is a mark nobody can read. A pinned row set
10162
+ is a LOCKED VIEW (a curated set). It is not a locked database (that forbids record
10163
+ add/delete/edit and still allows fields) and not a pre-set field (that locks one
10164
+ column's definition).
10165
+ ⚠ THE WRAPPER IS `display: contents` UNTIL IT HOLDS A CHIP (see
10166
+ `styles/wave51/grid.css`), so every surface that is not a related tab keeps the
10167
+ toolbar as a direct flex child of `.cg-main` and nothing about its layout, its
10168
+ container query or its `:has()` rules changes. */}
10169
+ <div className="cg-relpin-bar">
10170
+ {related && (
10171
+ <span
10172
+ className="cg-relpin-chip"
10173
+ title={"Locked view: these are the records linked to this one, so the set is the "
10174
+ + "premise of this tab rather than a condition you can change here."}
10175
+ >
10176
+ <LockMark size={11} />
10177
+ <span className="cg-relpin-text">{`Linked to ${related.label}`}</span>
10178
+ </span>
10179
+ )}
10180
  <Toolbar
10181
  manager={true}
10182
  nouns={topic.nouns}
 
10336
  notesUnread={notesUnread.length}
10337
  onNotes={() => setWorkspaceDrawer((open) => (open === "notes" ? null : "notes"))}
10338
  />
10339
+ </div>
10340
  {/* ⭐ R11's SECOND ROW β€” live, on the pivoted database. It renders only once the pivot has
10341
  actually been SERVED, which is the house posture for a control whose other half may
10342
  not be wired yet: absent beats present-and-inert. A control row over a database whose
 
10646
  drawCell={drawGridCell}
10647
  onHeaderMenuClick={(column, bounds) => openHeaderMenu(column, bounds)}
10648
  onHeaderClicked={onHeaderClicked}
10649
+ /* ⭐⭐ W51-T04 / R14 β€” `onHeaderContextMenu={onHeaderClicked}` was the wiring here,
10650
+ and it was the wrong thing: the left-click handler sorts the group strip in
10651
+ Summary mode, bails on the resize edge before suppressing the browser menu, and
10652
+ anchors on the header cell rather than the pointer. See `onHeaderContextMenu`
10653
+ above. The caret door on the line above this pair is unchanged. */
10654
+ onHeaderContextMenu={onHeaderContextMenu}
10655
  onKeyDown={onGridKeyDown}
10656
  maxColumnWidth={600}
10657
  getCellsForSelection={true}
 
10769
  fieldByKey={fieldByKey}
10770
  visibleKeys={visibleKeys}
10771
  titleKey={lockedKey}
10772
+ onOpen={openRecord}
10773
  onToggleGroup={onListToggleGroup}
10774
  />
10775
  )}
 
10787
  /* wave17 item 9 / R4 β€” the surface the day-grain measure channel is asked
10788
  about (C-CAL). The server refuses `product` in words. */
10789
  scope={scope}
10790
+ onOpen={openRecord}
10791
  /* owner item 3 β€” the summary month, so the view menu's Export can carry it. */
10792
  onSheet={onCalSheet}
10793
  />
 
10802
  fields={fields}
10803
  visibleKeys={visibleKeys}
10804
  titleKey={lockedKey}
10805
+ onOpen={openRecord}
10806
  />
10807
  )}
10808
  {displayMode === "timeline" &&
 
10813
  visibleKeys={visibleKeys}
10814
  field={calendarField}
10815
  titleKey={lockedKey}
10816
+ onOpen={openRecord}
10817
  />
10818
  ) : (
10819
  <div className="cg-mode-empty">
 
10832
  readOnlyReason={kanbanReason}
10833
  clamped={displaySpec?.kanbanClamp !== false}
10834
  onMove={onKanbanMove}
10835
+ onOpen={openRecord}
10836
  /* Item 12 (R8). ⚠ A `useCallback` or the literal `null` β€” NEVER an inline arrow.
10837
  KanbanView is memo'd and every prop here is referentially stable on purpose
10838
  (see the note above `kanbanCardKeys`); a fresh closure each render undoes that
 
10868
  canBind={!!activeView && mayEditView(activeView, viewer)}
10869
  onSpec={setSwipeSpec}
10870
  onSwipe={onSwipeDecide}
10871
+ onOpen={openRecord}
10872
  /* ⭐⭐ WAVE-29 T26 (owner R9) β€” the card renders the RECORD, so the deck now gets
10873
  what the modal gets: the view's visible fields (not the three-key kanban
10874
  summary), this surface's scope so comments can key on it, and the document
 
11073
  allRows={scopedRows}
11074
  selectedPids={selectedPids}
11075
  onSelectPids={selectPids}
11076
+ onOpen={openRecord}
11077
  />
11078
  )}
11079
  {/* Owner item 19 β€” the hover-only Expand. The COUNTERPART to item 17: the single
 
11100
  title="Expand record"
11101
  aria-label="Expand record"
11102
  onMouseDown={(event) => event.preventDefault()}
11103
+ onClick={() => openRecord(expandAt.pid)}
11104
  >
11105
  {/* Airtable's expand mark: two corner brackets pushing apart. SVG, never a
11106
  glyph β€” no emojis in this UI, and a unicode arrow renders differently on
 
11287
  (delArmed && delArmed === [...selectedPids].join(",") ? " is-armed" : "")
11288
  }
11289
  style={ONE_LINE}
11290
+ /* ⭐⭐ W51-T03 / R6 β€” THE BAR'S DELETE GOES THROUGH THE ONE DIALOG NOW, with
11291
+ its count. β›” `deleteRecords` ITSELF IS UNTOUCHED: its automation-authorship
11292
+ arm (WARN THEN ALLOW, owner 2026-08-06) answers a different question from
11293
+ this dialog, and the keyboard door still reaches it directly, which is the
11294
+ behaviour the owner named Ctrl+Z as the safety net for. */
11295
+ onClick={() => setRecordDelete([...selectedPids])}
11296
  >
11297
  {delArmed && delArmed === [...selectedPids].join(",")
11298
  ? "Delete anyway?"
 
11646
  : /**
11647
  * ⭐⭐ 2026-08-10 β€” the DEFINITION stratum's own delete.
11648
  *
11649
+ * β›”β›” WIDENED BY W51-T03, AND THE WIDENING IS D-133. It read
11650
+ * `(type === "link" || type === "rollup" || type === "formula")` β€” narrowed in
11651
+ * 2026-08-10 to the three kinds that hold no data of their own, on the argument
11652
+ * that a link, a rollup and a formula are QUESTIONS asked of other cells, so
11653
+ * removing one destroys no measurement. The cost of that caution was measured
11654
+ * and booked as D-114/D-133: a plain text or number column CREATED BY THE USER on
11655
+ * a `ut_*` database carries no `custom` flag, so it failed the first branch, and
11656
+ * it is none of those three kinds, so it failed this one. NO DOOR ANYWHERE
11657
+ * DELETED IT. A field you can make and cannot unmake is not a cautious product,
11658
+ * it is a one-way door.
11659
+ * ⭐ THE PREDICATE IS `isUserSchemaField`, WHICH IS NOT A NEW ANSWER. It is the
11660
+ * same "this column's shape belongs to this tenant" test `onRename` and
11661
+ * `onRetype` two props up already use, and the same one `columnDefinitionOffer`
11662
+ * (display.ts) uses to decide whether the menu row renders at all. Widening to
11663
+ * anything looser would have offered a delete the menu then withholds.
11664
+ * ⚠ THE THREE KINDS STAY, as a UNION rather than a replacement: a PRE-SET rollup
11665
+ * is machine-owned, so `isUserSchemaField` refuses it, and the owner ruling of
11666
+ * 2026-08-09 (*"No rollup field should be uneditable"*) says it keeps its door.
11667
+ * Dropping the arm would have revoked a live ruling while claiming to widen.
11668
  * ⚠ `schemaLocked` still gates the button inside ColumnMenu, so a pre-set link
11669
+ * never shows it; the confirm says a pre-set column comes back.
 
11670
  */
11671
  isUserTable &&
11672
  !menuField.custom &&
11673
  menuField.key !== lockedKey &&
11674
+ (isUserSchemaField(menuField, isUserTable) ||
11675
+ menuField.type === "link" || menuField.type === "rollup" ||
11676
  menuField.type === "formula")
11677
  ? () => {
11678
  setColumnDelete({ field: menuField, confirm: () => deleteDefinitionField(menuField.key) });
 
11698
  onDuplicate={
11699
  // R8: any non-identity field may become a tenant custom field. The identity
11700
  // column exposes no duplicate affordance, and the server names that refusal too.
11701
+ /**
11702
+ * ⭐⭐ W51-T03 / INSTRUCTION 5 β€” THE HOST DECIDES WHETHER TO ASK, because only the
11703
+ * host can see the rows. A column that holds nothing has one possible answer to
11704
+ * "duplicate the cells too", and R8's fake-affordance rule makes a dialog with one
11705
+ * possible answer a click tax, so it duplicates in place with `copyValues` false.
11706
+ * `columnCellValues` answers `null` on a windowed or read-through table, which is
11707
+ * NOT zero, so those always ask.
11708
+ */
11709
  menuField.key !== lockedKey
11710
+ ? () => {
11711
+ const held = columnCellValues(menuField.key);
11712
+ if (held === 0) duplicateField(menuField, false);
11713
+ else setFieldDuplicate({ field: menuField, copyValues: true });
11714
+ }
11715
  : undefined
11716
  }
11717
  onMoveLeft={
 
11842
  locked identity column (only its position matters β€” the create form never shows it).
11843
  The action/pane handlers below are unreachable in this mode (create-only; Cancel
11844
  closes), supplied inert to satisfy the surface. */}
11845
+ {/* ⭐⭐ W51-T03 / OWNER RULING R6 β€” FOUR DOORS, ONE SHELL.
11846
+ *"ONE ConfirmDialog for every destructive action … the Duplicate field dialog is the
11847
+ same shell with a primary button."* Below are the grid's four: duplicate a field,
11848
+ delete a field, delete a view, delete the selected records. Each is `ui/ConfirmDialog`
11849
+ with its own title, its own one-line body and its own verb, and NONE of them owns a
11850
+ scrim, a focus trap or an Escape listener. That is the point: four surfaces claiming
11851
+ Escape for themselves is the "topmost wins" race the kit exists to end. */}
11852
+ {fieldDuplicate && (
11853
+ <ConfirmDialog
11854
+ open
11855
+ tone="primary"
11856
+ title={`Duplicate ${fieldDuplicate.field.label}`}
11857
+ body={
11858
+ /* β›” THE TOGGLE'S STATE **IS** `copyValues`, not a mirror of it. It is read straight
11859
+ out of the pending record and written straight back, so what the switch shows and
11860
+ what `field_duplicate` carries cannot drift. ON by default, matching the reference
11861
+ (Airtable 14): the reader opened a dialog about a column that has values, and the
11862
+ likely intent is to keep them. */
11863
+ <DialogToggle
11864
+ label="Duplicate cells"
11865
+ checked={fieldDuplicate.copyValues}
11866
+ onChange={(next) =>
11867
+ setFieldDuplicate((current) => (current ? { ...current, copyValues: next } : current))
11868
+ }
11869
+ />
11870
+ }
11871
+ confirmLabel="Duplicate field"
11872
+ onCancel={() => setFieldDuplicate(null)}
11873
+ onConfirm={() => {
11874
+ duplicateField(fieldDuplicate.field, fieldDuplicate.copyValues);
11875
+ setFieldDuplicate(null);
11876
+ }}
11877
+ />
11878
+ )}
11879
+ {columnDelete && (
11880
+ <ConfirmDialog
11881
+ open
11882
+ tone="destructive"
11883
+ title={`Delete ${columnDelete.field.label}?`}
11884
+ body={<p className="cg-dialog-line">{fieldDeleteImpactLine(columnCellValues(columnDelete.field.key))}</p>}
11885
+ confirmLabel="Delete field"
11886
+ onCancel={() => setColumnDelete(null)}
11887
+ onConfirm={() => { columnDelete.confirm(); setColumnDelete(null); }}
11888
+ />
11889
+ )}
11890
  {pendingViewDelete && (
11891
+ <ConfirmDialog
11892
+ open
11893
+ tone="destructive"
11894
+ title={`Delete ${pendingViewDelete.name}?`}
11895
+ /* R32 survives R6 intact: the DISCLOSURE is what was ever unique to a view delete, and
11896
+ it is now this dialog's body rather than a second panel with its own buttons. */
11897
+ body={
11898
+ <ViewDeleteDisclosure
11899
+ dependents={pendingViewDelete.dependents}
11900
+ share={pendingViewDelete.share}
11901
+ loading={pendingViewDelete.loading}
11902
+ unanswered={pendingViewDelete.unanswered}
11903
+ error={pendingViewDelete.error}
11904
+ />
11905
+ }
11906
+ confirmLabel="Delete view"
11907
  onCancel={() => setPendingViewDelete(null)}
11908
  onConfirm={() => {
11909
  const id = pendingViewDelete.id;
 
11912
  }}
11913
  />
11914
  )}
11915
+ {/* ⚠ `.length > 0`, not merely truthy: an empty array is truthy, and a dialog offering to
11916
+ delete 0 records is the bare-zero defect D-217 names, one door along. */}
11917
+ {recordDelete && recordDelete.length > 0 && (
11918
+ <ConfirmDialog
11919
+ open
11920
+ tone="destructive"
11921
+ title={`Delete ${recordDelete.length === 1 ? "1 record" : `${recordDelete.length.toLocaleString()} records`}?`}
11922
+ /* ⚠ THE UNDO IS THE HONEST SENTENCE HERE, and it is the one the owner named: a bulk
11923
+ row delete pushes ONE grouped undo entry with the values captured before the round
11924
+ trip. Saying "this cannot be undone" would be false. */
11925
+ body={<p className="cg-dialog-line">Ctrl+Z puts them back.</p>}
11926
+ confirmLabel="Delete records"
11927
+ onCancel={() => setRecordDelete(null)}
11928
+ onConfirm={() => {
11929
+ void deleteRecords(recordDelete);
11930
+ setRecordDelete(null);
11931
+ }}
11932
+ />
11933
+ )}
11934
 
11935
  {plusMenu && fieldByKey.get(lockedKey) && (
11936
  <ColumnMenu
web/src/customer-grid/MapView.tsx CHANGED
@@ -105,6 +105,12 @@ import {
105
  zoneMutationPayload,
106
  } from "./routeZoneApi";
107
  import { mapNavigatorMode, routeSourceStopIds, toggleRouteSelection } from "./routeZoneTypes";
 
 
 
 
 
 
108
  import type {
109
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
110
  RouteAssigneeDirectory, RouteDeliveryDto, RouteDeliveryRequest,
@@ -804,6 +810,12 @@ export function MapView({
804
  } | null>(null);
805
  const [routePinNotice, setRoutePinNotice] = useState<string | null>(null);
806
  const [routePinBusy, setRoutePinBusy] = useState(false);
 
 
 
 
 
 
807
  const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
808
  const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
809
  const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
@@ -1319,11 +1331,37 @@ export function MapView({
1319
  }
1320
  })();
1321
  }, [activeView, onManagedRouteViewState, routeFilterSignature, selectedRouteIds]);
1322
- const toggleNamedRoute = useCallback(async (route: MapRouteDto) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1323
  const isAdding = !selectedRouteIds.has(route.id);
1324
- if (isAdding) {
1325
- if (route.outsideFilter && !window.confirm(`${route.name} is outside this filter. Include only this route's managed membership group?`)) return;
1326
- }
1327
  const next = toggleRouteSelection(selectedRouteIds, route.id);
1328
  if (!activeView) {
1329
  setRouteSelectionWarning("Select a saved View before adding a route inclusion.");
@@ -1393,6 +1431,27 @@ export function MapView({
1393
  }
1394
  } catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
1395
  }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedPids, selectedRouteIds]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1396
  const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
1397
  try {
1398
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
@@ -1997,6 +2056,39 @@ export function MapView({
1997
  // eslint-disable-next-line react-hooks/exhaustive-deps
1998
  }, [fit]);
1999
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2000
  /**
2001
  * W37-T35 β€” HOW FAR IN THE CAMERA MAY GO, and the answer now depends on what is under the pins.
2002
  *
@@ -3533,8 +3625,13 @@ export function MapView({
3533
  * clicking" again, and the panel row hides itself while the dashed boundary would have stayed
3534
  * painted with no control anywhere: the same orphan through the other door. Both sides must
3535
  * read `zoneEditorPanelOpen && !zoneKeyboardDraft && <geometry>` or they drift apart again.
 
 
 
 
 
 
3536
  */
3537
- const zoneEditorPanelOpen = zones !== null && mapNavigator === "zones" && zoneEditorOpen;
3538
  const gratOpacity = graticuleOpacity(view.k);
3539
  // I18 β€” the Google hand-off, and W37-T35 changed what it is FOR.
3540
  // It used to be the answer to "I need to see the actual street", because the
@@ -3619,394 +3716,82 @@ export function MapView({
3619
  </a>
3620
  </span>
3621
  )}
3622
- {/* ═══════════════════════════════════════════════════════════════════════════════════
3623
- THE ROUTE PANEL β€” rebuilt for owner items 2, 4, 6, 8 and 9.
3624
-
3625
- ⭐⭐ ITEM 2 IS THE STRUCTURAL ONE AND IT IS WHY THIS IS ONE REBUILD RATHER THAN FIVE
3626
- EDITS. The panel used to render its entire body inside `selectedPids.size >= 2`, so
3627
- clicking Route with nothing chosen produced a box containing one sentence telling you
3628
- off. The owner's answer: show the navigation, empty. So the chrome, the travel mode,
3629
- the stop list and the record search are UNCONDITIONAL, and only the parts that
3630
- genuinely describe a solved route (the distance, the visit numbers, the save target)
3631
- wait for `plan`.
3632
-
3633
- β›” `plan` IS NULL UNTIL `routeOn` FLIPS **AND** TWO STOPS CAN BE ROUTED, so every read
3634
- of `plan.*` below sits inside a `plan &&`. The old code was safe only because the whole
3635
- body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
3636
- selected is a crash, not a blank.
3637
- ═══════════════════════════════════════════════════════════════════════════════════ */}
3638
- {mapNavigator === "routes" && (
3639
- <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
3640
- {navigatorTabs}
3641
- {/* D-599 / W46-T22 - `zones` is the vocabulary a Route's Zone selector offers. It
3642
- is already loaded here to draw the map, so RouteNav gets a pass-through and
3643
- never a second fetch of its own. */}
3644
- <RouteNav
3645
- routes={namedRoutes}
3646
- folders={routeFolders}
3647
- selectedIds={selectedRouteIds}
3648
- activeRouteId={activeRouteId}
3649
- sources={routeSources}
3650
- storageKey={tableKey}
3651
- createdRoute={createdRoute}
3652
- onCreatedDismiss={() => setCreatedRoute(null)}
3653
- onToggle={(route) => void toggleNamedRoute(route)}
3654
- onActiveRouteChange={setActiveRouteId}
3655
- onOpenRecord={onOpen}
3656
- stopLabels={routeStopLabels}
3657
- stopCoords={routeStopCoords}
3658
- roundTrip={roundTrip}
3659
- onRoundTripChange={(value) => {
3660
- if (value) setRouteEndPid(null);
3661
- // A saved/manual order is an intentional route, but an endpoint change asks for
3662
- // a fresh constrained solve. Leaving it in place would make the dropdown move
3663
- // without changing the painted or timed route.
3664
- setRouteOrder(null);
3665
- setRoundTrip(value);
3666
- }}
3667
- routeStartPid={routeStartPid}
3668
- routeEndPid={routeEndPid}
3669
- onRouteStartChange={(pid) => {
3670
- setRouteOrder(null);
3671
- setRouteStartPid(pid);
3672
- if (pid === routeEndPid) setRouteEndPid(null);
3673
- }}
3674
- onRouteEndChange={(pid) => { setRouteOrder(null); setRouteEndPid(pid); }}
3675
- onStopAdded={(updated) => setNamedRoutes((current) => current.map((item) =>
3676
- item.id === updated.id
3677
- ? { ...item, ...updated, folderId: item.folderId, navOrder: item.navOrder }
3678
- : item))}
3679
- onCreate={createNamedRoute}
3680
- onMoveToOrder={moveNamedRouteStop}
3681
- onUpdate={updateNamedRoute}
3682
- onDuplicate={duplicateNamedRoute}
3683
- onDelete={deleteNamedRoute}
3684
- onShare={shareNamedRoute}
3685
- onRouteMove={moveNamedRoute}
3686
- onRouteReorder={reorderNamedRoutes}
3687
- onFolderCreate={createNamedRouteFolder}
3688
- onFolderUpdate={updateNamedRouteFolder}
3689
- onFolderDelete={deleteNamedRouteFolder}
3690
- onFolderReorder={reorderNamedRouteFolders}
3691
- onCreateStart={() => setSaveTarget("")}
3692
- mapLinks={activeRouteMaps.links}
3693
- mapLinkRefusal={activeRouteMapsRefusal}
3694
- deliveries={routeDeliveries}
3695
- assignees={routeAssignees?.people ?? null}
3696
- zones={zones || []}
3697
- routeToday={routeAssignees?.today ?? null}
3698
- assigneeError={routeAssigneeError}
3699
- onSchedule={scheduleNamedRouteDelivery}
3700
- onDeleteDelivery={deleteNamedRouteDelivery}
3701
- />
3702
- {routePinPrompt && (
3703
- <div
3704
- className="cg-w44-route-prompt"
3705
- role="dialog"
3706
- aria-label={`${routePinPrompt.present ? "Add" : "Remove"} Route stop`}
3707
- aria-describedby="cg-route-pin-prompt-copy"
3708
- >
3709
- <p id="cg-route-pin-prompt-copy">
3710
- {routePinPrompt.present ? "Add" : "Remove"} {routePinPrompt.title}{" "}
3711
- {routePinPrompt.present ? "to" : "from"} {activeNamedRoute?.name || "this Route"}?
3712
- </p>
3713
- <div className="cg-form-actions">
3714
- <button type="button" className="cg-btn cg-btn--primary" disabled={routePinBusy}
3715
- onClick={() => void confirmRoutePinMembership()}>
3716
- Confirm {routePinPrompt.present ? "add" : "remove"}
3717
- </button>
3718
- <button type="button" className="cg-btn" disabled={routePinBusy}
3719
- onClick={() => setRoutePinPrompt(null)}>
3720
- Cancel
3721
- </button>
3722
- </div>
3723
- </div>
3724
- )}
3725
- {routePinNotice && (
3726
- <span className="cg-w44-route-warning" role="status">{routePinNotice}</span>
3727
- )}
3728
- {routeSelectionWarning && (
3729
- <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
3730
- )}
3731
- </aside>
3732
- )}
3733
  {routeSelectionWarning && !routePanelOpen && (
3734
  <aside className="cg-route-popover" aria-label="Route selection notice">
3735
  <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
3736
  </aside>
3737
  )}
3738
  {geoControl}
3739
- {zones !== null && mapNavigator === "zones" && !zoneEditorOpen && (
3740
- <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
3741
- {navigatorTabs}
3742
- <div className="cg-route-popover-head">
3743
- <button type="button" className="cg-route-index-back" onClick={() => setZoneNavigatorOpen(false)}>Back</button>
3744
- <span className="cg-views-title">Zones</span>
3745
- </div>
3746
- <div className="cg-map-zones" role="group" aria-label="Choose visible Zones">
3747
- <div id="cg-map-zone-choices" className="cg-map-zone-choices" role="group" aria-label="Visible map Zones">
3748
- {(zones || []).length === 0 ? (
3749
- <span className="cg-map-zone-empty">No Zones yet.</span>
3750
- ) : (zones || []).map((zone) => (
3751
- <div className="cg-map-zone-option" key={zone.id}>
3752
- <label className="cg-map-zone-choice">
3753
- <input
3754
- type="checkbox"
3755
- checked={activeZoneIds.has(zone.id)}
3756
- disabled={!zone.visible}
3757
- onChange={(event) => toggleZone(zone, event.target.checked)}
3758
- />
3759
- <span className="cg-map-zone-swatch" style={{ backgroundColor: zone.color }} aria-hidden="true" />
3760
- <span>{zone.visible ? zone.name : `${zone.name} (hidden)`}</span>
3761
- </label>
3762
- <button type="button" className="cg-map-zone-edit"
3763
- disabled={normalizedCustomerZones && !zone.permission?.canEdit}
3764
- onClick={() => beginEditZone(zone)} aria-label={`Edit ${zone.name}`}>
3765
- Edit
3766
- </button>
3767
- </div>
3768
- ))}
3769
- </div>
3770
- <button type="button" className="cg-btn cg-btn--primary" onClick={beginNewZone}>New Zone</button>
3771
- {/* β›” W46-T28 β€” `zoneErr` USED TO RENDER IN THE EDITOR PANEL ONLY, and half the
3772
- things that set it happen with the editor closed: `persistZoneGeometry` fires
3773
- from a boundary drag and now from a vertex drag, both of which happen right
3774
- here on the map with this list open. A rejected reshape would have failed in
3775
- silence, the shape snapping back with no reason given. Standing rule 1: a
3776
- refusal is reported, never silently enforced. */}
3777
- {zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
3778
- </div>
3779
- </aside>
3780
- )}
3781
- {zones !== null && mapNavigator === "zones" && zoneEditorOpen && (
3782
- <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
3783
- {navigatorTabs}
3784
- <div className="cg-route-popover-head">
3785
- <button type="button" className="cg-route-index-back" onClick={() => { setZoneErr(null); setZoneEditorOpen(false); }}>Back to Zones</button>
3786
- <span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
3787
- </div>
3788
- <div className="cg-map-zones cg-map-zone-editor">
3789
- <label className="cg-map-zone-control">
3790
- Zone name
3791
- <input
3792
- className="cg-input"
3793
- value={zoneName}
3794
- maxLength={120}
3795
- aria-label="Zone name"
3796
- placeholder="Name this Zone"
3797
- onChange={(event) => setZoneName(event.target.value)}
3798
- />
3799
- </label>
3800
- <fieldset className="cg-zone-shape-picker">
3801
- <legend>Boundary</legend>
3802
- <div role="group" aria-label="Zone boundary shape">
3803
- <button type="button" aria-pressed={zoneDrawShape === "polygon"}
3804
- onClick={() => setZoneDrawShape("polygon")}>Polygon</button>
3805
- <button type="button" aria-pressed={zoneDrawShape === "circle"}
3806
- onClick={() => setZoneDrawShape("circle")}>Circle</button>
3807
- </div>
3808
- <span>Choose a shape, then drag on the map, or draw it by clicking.</span>
3809
- {!zoneKeyboardDraft ? (
3810
- <button type="button" className="cg-link-btn cg-zone-draw-btn" onClick={startKeyboardZoneDrawing}>
3811
- <DrawZoneIcon />
3812
- Draw by clicking
3813
- </button>
3814
- ) : (
3815
- <>
3816
- {/* β›”β›” W46-T28 β€” "FINISH SHAPE" IS THE MISSING CONTROL, not a convenience.
3817
- Pressing Enter only commits the outline while the MAP holds focus, and
3818
- naming the Zone moves focus into the input beside this. Without a button
3819
- in the panel, the only ending on offer was "Stop drawing", which throws
3820
- the points away, so a drawn shape could never reach the Save button. */}
3821
- <div className="cg-zone-draw-actions">
3822
- <button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
3823
- onClick={() => { finishZoneDraft(); }}>
3824
- <DrawZoneIcon />
3825
- Finish shape
3826
- </button>
3827
- <button type="button" className="cg-link-btn cg-zone-draw-btn"
3828
- onClick={() => { setZoneKeyboardDraft(null); setZoneErr(null); }}>
3829
- Stop drawing
3830
- </button>
3831
- </div>
3832
- <span role="status" aria-live="polite">
3833
- {zoneKeyboardDraft.shape === "polygon"
3834
- ? `${zoneKeyboardDraft.points.length} ${zoneKeyboardDraft.points.length === 1 ? "vertex" : "vertices"}. Click the map to add one, then choose Finish shape, or press Enter on the map.`
3835
- : zoneKeyboardDraft.center
3836
- ? "Center placed. Click its edge, then choose Finish shape."
3837
- : "Click the map to place the circle center, then click its edge."}
3838
- </span>
3839
- </>
3840
- )}
3841
- </fieldset>
3842
- {/* ⭐⭐ W47-T03, RULING R4 β€” THE FINISHED SHAPE CARRIES ITS OWN TWO ENDINGS.
3843
- Before this there was no such thing as a finished-but-unsaved Zone on screen:
3844
- "Finish shape" cleared the only painted state and the user was left holding a
3845
- boundary they could not see, in front of a primary button that gave no sign it
3846
- now had something to save. The pair sits exactly where Finish shape / Stop
3847
- drawing were, because it is the same flow one step later.
3848
- β›” SAVE GOES THROUGH `saveZone`, NOT A SECOND WRITE PATH. `saveZone` already
3849
- reads `drawnZoneGeometry`, already states its own refusal in `zoneErr` when the
3850
- name is missing, and already clears the geometry on success so this row and the
3851
- dashed shape retire together the moment the solid saved Zone appears.
3852
- ⚠ Discard clears the geometry ONLY. It does not close the editor or reset the
3853
- name and colour: throwing away a boundary the user disliked should not also
3854
- throw away the two fields they typed before drawing it. */}
3855
- {!zoneKeyboardDraft && drawnZoneGeometry && (
3856
- <>
3857
- <div className="cg-zone-draw-actions cg-zone-unsaved-actions">
3858
- <button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
3859
- disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
3860
- onClick={() => { void saveZone(zoneEditor || undefined); }}>
3861
- Save zone
3862
- </button>
3863
- <button type="button" className="cg-link-btn cg-zone-draw-btn"
3864
- onClick={() => { setDrawnZoneGeometry(null); setZoneErr(null); }}>
3865
- Discard
3866
- </button>
3867
- </div>
3868
- <span className="cg-zone-unsaved-note" role="status" aria-live="polite">
3869
- Shape finished. It is not saved yet, and shows as the dashed outline on the
3870
- map until you choose Save zone.
3871
- </span>
3872
- </>
3873
- )}
3874
- {zoneEditor && (
3875
- <button
3876
- type="button"
3877
- className="cg-btn"
3878
- disabled={zoneBusy || (normalizedCustomerZones && !zoneEditor.permission?.canEdit)}
3879
- onClick={() => void setZoneVisible(zoneEditor, !zoneEditor.visible)}
3880
- >
3881
- {zoneEditor.visible ? "Hide Zone" : "Show Zone"}
3882
- </button>
3883
- )}
3884
- <label className="cg-map-zone-control">
3885
- Color
3886
- <select className="cg-route-select" value={zoneColor} aria-label="Zone color" onChange={(event) => setZoneColor(event.target.value)}>
3887
- {ZONE_COLOR_CHOICES.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}
3888
- </select>
3889
- </label>
3890
- {/* ⭐ OWNER 2026-08-31 - the opacity is a dial now, not a constant. It sits beside
3891
- Color because both are how a Zone READS rather than what it covers, and it takes
3892
- effect on every Zone the moment it moves: the value is the custom property the
3893
- saved-Zone rule already consumes.
3894
- ⚠ The reading is shown as a PERCENTAGE because that is the unit the instruction
3895
- was given in ("80% opacity"), while the stored value stays the 0-1 fraction every
3896
- consumer expects - the conversion happens at this boundary and nowhere else. */}
3897
- <label className="cg-map-zone-control">
3898
- Fill opacity
3899
- <input
3900
- type="range"
3901
- className="cg-zone-opacity-range"
3902
- min={0}
3903
- max={100}
3904
- step={5}
3905
- value={Math.round(zoneFillOpacity * 100)}
3906
- aria-label="Zone fill opacity"
3907
- aria-valuetext={`${Math.round(zoneFillOpacity * 100)} percent`}
3908
- onChange={(event) => setZoneFillOpacity(Number(event.currentTarget.value) / 100)}
3909
- />
3910
- <span className="cg-zone-opacity-read">{Math.round(zoneFillOpacity * 100)}%</span>
3911
- </label>
3912
- {/* β›”β›” W46-T28 β€” A MISSING NAME OR BOUNDARY NO LONGER DISABLES THIS BUTTON, and
3913
- that is the point rather than a loosening. A disabled control cannot say why it
3914
- is disabled, so the owner's "it won't even let me save" arrived with no reason
3915
- on screen at all. `saveZone` already has the message for both cases ("Name a
3916
- Zone and draw its boundary on the map.") and `zoneErr` renders at the foot of
3917
- this panel, so letting the click through turns a silent refusal into a stated
3918
- one. Permission and in-flight state still disable it: those are not the user's
3919
- mistake to correct. */}
3920
- <button
3921
- type="button"
3922
- className="cg-btn cg-btn--primary"
3923
- disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
3924
- onClick={() => {
3925
- // An outline still being drawn is committed first, and its geometry handed
3926
- // straight down: state set in this tick is not readable from `saveZone`.
3927
- if (zoneKeyboardDraft) {
3928
- const pending = finishZoneDraft();
3929
- // `finishZoneDraft` has already put the real reason in `zoneErr`. Falling
3930
- // through would overwrite it with a vaguer one.
3931
- if (!pending) return;
3932
- void saveZone(zoneEditor || undefined, pending);
3933
- return;
3934
- }
3935
- void saveZone(zoneEditor || undefined);
3936
- }}
3937
- title={drawnZoneGeometry || zoneKeyboardDraft
3938
- ? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
3939
- : zoneEditor ? "Save Zone details" : "Draw a boundary before saving"}
3940
- >
3941
- {zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
3942
- </button>
3943
- {zoneEditor && (!normalizedCustomerZones || zoneEditor.permission?.canDelete) && (
3944
- <button type="button" className="cg-btn cg-btn--danger" disabled={zoneBusy}
3945
- onClick={() => {
3946
- if (window.confirm(`Delete ${zoneEditor.name}?`)) void deleteZone(zoneEditor);
3947
- }}>
3948
- Delete Zone
3949
- </button>
3950
- )}
3951
- {zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
3952
- </div>
3953
- </aside>
3954
- )}
3955
- {/* Every gesture the map has, named. `alt` (add to the selection rather
3956
- than replace it, onPointerUp) shipped in wave 8 and was disclosed
3957
- NOWHERE, so "select these as well" was a feature only the source
3958
- knew about. It needs shift too β€” alt alone still pans. */}
3959
- <span className="cg-map-hint">
3960
- Scroll to zoom Β· drag to pan Β· {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
3961
- Β· shift-alt-drag to extend the selection Β· click or press Enter on a pin to open the
3962
- record Β· shift-click or press Space on a pin to add or remove it from the selection
3963
- </span>
3964
- </div>
3965
- {/* ⭐⭐ W41-T48 β€” OPENING A RECORD FOLDS THE RAIL, and R14 (2026-09-03) removed the
3966
- `!routePanelOpen` gate from this frame's `onPointerDown`. That gate existed only because
3967
- a pin click in Route mode did not open a record; it now does, on every pin, so the map
3968
- must fold the rail in Route mode exactly as it does outside it. */}
3969
- <div
3970
- ref={mapFrameRef}
3971
- className="cg-map-frame"
3972
- tabIndex={0}
3973
- role="group"
3974
- aria-label={zoneKeyboardDraft
3975
- ? `Zone ${zoneKeyboardDraft.shape} drawing canvas. Click the map to add points, then press Enter to finish.`
3976
- : "Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."}
3977
- onKeyDown={onFrameKeyDown}
3978
- onPointerDown={() => signal(NAV_MINIMIZE_EVENT)}
3979
- >
3980
- <svg
3981
- ref={setSvgEl}
3982
- viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
3983
- preserveAspectRatio="xMidYMid meet"
3984
- className={"cg-map-svg" + (drag ? " is-selecting" : "")}
3985
- role="img"
3986
- aria-label={`Map of ${points.length.toLocaleString()} records`}
3987
- onPointerDown={onPointerDown}
3988
- onPointerMove={onPointerMove}
3989
- onPointerUp={onPointerUp}
3990
- onPointerCancel={onPointerUp}
3991
- >
3992
- <rect className="cg-map-water" x={0} y={0} width={VIEW_W} height={VIEW_H} />
3993
- <g transform={tf}>
3994
- {/* --- W37-T35: the raster basemap, UNDER everything, inside the same transform.
3995
- β›” AND THE VENDORED GEOMETRY BELOW IS HIDDEN WHILE IT PAINTS. Drawing a
3996
- generalised coastline on top of a real one does not add detail, it adds a SECOND
3997
- coastline a few pixels off the first, plus a graticule fighting the tiles' own
3998
- grid. Two basemaps disagreeing about where Florida is looks like a rendering bug
3999
- to everyone except the person who knows there are two of them. --- */}
4000
- {tileLayer && (
4001
- <g className="cg-map-tiles" aria-hidden="true">
4002
- {/* Painted under the images so a tile still in flight shows map-coloured ground
4003
- rather than the page behind it, which reads as a hole rather than as loading. */}
4004
- <rect
4005
- className="cg-map-tilebed"
4006
- x={tileLayer.bed.x}
4007
- y={tileLayer.bed.y}
4008
- width={tileLayer.bed.w}
4009
- height={tileLayer.bed.h}
4010
  />
4011
  {tileLayer.items.map((t) => (
4012
  <image
@@ -4790,6 +4575,378 @@ export function MapView({
4790
  </div>
4791
  )}
4792
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4793
  </div>
4794
  );
4795
  }
 
105
  zoneMutationPayload,
106
  } from "./routeZoneApi";
107
  import { mapNavigatorMode, routeSourceStopIds, toggleRouteSelection } from "./routeZoneTypes";
108
+ // W51-T28 / R6 + C8 β€” the wave-51 base kit. Every destructive act on this surface goes through
109
+ // the ONE dialog, and every panel registers its Escape claim with the ONE arbiter. Neither is
110
+ // re-implemented here: `ConfirmDialog` brings its own portal, focus trap, backdrop and focus
111
+ // restore, and `useEscapeClose` brings the topmost-wins stack.
112
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
113
+ import { useEscapeClose } from "../ui/useEscapeClose";
114
  import type {
115
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
116
  RouteAssigneeDirectory, RouteDeliveryDto, RouteDeliveryRequest,
 
810
  } | null>(null);
811
  const [routePinNotice, setRoutePinNotice] = useState<string | null>(null);
812
  const [routePinBusy, setRoutePinBusy] = useState(false);
813
+ /* ⭐ W51-T28 / R6 β€” THE TWO PENDING CONFIRMS, HOISTED TO THE COMPONENT so the dialog outlives
814
+ the control that opened it. Both replaced a `window.confirm`, which blocked the JS thread and
815
+ therefore needed no state at all; a real dialog paints on a later frame, so the subject of the
816
+ question has to be held somewhere that survives that frame. */
817
+ const [pendingRouteInclude, setPendingRouteInclude] = useState<MapRouteDto | null>(null);
818
+ const [pendingZoneDelete, setPendingZoneDelete] = useState<MapZone | null>(null);
819
  const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
820
  const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
821
  const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
 
1331
  }
1332
  })();
1333
  }, [activeView, onManagedRouteViewState, routeFilterSignature, selectedRouteIds]);
1334
+ /**
1335
+ * ⭐⭐ W51-T28 / R6 β€” THE WRITE HALF, SPLIT OUT SO THE CONFIRM CAN BE A DIALOG.
1336
+ *
1337
+ * This body was reached past a `window.confirm` sitting at the top of one async function, and
1338
+ * that arrangement cannot survive the change: `window.confirm` blocks the thread and hands back
1339
+ * a boolean, while a dialog is a render. There is no way to `await` the dialog without inventing
1340
+ * a promise bridge across React state, so the function is CUT INSTEAD OF WRAPPED.
1341
+ *
1342
+ * β›”β›” THE NAME IS LOAD-BEARING, AND NOT FOR READABILITY. `verify_w44_map_routes.py`'s
1343
+ * `managed-route-callback` leg slices this file between the `toggleNamedRoute` declaration and
1344
+ * the `moveNamedRouteStop` one, then asserts that `onManagedRouteViewState?.(...)` fires AFTER
1345
+ * the `body?.managedBy !== "loopable"` refusal. Splitting the function moved that whole sequence
1346
+ * out of the slice, and the leg went red on code whose logic had not changed a line. The
1347
+ * extracted half therefore keeps the `toggleNamedRoute` PREFIX, so the slice opens on this
1348
+ * function rather than on the entry below it and still contains the whole toggle path. Rename
1349
+ * this and that gate, which this ticket does not own, goes red again for the same non-reason.
1350
+ *
1351
+ * β›”β›” AND THE PROSE HERE MUST NOT SPELL THE ANCHORS THE WAY THE GATE SPELLS THEM. That leg
1352
+ * slices with a plain `str.find` over the RAW file and strips no comments, so a note quoting its
1353
+ * two anchor strings verbatim, `const` keyword and all, is found BEFORE the real declarations
1354
+ * and yields a 33-character slice. That is exactly how this comment reddened the gate it was
1355
+ * written to explain, which is why the two names above appear WITHOUT the keyword in front.
1356
+ *
1357
+ * β›” `isAdding` AND `next` ARE RECOMPUTED HERE, NOT PASSED IN, and that is the trap this note
1358
+ * exists for. The pending route waits in state across at least one render; a decision captured
1359
+ * at the moment the dialog opened could describe a selection that has since changed underneath
1360
+ * it. Recomputing from the live `selectedRouteIds` makes the confirmed act the act the user is
1361
+ * looking at. There is exactly ONE copy of this body: the ordinary path calls it directly.
1362
+ */
1363
+ const toggleNamedRouteSelection = useCallback(async (route: MapRouteDto) => {
1364
  const isAdding = !selectedRouteIds.has(route.id);
 
 
 
1365
  const next = toggleRouteSelection(selectedRouteIds, route.id);
1366
  if (!activeView) {
1367
  setRouteSelectionWarning("Select a saved View before adding a route inclusion.");
 
1431
  }
1432
  } catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
1433
  }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedPids, selectedRouteIds]);
1434
+ /**
1435
+ * The ENTRY point. Ticking a route that the View's own filter excludes is the one branch that
1436
+ * asks first: the inclusion widens what the grid shows, so the person is told before it happens.
1437
+ * Everything else goes straight through to the write above.
1438
+ */
1439
+ const toggleNamedRoute = useCallback(async (route: MapRouteDto) => {
1440
+ const isAdding = !selectedRouteIds.has(route.id);
1441
+ if (isAdding && route.outsideFilter) {
1442
+ setPendingRouteInclude(route);
1443
+ return;
1444
+ }
1445
+ await toggleNamedRouteSelection(route);
1446
+ }, [toggleNamedRouteSelection, selectedRouteIds]);
1447
+ const confirmPendingRouteInclude = useCallback(() => {
1448
+ const route = pendingRouteInclude;
1449
+ if (!route) return;
1450
+ // Cleared BEFORE the dispatch, so a second Enter on a dialog that has not yet unmounted
1451
+ // cannot post the same inclusion twice.
1452
+ setPendingRouteInclude(null);
1453
+ void toggleNamedRouteSelection(route);
1454
+ }, [toggleNamedRouteSelection, pendingRouteInclude]);
1455
  const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
1456
  try {
1457
  const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
 
2056
  // eslint-disable-next-line react-hooks/exhaustive-deps
2057
  }, [fit]);
2058
 
2059
+ /* ═══════════════ W51-T28 / C8 β€” ESCAPE CLOSES THE MAP'S OWN PANELS ═══════════════════════
2060
+ *
2061
+ * β›” THE TWO CLOSE ACTIONS ARE NAMED CALLBACKS, AND THE `Back` BUTTONS CALL THE SAME ONES.
2062
+ * Escape that does something slightly different from the visible close is a second behaviour
2063
+ * wearing the first one's name; sharing the callback makes "Escape does what Back does" a
2064
+ * property of the code rather than a claim about it.
2065
+ *
2066
+ * ⚠ THE `active` FLAGS MUST MATCH THE RENDER CONDITIONS, INCLUDING THE EMPTY STATE. This
2067
+ * component returns `.cg-mode-empty` early when there is no camera and no fit, and that branch
2068
+ * renders none of these panels. A claim on Escape from a panel nobody can see would swallow the
2069
+ * key from whatever IS on screen, so `mapCanvasMounted` is part of both flags. The two panel
2070
+ * expressions are hoisted here rather than duplicated: the render sites below read these same
2071
+ * constants, so the flag and the panel cannot drift apart.
2072
+ *
2073
+ * ⭐ THE TOPMOST-WINS ORDER IS NOT CONFIGURED ANYWHERE, ON PURPOSE. `useEscapeClose` keeps ONE
2074
+ * push-ordered stack, and `ConfirmDialog` joins it when it opens, i.e. after the panel that
2075
+ * opened it. So Escape closes the dialog first and the panel underneath on the second press,
2076
+ * with no priority number, no z-index and no second listener involved.
2077
+ *
2078
+ * ⚠ `cancelEditFirst` STAYS AT ITS DEFAULT FALSE. These are panels holding a Zone-name input
2079
+ * and a search box; opting in would turn every one of those into a two-Escape close.
2080
+ */
2081
+ const mapCanvasMounted = view != null && fit != null;
2082
+ const zoneChooserPanelOpen = zones !== null && mapNavigator === "zones" && !zoneEditorOpen;
2083
+ const zoneEditorPanelOpen = zones !== null && mapNavigator === "zones" && zoneEditorOpen;
2084
+ const closeZoneChooser = useCallback(() => setZoneNavigatorOpen(false), []);
2085
+ const closeZoneEditor = useCallback(() => {
2086
+ setZoneErr(null);
2087
+ setZoneEditorOpen(false);
2088
+ }, []);
2089
+ useEscapeClose(mapCanvasMounted && zoneChooserPanelOpen, closeZoneChooser);
2090
+ useEscapeClose(mapCanvasMounted && zoneEditorPanelOpen, closeZoneEditor);
2091
+
2092
  /**
2093
  * W37-T35 β€” HOW FAR IN THE CAMERA MAY GO, and the answer now depends on what is under the pins.
2094
  *
 
3625
  * clicking" again, and the panel row hides itself while the dashed boundary would have stayed
3626
  * painted with no control anywhere: the same orphan through the other door. Both sides must
3627
  * read `zoneEditorPanelOpen && !zoneKeyboardDraft && <geometry>` or they drift apart again.
3628
+ *
3629
+ * β›” W51-T28 MOVED THE DECLARATION UP, IT DID NOT ADD A SECOND ONE. `useEscapeClose` has to
3630
+ * register above the `!view || !fit` early return, so `zoneEditorPanelOpen` and its chooser
3631
+ * sibling now live beside those hooks. Declaring the expression twice is exactly the drift this
3632
+ * comment warns about, so there is one const and both the Escape claim and the render sites
3633
+ * read it.
3634
  */
 
3635
  const gratOpacity = graticuleOpacity(view.k);
3636
  // I18 β€” the Google hand-off, and W37-T35 changed what it is FOR.
3637
  // It used to be the answer to "I need to see the actual street", because the
 
3716
  </a>
3717
  </span>
3718
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3719
  {routeSelectionWarning && !routePanelOpen && (
3720
  <aside className="cg-route-popover" aria-label="Route selection notice">
3721
  <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
3722
  </aside>
3723
  )}
3724
  {geoControl}
3725
+ {/* Every gesture the map has, named. `alt` (add to the selection rather
3726
+ than replace it, onPointerUp) shipped in wave 8 and was disclosed
3727
+ NOWHERE, so "select these as well" was a feature only the source
3728
+ knew about. It needs shift too β€” alt alone still pans. */}
3729
+ <span className="cg-map-hint">
3730
+ Scroll to zoom Β· drag to pan Β· {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
3731
+ Β· shift-alt-drag to extend the selection Β· click or press Enter on a pin to open the
3732
+ record Β· shift-click or press Space on a pin to add or remove it from the selection
3733
+ </span>
3734
+ </div>
3735
+ {/* ⭐⭐ W51-T32 - THE MAP AND THE 380 px ROUTE COLUMN SHARE ONE FLEX ROW, WHICH IS WHY
3736
+ THE THREE NAVIGATOR PANELS MOVED OUT OF THE TOOLBAR. They used to be toolbar children
3737
+ floated over the canvas, and the mechanism that made that unfixable is document order
3738
+ inside an SVG: a pin painted under the floating column could not receive a pointer
3739
+ event, and no stacking value on either side changes that. Wave 50's QA measured 427 px
3740
+ of live map covered and a coordinate click on a covered pin opening nothing at all.
3741
+ The repair is LAYOUT: the canvas and the column are siblings in a row, the canvas
3742
+ yields the width the column takes, and every pin is back in the open.
3743
+ ⚠ The row also RETIRES four competing declarations in three other stylesheets, all of
3744
+ them keyed on the toolbar-child path, so they simply stop matching rather than needing
3745
+ an override this ticket is not allowed to write.
3746
+ ⚠ The frame block below deliberately keeps its former indentation. Re-indenting 820
3747
+ lines would bury a structural move in a whitespace diff and would rewrite two
3748
+ multi-line template literals inside it. */}
3749
+ <div className="cg-map-stage">
3750
+ {/* ⭐⭐ W41-T48 β€” OPENING A RECORD FOLDS THE RAIL, and R14 (2026-09-03) removed the
3751
+ `!routePanelOpen` gate from this frame's `onPointerDown`. That gate existed only because
3752
+ a pin click in Route mode did not open a record; it now does, on every pin, so the map
3753
+ must fold the rail in Route mode exactly as it does outside it. */}
3754
+ <div
3755
+ ref={mapFrameRef}
3756
+ className="cg-map-frame"
3757
+ tabIndex={0}
3758
+ role="group"
3759
+ aria-label={zoneKeyboardDraft
3760
+ ? `Zone ${zoneKeyboardDraft.shape} drawing canvas. Click the map to add points, then press Enter to finish.`
3761
+ : "Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."}
3762
+ onKeyDown={onFrameKeyDown}
3763
+ onPointerDown={() => signal(NAV_MINIMIZE_EVENT)}
3764
+ >
3765
+ <svg
3766
+ ref={setSvgEl}
3767
+ viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
3768
+ preserveAspectRatio="xMidYMid meet"
3769
+ className={"cg-map-svg" + (drag ? " is-selecting" : "")}
3770
+ role="img"
3771
+ aria-label={`Map of ${points.length.toLocaleString()} records`}
3772
+ onPointerDown={onPointerDown}
3773
+ onPointerMove={onPointerMove}
3774
+ onPointerUp={onPointerUp}
3775
+ onPointerCancel={onPointerUp}
3776
+ >
3777
+ <rect className="cg-map-water" x={0} y={0} width={VIEW_W} height={VIEW_H} />
3778
+ <g transform={tf}>
3779
+ {/* --- W37-T35: the raster basemap, UNDER everything, inside the same transform.
3780
+ β›” AND THE VENDORED GEOMETRY BELOW IS HIDDEN WHILE IT PAINTS. Drawing a
3781
+ generalised coastline on top of a real one does not add detail, it adds a SECOND
3782
+ coastline a few pixels off the first, plus a graticule fighting the tiles' own
3783
+ grid. Two basemaps disagreeing about where Florida is looks like a rendering bug
3784
+ to everyone except the person who knows there are two of them. --- */}
3785
+ {tileLayer && (
3786
+ <g className="cg-map-tiles" aria-hidden="true">
3787
+ {/* Painted under the images so a tile still in flight shows map-coloured ground
3788
+ rather than the page behind it, which reads as a hole rather than as loading. */}
3789
+ <rect
3790
+ className="cg-map-tilebed"
3791
+ x={tileLayer.bed.x}
3792
+ y={tileLayer.bed.y}
3793
+ width={tileLayer.bed.w}
3794
+ height={tileLayer.bed.h}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3795
  />
3796
  {tileLayer.items.map((t) => (
3797
  <image
 
4575
  </div>
4576
  )}
4577
  </div>
4578
+ {/* ═══════════════════════════════════════════════════════════════════════════════════
4579
+ THE ROUTE PANEL β€” rebuilt for owner items 2, 4, 6, 8 and 9.
4580
+
4581
+ ⭐⭐ ITEM 2 IS THE STRUCTURAL ONE AND IT IS WHY THIS IS ONE REBUILD RATHER THAN FIVE
4582
+ EDITS. The panel used to render its entire body inside `selectedPids.size >= 2`, so
4583
+ clicking Route with nothing chosen produced a box containing one sentence telling you
4584
+ off. The owner's answer: show the navigation, empty. So the chrome, the travel mode,
4585
+ the stop list and the record search are UNCONDITIONAL, and only the parts that
4586
+ genuinely describe a solved route (the distance, the visit numbers, the save target)
4587
+ wait for `plan`.
4588
+
4589
+ β›” `plan` IS NULL UNTIL `routeOn` FLIPS **AND** TWO STOPS CAN BE ROUTED, so every read
4590
+ of `plan.*` below sits inside a `plan &&`. The old code was safe only because the whole
4591
+ body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
4592
+ selected is a crash, not a blank.
4593
+ ═══════════════════════════════════════════════════════════════════════════════════ */}
4594
+ {mapNavigator === "routes" && (
4595
+ <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
4596
+ {navigatorTabs}
4597
+ {/* D-599 / W46-T22 - `zones` is the vocabulary a Route's Zone selector offers. It
4598
+ is already loaded here to draw the map, so RouteNav gets a pass-through and
4599
+ never a second fetch of its own. */}
4600
+ <RouteNav
4601
+ routes={namedRoutes}
4602
+ folders={routeFolders}
4603
+ selectedIds={selectedRouteIds}
4604
+ activeRouteId={activeRouteId}
4605
+ sources={routeSources}
4606
+ storageKey={tableKey}
4607
+ createdRoute={createdRoute}
4608
+ onCreatedDismiss={() => setCreatedRoute(null)}
4609
+ onToggle={(route) => void toggleNamedRoute(route)}
4610
+ onActiveRouteChange={setActiveRouteId}
4611
+ onOpenRecord={onOpen}
4612
+ stopLabels={routeStopLabels}
4613
+ stopCoords={routeStopCoords}
4614
+ roundTrip={roundTrip}
4615
+ onRoundTripChange={(value) => {
4616
+ if (value) setRouteEndPid(null);
4617
+ // A saved/manual order is an intentional route, but an endpoint change asks for
4618
+ // a fresh constrained solve. Leaving it in place would make the dropdown move
4619
+ // without changing the painted or timed route.
4620
+ setRouteOrder(null);
4621
+ setRoundTrip(value);
4622
+ }}
4623
+ routeStartPid={routeStartPid}
4624
+ routeEndPid={routeEndPid}
4625
+ onRouteStartChange={(pid) => {
4626
+ setRouteOrder(null);
4627
+ setRouteStartPid(pid);
4628
+ if (pid === routeEndPid) setRouteEndPid(null);
4629
+ }}
4630
+ onRouteEndChange={(pid) => { setRouteOrder(null); setRouteEndPid(pid); }}
4631
+ onStopAdded={(updated) => setNamedRoutes((current) => current.map((item) =>
4632
+ item.id === updated.id
4633
+ ? { ...item, ...updated, folderId: item.folderId, navOrder: item.navOrder }
4634
+ : item))}
4635
+ onCreate={createNamedRoute}
4636
+ onMoveToOrder={moveNamedRouteStop}
4637
+ onUpdate={updateNamedRoute}
4638
+ onDuplicate={duplicateNamedRoute}
4639
+ onDelete={deleteNamedRoute}
4640
+ onShare={shareNamedRoute}
4641
+ onRouteMove={moveNamedRoute}
4642
+ onRouteReorder={reorderNamedRoutes}
4643
+ onFolderCreate={createNamedRouteFolder}
4644
+ onFolderUpdate={updateNamedRouteFolder}
4645
+ onFolderDelete={deleteNamedRouteFolder}
4646
+ onFolderReorder={reorderNamedRouteFolders}
4647
+ onCreateStart={() => setSaveTarget("")}
4648
+ mapLinks={activeRouteMaps.links}
4649
+ mapLinkRefusal={activeRouteMapsRefusal}
4650
+ deliveries={routeDeliveries}
4651
+ assignees={routeAssignees?.people ?? null}
4652
+ zones={zones || []}
4653
+ routeToday={routeAssignees?.today ?? null}
4654
+ assigneeError={routeAssigneeError}
4655
+ onSchedule={scheduleNamedRouteDelivery}
4656
+ onDeleteDelivery={deleteNamedRouteDelivery}
4657
+ />
4658
+ {routePinNotice && (
4659
+ <span className="cg-w44-route-warning" role="status">{routePinNotice}</span>
4660
+ )}
4661
+ {routeSelectionWarning && (
4662
+ <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
4663
+ )}
4664
+ </aside>
4665
+ )}
4666
+ {zoneChooserPanelOpen && (
4667
+ <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
4668
+ {navigatorTabs}
4669
+ <div className="cg-route-popover-head">
4670
+ <button type="button" className="cg-route-index-back" onClick={closeZoneChooser}>Back</button>
4671
+ <span className="cg-views-title">Zones</span>
4672
+ </div>
4673
+ <div className="cg-map-zones" role="group" aria-label="Choose visible Zones">
4674
+ <div id="cg-map-zone-choices" className="cg-map-zone-choices" role="group" aria-label="Visible map Zones">
4675
+ {(zones || []).length === 0 ? (
4676
+ <span className="cg-map-zone-empty">No Zones yet.</span>
4677
+ ) : (zones || []).map((zone) => (
4678
+ <div className="cg-map-zone-option" key={zone.id}>
4679
+ <label className="cg-map-zone-choice">
4680
+ <input
4681
+ type="checkbox"
4682
+ checked={activeZoneIds.has(zone.id)}
4683
+ disabled={!zone.visible}
4684
+ onChange={(event) => toggleZone(zone, event.target.checked)}
4685
+ />
4686
+ <span className="cg-map-zone-swatch" style={{ backgroundColor: zone.color }} aria-hidden="true" />
4687
+ <span>{zone.visible ? zone.name : `${zone.name} (hidden)`}</span>
4688
+ </label>
4689
+ <button type="button" className="cg-map-zone-edit"
4690
+ disabled={normalizedCustomerZones && !zone.permission?.canEdit}
4691
+ onClick={() => beginEditZone(zone)} aria-label={`Edit ${zone.name}`}>
4692
+ Edit
4693
+ </button>
4694
+ </div>
4695
+ ))}
4696
+ </div>
4697
+ <button type="button" className="cg-btn cg-btn--primary" onClick={beginNewZone}>New Zone</button>
4698
+ {/* β›” W46-T28 β€” `zoneErr` USED TO RENDER IN THE EDITOR PANEL ONLY, and half the
4699
+ things that set it happen with the editor closed: `persistZoneGeometry` fires
4700
+ from a boundary drag and now from a vertex drag, both of which happen right
4701
+ here on the map with this list open. A rejected reshape would have failed in
4702
+ silence, the shape snapping back with no reason given. Standing rule 1: a
4703
+ refusal is reported, never silently enforced. */}
4704
+ {zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
4705
+ </div>
4706
+ </aside>
4707
+ )}
4708
+ {zoneEditorPanelOpen && (
4709
+ <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
4710
+ {navigatorTabs}
4711
+ <div className="cg-route-popover-head">
4712
+ <button type="button" className="cg-route-index-back" onClick={closeZoneEditor}>Back to Zones</button>
4713
+ <span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
4714
+ </div>
4715
+ <div className="cg-map-zones cg-map-zone-editor">
4716
+ <label className="cg-map-zone-control">
4717
+ Zone name
4718
+ <input
4719
+ className="cg-input"
4720
+ value={zoneName}
4721
+ maxLength={120}
4722
+ aria-label="Zone name"
4723
+ placeholder="Name this Zone"
4724
+ onChange={(event) => setZoneName(event.target.value)}
4725
+ />
4726
+ </label>
4727
+ <fieldset className="cg-zone-shape-picker">
4728
+ <legend>Boundary</legend>
4729
+ <div role="group" aria-label="Zone boundary shape">
4730
+ <button type="button" aria-pressed={zoneDrawShape === "polygon"}
4731
+ onClick={() => setZoneDrawShape("polygon")}>Polygon</button>
4732
+ <button type="button" aria-pressed={zoneDrawShape === "circle"}
4733
+ onClick={() => setZoneDrawShape("circle")}>Circle</button>
4734
+ </div>
4735
+ <span>Choose a shape, then drag on the map, or draw it by clicking.</span>
4736
+ {!zoneKeyboardDraft ? (
4737
+ <button type="button" className="cg-link-btn cg-zone-draw-btn" onClick={startKeyboardZoneDrawing}>
4738
+ <DrawZoneIcon />
4739
+ Draw by clicking
4740
+ </button>
4741
+ ) : (
4742
+ <>
4743
+ {/* β›”β›” W46-T28 β€” "FINISH SHAPE" IS THE MISSING CONTROL, not a convenience.
4744
+ Pressing Enter only commits the outline while the MAP holds focus, and
4745
+ naming the Zone moves focus into the input beside this. Without a button
4746
+ in the panel, the only ending on offer was "Stop drawing", which throws
4747
+ the points away, so a drawn shape could never reach the Save button. */}
4748
+ <div className="cg-zone-draw-actions">
4749
+ <button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
4750
+ onClick={() => { finishZoneDraft(); }}>
4751
+ <DrawZoneIcon />
4752
+ Finish shape
4753
+ </button>
4754
+ <button type="button" className="cg-link-btn cg-zone-draw-btn"
4755
+ onClick={() => { setZoneKeyboardDraft(null); setZoneErr(null); }}>
4756
+ Stop drawing
4757
+ </button>
4758
+ </div>
4759
+ <span role="status" aria-live="polite">
4760
+ {zoneKeyboardDraft.shape === "polygon"
4761
+ ? `${zoneKeyboardDraft.points.length} ${zoneKeyboardDraft.points.length === 1 ? "vertex" : "vertices"}. Click the map to add one, then choose Finish shape, or press Enter on the map.`
4762
+ : zoneKeyboardDraft.center
4763
+ ? "Center placed. Click its edge, then choose Finish shape."
4764
+ : "Click the map to place the circle center, then click its edge."}
4765
+ </span>
4766
+ </>
4767
+ )}
4768
+ </fieldset>
4769
+ {/* ⭐⭐ W47-T03, RULING R4 β€” THE FINISHED SHAPE CARRIES ITS OWN TWO ENDINGS.
4770
+ Before this there was no such thing as a finished-but-unsaved Zone on screen:
4771
+ "Finish shape" cleared the only painted state and the user was left holding a
4772
+ boundary they could not see, in front of a primary button that gave no sign it
4773
+ now had something to save. The pair sits exactly where Finish shape / Stop
4774
+ drawing were, because it is the same flow one step later.
4775
+ β›” SAVE GOES THROUGH `saveZone`, NOT A SECOND WRITE PATH. `saveZone` already
4776
+ reads `drawnZoneGeometry`, already states its own refusal in `zoneErr` when the
4777
+ name is missing, and already clears the geometry on success so this row and the
4778
+ dashed shape retire together the moment the solid saved Zone appears.
4779
+ ⚠ Discard clears the geometry ONLY. It does not close the editor or reset the
4780
+ name and colour: throwing away a boundary the user disliked should not also
4781
+ throw away the two fields they typed before drawing it. */}
4782
+ {!zoneKeyboardDraft && drawnZoneGeometry && (
4783
+ <>
4784
+ <div className="cg-zone-draw-actions cg-zone-unsaved-actions">
4785
+ <button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
4786
+ disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
4787
+ onClick={() => { void saveZone(zoneEditor || undefined); }}>
4788
+ Save zone
4789
+ </button>
4790
+ <button type="button" className="cg-link-btn cg-zone-draw-btn"
4791
+ onClick={() => { setDrawnZoneGeometry(null); setZoneErr(null); }}>
4792
+ Discard
4793
+ </button>
4794
+ </div>
4795
+ <span className="cg-zone-unsaved-note" role="status" aria-live="polite">
4796
+ Shape finished. It is not saved yet, and shows as the dashed outline on the
4797
+ map until you choose Save zone.
4798
+ </span>
4799
+ </>
4800
+ )}
4801
+ {zoneEditor && (
4802
+ <button
4803
+ type="button"
4804
+ className="cg-btn"
4805
+ disabled={zoneBusy || (normalizedCustomerZones && !zoneEditor.permission?.canEdit)}
4806
+ onClick={() => void setZoneVisible(zoneEditor, !zoneEditor.visible)}
4807
+ >
4808
+ {zoneEditor.visible ? "Hide Zone" : "Show Zone"}
4809
+ </button>
4810
+ )}
4811
+ <label className="cg-map-zone-control">
4812
+ Color
4813
+ <select className="cg-route-select" value={zoneColor} aria-label="Zone color" onChange={(event) => setZoneColor(event.target.value)}>
4814
+ {ZONE_COLOR_CHOICES.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}
4815
+ </select>
4816
+ </label>
4817
+ {/* ⭐ OWNER 2026-08-31 - the opacity is a dial now, not a constant. It sits beside
4818
+ Color because both are how a Zone READS rather than what it covers, and it takes
4819
+ effect on every Zone the moment it moves: the value is the custom property the
4820
+ saved-Zone rule already consumes.
4821
+ ⚠ The reading is shown as a PERCENTAGE because that is the unit the instruction
4822
+ was given in ("80% opacity"), while the stored value stays the 0-1 fraction every
4823
+ consumer expects - the conversion happens at this boundary and nowhere else. */}
4824
+ <label className="cg-map-zone-control">
4825
+ Fill opacity
4826
+ <input
4827
+ type="range"
4828
+ className="cg-zone-opacity-range"
4829
+ min={0}
4830
+ max={100}
4831
+ step={5}
4832
+ value={Math.round(zoneFillOpacity * 100)}
4833
+ aria-label="Zone fill opacity"
4834
+ aria-valuetext={`${Math.round(zoneFillOpacity * 100)} percent`}
4835
+ onChange={(event) => setZoneFillOpacity(Number(event.currentTarget.value) / 100)}
4836
+ />
4837
+ <span className="cg-zone-opacity-read">{Math.round(zoneFillOpacity * 100)}%</span>
4838
+ </label>
4839
+ {/* β›”β›” W46-T28 β€” A MISSING NAME OR BOUNDARY NO LONGER DISABLES THIS BUTTON, and
4840
+ that is the point rather than a loosening. A disabled control cannot say why it
4841
+ is disabled, so the owner's "it won't even let me save" arrived with no reason
4842
+ on screen at all. `saveZone` already has the message for both cases ("Name a
4843
+ Zone and draw its boundary on the map.") and `zoneErr` renders at the foot of
4844
+ this panel, so letting the click through turns a silent refusal into a stated
4845
+ one. Permission and in-flight state still disable it: those are not the user's
4846
+ mistake to correct. */}
4847
+ <button
4848
+ type="button"
4849
+ className="cg-btn cg-btn--primary"
4850
+ disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
4851
+ onClick={() => {
4852
+ // An outline still being drawn is committed first, and its geometry handed
4853
+ // straight down: state set in this tick is not readable from `saveZone`.
4854
+ if (zoneKeyboardDraft) {
4855
+ const pending = finishZoneDraft();
4856
+ // `finishZoneDraft` has already put the real reason in `zoneErr`. Falling
4857
+ // through would overwrite it with a vaguer one.
4858
+ if (!pending) return;
4859
+ void saveZone(zoneEditor || undefined, pending);
4860
+ return;
4861
+ }
4862
+ void saveZone(zoneEditor || undefined);
4863
+ }}
4864
+ title={drawnZoneGeometry || zoneKeyboardDraft
4865
+ ? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
4866
+ : zoneEditor ? "Save Zone details" : "Draw a boundary before saving"}
4867
+ >
4868
+ {zoneBusy ? "Saving Zone" : zoneEditor ? "Update Zone" : "Save Zone"}
4869
+ </button>
4870
+ {zoneEditor && (!normalizedCustomerZones || zoneEditor.permission?.canDelete) && (
4871
+ <button type="button" className="cg-btn cg-btn--danger" disabled={zoneBusy}
4872
+ onClick={() => setPendingZoneDelete(zoneEditor)}>
4873
+ Delete Zone
4874
+ </button>
4875
+ )}
4876
+ {zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
4877
+ </div>
4878
+ </aside>
4879
+ )}
4880
+ </div>
4881
+ {/* ═══════ W51-T28 / R6 β€” EVERY CONFIRM THIS SURFACE ASKS FOR, IN ONE PLACE ═══════════
4882
+ β›” MOUNTED AT THE COMPONENT ROOT, NOT BESIDE THE CONTROL THAT OPENS IT. Two of these
4883
+ were `window.confirm` calls inside a panel, and one lived inside the routes popover's
4884
+ own subtree. A dialog rendered inside a subtree that closes itself in the same handler
4885
+ unmounts before it paints, and the person sees nothing at all.
4886
+ β›” NO Z-INDEX IS SET HERE AND NONE IS NEEDED, AND W51-T32 MADE THAT MORE TRUE RATHER
4887
+ THAN LESS. The three navigator panels are now ordinary items in the map row, painting in
4888
+ the flow at the browser's default stacking; only the transient selection notice still
4889
+ floats at `--cg-z-mapchrome` (65). `ConfirmDialog` portals to <body> at `--cg-z-overlay`
4890
+ (110), so dialog over panel over pins still holds on the scale in `index.css :root`, and
4891
+ "raising" the dialog would be re-breaking the three-way order by hand. */}
4892
+ <ConfirmDialog
4893
+ open={pendingZoneDelete !== null}
4894
+ title={`Delete ${pendingZoneDelete?.name ?? "Zone"}?`}
4895
+ /* ⭐ A REAL COUNT, NOT A ROUNDED REASSURANCE (standing rules 1 and 8). `memberships` is
4896
+ the Zone's member pids and is already on the object the chooser drew, so the sentence
4897
+ states what deleting the shape actually leaves behind. */
4898
+ body={(() => {
4899
+ const kept = (pendingZoneDelete?.memberships || []).length;
4900
+ return kept === 1
4901
+ ? "1 stop keeps its records; the zone shape is removed"
4902
+ : `${kept.toLocaleString()} stops keep their records; the zone shape is removed`;
4903
+ })()}
4904
+ confirmLabel="Delete zone"
4905
+ tone="destructive"
4906
+ busy={zoneBusy}
4907
+ /* β›”β›” CLEARED ON SETTLE, NOT BEFORE THE DISPATCH, AND THE ORDER IS THE WHOLE POINT OF
4908
+ `busy`. Clearing first closes the dialog in the same batched render, so `open` is
4909
+ already false by the time `zoneBusy` flips and the locked buttons never paint: a prop
4910
+ that cannot render, with a gate needle pinning it, is precisely the shape this file's
4911
+ other legs exist to refuse. Re-entrancy is covered by `busy` disabling both buttons and
4912
+ by `ConfirmDialog` refusing to dismiss while busy, so nothing is lost by waiting. */
4913
+ onConfirm={() => {
4914
+ const zone = pendingZoneDelete;
4915
+ if (!zone || zoneBusy) return;
4916
+ void deleteZone(zone).finally(() => setPendingZoneDelete(null));
4917
+ }}
4918
+ onCancel={() => setPendingZoneDelete(null)}
4919
+ />
4920
+ <ConfirmDialog
4921
+ open={pendingRouteInclude !== null}
4922
+ /* ⚠ A SHORT NOUN PHRASE, per the kit's own contract and DESIGN.md section 2: the
4923
+ question lives in the body, and the button names the act. The zone delete ABOVE is
4924
+ the ONE title written as a question, because its exact wording is the done-when. */
4925
+ title="Route outside this filter"
4926
+ body={`${pendingRouteInclude?.name ?? "This route"} is outside this filter. Only this route's managed membership group is included.`}
4927
+ confirmLabel="Include route"
4928
+ tone="primary"
4929
+ onConfirm={confirmPendingRouteInclude}
4930
+ onCancel={() => setPendingRouteInclude(null)}
4931
+ />
4932
+ {/* ⚠ UNREACHABLE TODAY, AND CONVERTED ANYWAY. R14 (W50-T14) retired the pin click and the
4933
+ pin Enter, which were `requestRoutePinMembership`'s only two callers, so nothing sets
4934
+ `routePinPrompt` at present. The machinery is deliberately kept whole and wired
4935
+ (verify_map.py's `single-stop-door` / `actual-membership` / `visible-confirmation` legs
4936
+ all still hold it), so leaving the one native-shaped prompt behind would have left R6
4937
+ half-applied for whoever reinstates a door. */}
4938
+ <ConfirmDialog
4939
+ open={routePinPrompt !== null}
4940
+ title={routePinPrompt?.present ? "Add a route stop" : "Remove a route stop"}
4941
+ body={routePinPrompt
4942
+ ? `${routePinPrompt.title} will be ${routePinPrompt.present ? "added to" : "removed from"} ${activeNamedRoute?.name || "this Route"}.`
4943
+ : undefined}
4944
+ confirmLabel={routePinPrompt?.present ? "Add stop" : "Remove stop"}
4945
+ tone={routePinPrompt?.present ? "primary" : "destructive"}
4946
+ busy={routePinBusy}
4947
+ onConfirm={() => void confirmRoutePinMembership()}
4948
+ onCancel={() => setRoutePinPrompt(null)}
4949
+ />
4950
  </div>
4951
  );
4952
  }
web/src/customer-grid/OverlaySurface.tsx CHANGED
@@ -17,6 +17,7 @@ import type {
17
  RefObject,
18
  } from "react";
19
  import { createPortal } from "react-dom";
 
20
  import { computeOverlayPosition } from "./overlayPlacement";
21
  import type { Placement as OverlayPlacement } from "./overlayPlacement";
22
 
@@ -130,6 +131,9 @@ interface OverlayLayerOptions {
130
  restoreFocus?: boolean;
131
  trapFocus?: boolean;
132
  outsideElements?: Array<HTMLElement | null>;
 
 
 
133
  }
134
 
135
  /** Shared dismissal/focus contract for anchored menus and fixed drawers. */
@@ -142,6 +146,7 @@ export function useOverlayLayer({
142
  restoreFocus = true,
143
  trapFocus = false,
144
  outsideElements = [],
 
145
  }: OverlayLayerOptions): void {
146
  const id = useId();
147
  const stack = useContext(OverlayStackContext);
@@ -152,6 +157,11 @@ export function useOverlayLayer({
152
 
153
  useEffect(() => stack?.register(id), [id, stack]);
154
 
 
 
 
 
 
155
  useEffect(() => {
156
  const onPointerDown = (event: PointerEvent) => {
157
  if (!dismissOnOutside || (stack && !stack.isTop(id))) return;
@@ -167,17 +177,11 @@ export function useOverlayLayer({
167
  };
168
  const onKeyDown = (event: KeyboardEvent) => {
169
  if (stack && !stack.isTop(id)) return;
170
- if (event.key === "Escape") {
171
- event.preventDefault();
172
- event.stopPropagation();
173
- if (
174
- document.activeElement instanceof HTMLElement &&
175
- panelRef.current?.contains(document.activeElement)
176
- )
177
- document.activeElement.blur();
178
- dismissRef.current();
179
- return;
180
- }
181
  if (event.key !== "Tab" || !trapFocus) return;
182
  const focusable = Array.from(
183
  panelRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []
 
17
  RefObject,
18
  } from "react";
19
  import { createPortal } from "react-dom";
20
+ import { useEscapeClose } from "../ui/useEscapeClose";
21
  import { computeOverlayPosition } from "./overlayPlacement";
22
  import type { Placement as OverlayPlacement } from "./overlayPlacement";
23
 
 
131
  restoreFocus?: boolean;
132
  trapFocus?: boolean;
133
  outsideElements?: Array<HTMLElement | null>;
134
+ /** Escape cancels a live text edit inside the panel before it closes it. Default
135
+ * FALSE, which is the one-press blur-and-close every overlay had before W51-T01. */
136
+ cancelEditFirst?: boolean;
137
  }
138
 
139
  /** Shared dismissal/focus contract for anchored menus and fixed drawers. */
 
146
  restoreFocus = true,
147
  trapFocus = false,
148
  outsideElements = [],
149
+ cancelEditFirst = false,
150
  }: OverlayLayerOptions): void {
151
  const id = useId();
152
  const stack = useContext(OverlayStackContext);
 
157
 
158
  useEffect(() => stack?.register(id), [id, stack]);
159
 
160
+ // The ONE Escape path for this layer. Mounted means claiming, so `active` is true.
161
+ const onEscape = useCallback(() => dismissRef.current(), []);
162
+ const escapeContainer = useCallback(() => panelRef.current as HTMLElement | null, [panelRef]);
163
+ useEscapeClose(true, onEscape, { cancelEditFirst, container: escapeContainer });
164
+
165
  useEffect(() => {
166
  const onPointerDown = (event: PointerEvent) => {
167
  if (!dismissOnOutside || (stack && !stack.isTop(id))) return;
 
177
  };
178
  const onKeyDown = (event: KeyboardEvent) => {
179
  if (stack && !stack.isTop(id)) return;
180
+ // β›” ESCAPE IS NOT HANDLED HERE ANY MORE (W51-T01). It is arbitrated by the ONE
181
+ // module-level stack in `ui/useEscapeClose`, registered by this hook above, because
182
+ // `OverlayStackContext` cannot order this layer against a portalled dialog that
183
+ // never joins it β€” a menu opened inside a ConfirmDialog used to race the dialog.
184
+ // Outside-click still uses the context stack, unchanged, on purpose.
 
 
 
 
 
 
185
  if (event.key !== "Tab" || !trapFocus) return;
186
  const focusable = Array.from(
187
  panelRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -1,10 +1,16 @@
1
- import { lazy, Suspense, useEffect, useId, useLayoutEffect, useMemo, useRef, useState }
2
- from "react";
3
  import type { ReactNode, TextareaHTMLAttributes } from "react";
4
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
5
 
6
  /**
7
- * ⭐ WAVE-27 item 20 (R5 / contract C10) β€” the embedded grid a Details section renders.
 
 
 
 
 
 
8
  *
9
  * β›” LAZY BECAUSE THE IMPORT IS A CYCLE, not because it is big. `CustomerGrid` mounts
10
  * `RecordDetail`; a static import back the other way is `A -> B -> A`, which bundlers resolve by
@@ -12,9 +18,9 @@ import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
12
  * module happens to evaluate first, i.e. the kind that survives every local test and lands in
13
  * production. `React.lazy` defers the resolution to first RENDER, by which point both modules
14
  * exist. It also composes with item 34's route-level splitting instead of fighting it: a reader
15
- * who never opens a Details tab never downloads a second copy of anything.
16
  */
17
- const LinkedGrid = lazy(() => import("./CustomerGrid"));
18
  import {
19
  automationDetail,
20
  automationState,
@@ -36,19 +42,20 @@ import { actionHref } from "./display";
36
  import JsonViewer, { CodeViewer } from "./JsonViewer";
37
  import { StarRow, StarIcon } from "./Stars";
38
  import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditField, ratingMax } from "./types";
39
- /* ⭐⭐ W41-T44 (owner instruction 25) β€” THE PIVOT'S VOCABULARY IS IMPORTED, NEVER RESTATED.
40
- W41-T42 declared all of it in `types.ts` precisely because this ticket and W41-T43 open the
41
- same feature through other doors and neither may edit that file. A second `buildPivotRequest`
42
- inlined here would be a second opinion about what a pivot request is, and two spellings of one
43
- wire contract is how a feature ships dead with both halves correct
44
  [[two-lanes-one-contract-dead-feature]]. */
45
- import { buildPivotRequest, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOWS, PIVOT_WINDOW_LABELS,
46
- pivotResponse, relationalTargets } from "./types";
47
- import type { CustomerDoc, DisplaySpec, Field, FilterRule, PivotResponse, PivotWindow,
48
- Row, Viewer } from "./types";
49
- /* The pivot is a SERVER question (contract C10), so this panel needs the same two constants the
50
- grid's own pivot fetch uses. One door, one credential mode. */
51
- import { API_V1, CREDENTIALS } from "../apiContract";
 
 
52
 
53
  /**
54
  * ⭐⭐ WAVE-34 (owner ruling R13) β€” whose value sits in this enrichment cell, in words.
@@ -333,74 +340,23 @@ function SixDots() {
333
  );
334
  }
335
 
336
- /* ══════════════════════════════════════════════════════════════════════════════════════════
337
- ⭐⭐ W41-T44 Β· OWNER INSTRUCTION 25 Β· RULING R12 Β· CONTRACTS C4 + C5 + C7 β€”
338
- A RECORD PIVOTS TO ITS OWN RELATED RECORDS.
339
-
340
- Owner: *"opening a customer record offers Relational, and choosing Odoo Products shows only
341
- that customer's ordered SKUs."*
342
 
343
- β›”β›” THIS IS **NOT** `embeddedRecordIds`, AND THE DISTINCTION IS THE WHOLE TICKET. An embedded
344
- grid FETCHES ITS WHOLE TABLE and filters to an id list in the browser (the note on `openLinks`
345
- below states it, and it is why the link sections are collapsed until asked for). A record
346
- pivot built that way would pull the entire product table into the tab to show one customer's
347
- SKUs, which is standing rule 1 in the direction that matters: not a cap, but an uncapped
348
- connected-source table dragged client-side to be filtered locally. The pivot's rows come from
349
- contract C10's endpoint, server side, and this panel renders what comes back.
350
 
351
- β›” NO JOIN IS COMPUTED HERE, for the same reason the grid computes none. Customers to products
352
- is two hops through `sales_lines`, and the naive join (`sales_lines.product`) yields a column
353
- of nulls that reads as "never sold". This names a source, a target, a link field and ONE
354
- record; the resolution belongs to the server.
355
- ══════════════════════════════════════════════════════════════════════════════════════════ */
356
-
357
- /**
358
- * β›”β›” CONTRACT C4's TWO BRIDGE COLUMNS, AND THIS CONSTANT IS THE ONLY PLACE THEY ARE SPELLED.
359
- *
360
- * C4: *"`product_data.product_id` ("Odoo ID", `type:int`) is the relational bridge, mirroring
361
- * `customer_data.partner_id`. It is instruction 25's answer."* So the id a record pivots ON is
362
- * its Odoo id, carried by one of exactly these two columns, and the order is the order the
363
- * contract names them in.
364
- *
365
- * ⚠ `customer_data.partner_id` EXISTS TODAY (`odoo_customers.yml`, W33-T43, and its `identity`
366
- * line says there is one id per row and no second one). `product_data.product_id` DOES NOT exist
367
- * on this branch: it is C4's own server work and it is not lane D's. Until it lands, a product
368
- * record finds no bridge here and this panel says so rather than sending a filter naming a
369
- * column that is not there.
370
- *
371
- * β›” NOT `pid` AS A FALLBACK. A pid is the row identity, and the filter tree is compiled against
372
- * DECLARED COLUMNS (`filter_sql.compile_filter_tree`); the pid set travels as `member_ids` on a
373
- * different rail entirely. A leaf naming `pid` would be dropped on the way in, which is a filter
374
- * that silently matches everything, which is every record's related rows presented as this one's.
375
- */
376
- const RECORD_BRIDGE_KEYS = ["partner_id", "product_id"] as const;
377
-
378
- /**
379
- * ⭐ THE ONE FILTER THAT NAMES THIS RECORD. T44's `how:` line calls the record pivot *"W41-T42's
380
- * engine with a one-element member set"*, and this is that element: ONE leaf in the REQUEST, not
381
- * one id list filtered in the client.
382
- *
383
- * ⚠ `null` MEANS "THIS TABLE HAS NO BRIDGE COLUMN, OR THIS RECORD'S IS BLANK", and it is refused
384
- * rather than smoothed. An unfiltered pivot request would ask the server for the related records
385
- * of the WHOLE table and this panel would present the answer under one record's name, which is a
386
- * wrong answer rather than a missing one.
387
- */
388
- function recordPivotFilter(fields: Field[], record: Row): FilterRule | null {
389
- for (const key of RECORD_BRIDGE_KEYS) {
390
- if (!fields.some((f) => f.key === key)) continue;
391
- const value = record[key];
392
- /* β›” ZERO IS SKIPPED, AND IT IS NOT AN OFF-BY-ONE. An Odoo id is a positive integer, so `0`
393
- here means the derived column produced nothing for this row, not that the record is id 0.
394
- A leaf carrying `"0"` is an ACTIVE rule (only an EMPTY `value` is inactive), so it would be
395
- sent, match nothing, and print "No related records for this record in this time window" --
396
- the one line reserved for a served answer of genuinely none. A wrong answer wearing the
397
- shape of a true one is worse than the refusal below. */
398
- if (value === null || value === undefined || value === "") continue;
399
- if (!(Number(value) > 0)) continue;
400
- return { colId: key, op: "eq", value: String(value) };
401
- }
402
- return null;
403
- }
404
 
405
  /** The record drawer's equivalent of the grid picker's `Add option` row. */
406
  function ChoiceCreateInput({
@@ -444,24 +400,118 @@ function ChoiceCreateInput({
444
  }
445
 
446
  /**
447
- * ⭐ THE SAME FOUR STATES `CustomerGrid` KEEPS, AND THE SAME WORDS FOR THEM. `absent` is not an
448
- * empty result: it is "the endpoint that answers this question is not there, or did not answer"
449
- * (C10's server half is W41-T20). Collapsing it into a served answer of zero rows would put "no
450
- * related records" on screen as the answer to a question nobody has asked yet.
451
  *
452
- * ⚠ Declared locally because `CustomerGrid`'s copy is a local type in that module and `types.ts`
453
- * is closed to this ticket. It is the vocabulary that must not fork, and it has not: four names,
454
- * same four meanings.
 
 
 
 
 
455
  */
456
- type RecordPivotState =
457
- | { status: "idle" }
458
- | { status: "loading" }
459
- | { status: "absent" }
460
- | { status: "ok"; answer: PivotResponse };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
 
462
  export default function RecordDetail({
463
- fields,
464
- record,
 
 
 
 
 
465
  titleKey,
466
  positionLabel,
467
  canPrev,
@@ -489,7 +539,55 @@ export default function RecordDetail({
489
  const panelRef = useRef<HTMLDivElement>(null);
490
  const titleId = useId();
491
  const tabsId = useId();
492
- const title = String(record[titleKey] ?? "Untitled");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
  // Wave 19 (item 12): `scope` joins the predicate β€” the comments rail addresses a server
494
  // endpoint per topic now, so a host that names no surface gets no rail rather than a rail
495
  // pointed at a guess. In practice CustomerGrid always names one; this is the fail-closed edge.
@@ -565,7 +663,12 @@ export default function RecordDetail({
565
 
566
  // `defaultOrder` is the whole vocabulary, so this is a PERMUTATION of it and nothing else β€”
567
  // a saved layout can reorder the panel, never change what is in it. See recordLayout.ts.
568
- const orderedKeys = resolveFieldOrder(pendingOrder ?? recordLayout, defaultOrder);
 
 
 
 
 
569
 
570
  // The key being dragged, twice over, written only in `onDragStart`/`onDragEnd` and always
571
  // together. The REF is what the handlers read: `dragover` must call preventDefault for a
@@ -599,175 +702,224 @@ export default function RecordDetail({
599
 
600
  const commitOrder = (next: string[]) => {
601
  if (next === orderedKeys) return; // moveKey/nudgeKey return the input on a no-op
 
 
 
 
602
  setPendingOrder(next);
603
  onRecordLayout?.(next);
604
  };
605
 
606
- // --- C-EMBED (item 13) β€” Fields | Insights ---------------------------------------------
607
- //
608
- // The owner's framing: in the record, the FILTER IS THE LOCK β€” you are looking at one
609
- // customer, so the pid set is not a control, it is the premise. Hence `locked`, and hence a
610
- // panel that is otherwise the same component the table mounts, with the same server, the
611
- // same buckets and the same additivity rules. Two implementations of "sales by month" that
612
- // could disagree is the thing worth avoiding here, not the duplicated markup.
613
- //
614
- // The display state is LOCAL and deliberately not persisted (v1): a bucket chosen while
615
- // reading one customer is a way of looking, not a property of the record. `onDisplay` is
616
- // passed all the same β€” the panel DISABLES its controls without one, and the contract says
617
- // the controls stay live.
618
- // No scope, no Insights β€” see the prop's note. `tab` is forced back rather than merely
619
- // unreachable, so a host that stops supplying the scope mid-session cannot leave the modal
620
- // showing a panel it can no longer address.
621
- // ⭐ WAVE-27 item 20 (owner ruling R5, contract C10) β€” the tab is "Details" now, and the
622
- // rename is the smaller half. It USED to be "Insights" and hold exactly one thing, a
623
- // time-series panel; R5 makes it the record's whole relational context β€” every database this
624
- // record LINKS to, rendered as a real grid of just its linked rows β€” with the time series
625
- // demoted to one section among them.
626
- const [tab, setTab] = useState<"fields" | "details">("fields");
627
- const canInsights = scope != null;
628
- const activeTab = canInsights ? tab : "fields";
629
- // `mode: "timeseries"` is the only required member of DisplaySpec and it is a truthful one
630
- // here: this IS the time-series reading of the record. Every other key is absent, which the
631
- // panel reads as "use my defaults".
632
- const [tsDisplay, setTsDisplay] = useState<DisplaySpec>({ mode: "timeseries" });
633
- // ⚠ Memoised, not `[Number(record.pid)]` inline: the panel's fetch effect depends on `pids`
634
- // by identity, so a fresh array every render would re-fetch on every render β€” forever.
635
- const insightPids = useMemo(() => [Number(record.pid)], [record.pid]);
636
- // wave17 item 5 β€” the same population as `insightPids`, as VALUES, so a snapshot metric can
637
- // read this record's own numbers. Memoised for the identical reason the pid list is.
638
- const insightRows = useMemo(() => [record], [record]);
 
639
  /**
640
- * ⭐ WAVE-27 item 20 (R5 / C10) β€” one section per LINK column on this record's table.
641
- *
642
- * ⚠ A link cell is a COMMA-JOINED LIST OF ROW IDS (the scalar `Row` contract β€” an array cell
643
- * cannot exist here), parsed exactly the way `CustomerGrid`'s own link modal parses it: trim,
644
- * to number, keep positive integers, de-duplicate. A second parse that disagreed about a
645
- * trailing comma would show a different set of records than the picker just wrote.
646
- *
647
- * ⚠ A link with NO TARGET TABLE is skipped rather than rendered empty. `_clean_field` refuses
648
- * a `link` without its bag, so this can only be a definition older than that rule β€” and an
649
- * embedded grid of `scope: ""` would fetch the customer table and present somebody else's
650
- * records under this column's name.
651
  *
652
- * Memoised: `embeddedRecordIds` is read by identity inside the grid's own row projection, so a
653
- * fresh array per render would re-project on every keystroke in the drawer.
 
 
 
654
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
655
  /**
656
- * ⭐ WAVE-27 item 20 β€” which Details sections have been OPENED.
 
 
 
 
 
 
 
 
 
657
  *
658
- * β›” THE SECTIONS ARE COLLAPSED UNTIL ASKED FOR, and that is a correctness decision as much
659
- * as a performance one. An embedded grid FETCHES ITS WHOLE TABLE and filters to
660
- * `embeddedRecordIds` client-side (`CustomerGrid.tsx:621-628`) β€” so on an Instagram profile,
661
- * whose preset carries FOUR link columns (`posts_link`, `profile_snapshots_link`,
662
- * `post_snapshots_link`, `comments_link`), opening this tab would mount four glide canvases
663
- * and pull four tables, two of them append-only snapshot tables. The count in each heading is
664
- * already known WITHOUT the grid (it is the length of the parsed id list), so a collapsed
665
- * section still tells you what is in it.
 
666
  */
667
- const [openLinks, setOpenLinks] = useState<Set<string>>(new Set());
668
- const linkSections = useMemo(
669
- () =>
670
- fields
671
- .filter((f) => f.type === "link" && typeof f.link?.table === "string" && f.link.table)
672
- .map((f) => ({
673
- field: f,
674
- table: f.link!.table as SurfaceScope,
675
- ids: [...new Set(
676
- String(record[f.key] ?? "")
677
- .split(",")
678
- .map((part) => Number(part.trim()))
679
- .filter((pid) => Number.isInteger(pid) && pid > 0)
680
- )],
681
- })),
682
- [fields, record]
 
683
  );
684
 
685
- /* ⭐⭐ W41-T44 β€” THE RECORD-LEVEL PIVOT'S STATE. Four hooks, all at the top level of this
686
- component and all above its single `return` (there is no early return in this body, which
687
- is checked rather than assumed: a hook after one runs a different number of times on the
688
- two renders and React #310 takes the surface down [[react-hooks-order-gate]]). */
689
- /** R9 β€” what this record can pivot to IS its table's link fields. `relationalTargets` is the
690
- * ONE derivation and the grid's toolbar uses the same one. */
691
- const relTargets = useMemo(() => relationalTargets(fields), [fields]);
692
  /**
693
- * ⭐ COLLAPSED UNTIL ASKED FOR, following the link sections' own precedent one block up, and
694
- * for the reason that note gives: opening the Details tab must not fire work for a section
695
- * nobody looked at. A pivot is a server join; firing one per record opened would be the same
696
- * mistake the link sections were written to avoid, one rail over.
697
  */
698
- const [relOpen, setRelOpen] = useState(false);
699
- const [relVia, setRelVia] = useState<string | null>(null);
700
- /** R10 β€” all time is the default AND the meaning of an absent value. */
701
- const [relWindow, setRelWindow] = useState<PivotWindow>("all");
702
- const [relPivot, setRelPivot] = useState<RecordPivotState>({ status: "idle" });
703
- const relTarget = relVia ? relTargets.find((t) => t.viaField === relVia) ?? null : null;
704
- const relFilter = recordPivotFilter(fields, record);
 
 
 
 
 
 
 
 
 
705
  /**
706
- * The request, serialised, as BOTH the effect's dependency and its body β€” the grid's own
707
- * pattern, for its own reason: one string, so a re-render that changes nothing cannot re-fire
708
- * the fetch and the body can never disagree with the key that decided to send it.
709
  *
710
- * ⚠ EMPTY UNLESS ALL FOUR HOLD: the section is open, a target is chosen, the host said which
711
- * surface this is, and the record has a C4 bridge id. Each missing one has its own line on
712
- * screen; none of them is a reason to ask the server anything.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
713
  */
714
- const relRequestBody =
715
- relOpen && relTarget && relFilter && scope
716
- ? JSON.stringify(
717
- buildPivotRequest(scope, [relFilter], "and", {
718
- database: relTarget.database,
719
- viaField: relTarget.viaField,
720
- window: relWindow,
721
- config: emptyViewConfig(),
722
- })
723
- )
724
- : "";
725
  useEffect(() => {
726
- if (!relRequestBody) {
727
- setRelPivot({ status: "idle" });
728
  return;
729
  }
730
  let live = true;
731
- setRelPivot({ status: "loading" });
732
- (async () => {
733
- try {
734
- const res = await fetch(`${API_V1}/${PIVOT_PATH}`, {
735
- method: "POST",
736
- credentials: CREDENTIALS,
737
- headers: { "Content-Type": "application/json" },
738
- body: relRequestBody,
739
- });
740
- if (!live) return;
741
- if (!res.ok) {
742
- setRelPivot({ status: "absent" });
743
- return;
744
- }
745
- const answer = pivotResponse(await res.json().catch(() => null));
746
- if (!live) return;
747
- /* β›” `null` is NOT smoothed into an empty answer: "the endpoint is not there" and "this
748
- record has no related records" are different facts and only one is ours to state. */
749
- setRelPivot(answer ? { status: "ok", answer } : { status: "absent" });
750
- } catch {
751
- if (live) setRelPivot({ status: "absent" });
752
  }
 
 
 
753
  })();
754
  return () => {
755
  live = false;
756
  };
757
- }, [relRequestBody]);
758
- /* The four non-served states, kept apart in LOGIC as well as in copy, because collapsing any
759
- two of them puts a wrong answer on screen where a missing one belongs. Ordinary values, not
760
- hooks: they are re-derived every render from `relPivot` and nothing memoises usefully. */
761
- const relAnswer = relPivot.status === "ok" ? relPivot.answer : null;
762
- const relRefusal = relAnswer?.refusal ?? null;
763
- const relServed = !!relAnswer && !relRefusal && relAnswer.fields.length > 0;
764
- /** Served, and carrying no shape to paint. Every other branch is false here, so it needs its
765
- * own line or the reader gets a chooser and silence. */
766
- const relColumnless = !!relAnswer && !relRefusal && relAnswer.fields.length === 0;
767
- const relColumns = relServed && relAnswer ? relAnswer.fields : [];
768
- /** β›” STANDING RULE 1's SECOND HALF. This panel truncates nothing, so a gap between the count
769
- * and the rows can only have come from the server, and it is REPORTED rather than absorbed. */
770
- const relShort = !!relAnswer && relAnswer.targetCount > relAnswer.rows.length;
 
 
 
771
 
772
  /**
773
  * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
@@ -830,7 +982,12 @@ export default function RecordDetail({
830
  // ONE verdict, `types.mayEditField` β€” stratum + read-only-by-nature + permissions.
831
  // No second permission test anywhere below: a `formula` or `created_time` field must stay
832
  // read-only after item 9, and that is this function's answer, not a type check of mine.
833
- const mayEdit = mayEditField(field, viewer);
 
 
 
 
 
834
  // The ONE exception, and it is a vocabulary problem rather than a permission one: a `user`
835
  // field with no supplied people has nothing to offer, so it reads rather than pretends.
836
  const noVocabulary = field.type === "user" && !userOptions?.length;
@@ -1434,6 +1591,25 @@ export default function RecordDetail({
1434
  >
1435
  <div className="cg-detail-header">
1436
  <div className="cg-detail-nav">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1437
  <button
1438
  type="button"
1439
  className="cg-detail-navbtn"
@@ -1454,6 +1630,8 @@ export default function RecordDetail({
1454
  >
1455
  β€Ί
1456
  </button>
 
 
1457
  {/* ⭐⭐ W35-T29 (R5, R6) β€” THE SAME RECORD STAR AS THE GRID'S, in the drawer.
1458
  β›” THE SAME STATE, NOT A SECOND ONE: `starred`/`onStar` come from the grid's own
1459
  `useRecordStars`, so starring here and starring in the row are one act on one list.
@@ -1467,8 +1645,12 @@ export default function RecordDetail({
1467
  star floated alone in the middle of the bar, attached to nothing. Owner: *"the
1468
  'Star record' place is so out of placed there. Put it just beside the < > under
1469
  record detail."* Inside `.cg-detail-nav` it is one of three 28px keys, and the
1470
- position caption reads after them. */}
1471
- {onStar && (
 
 
 
 
1472
  <button
1473
  type="button"
1474
  className={"cg-detail-star" + (starred ? " is-on" : "")}
@@ -1480,7 +1662,9 @@ export default function RecordDetail({
1480
  <RecordStarMark size={16} filled={starred} />
1481
  </button>
1482
  )}
1483
- <span className="cg-detail-pos">{positionLabel}</span>
 
 
1484
  </div>
1485
  <button
1486
  type="button"
@@ -1502,23 +1686,45 @@ export default function RecordDetail({
1502
  </div>
1503
  </div>
1504
 
1505
- {/* C-EMBED (item 13) β€” the two ways of reading one record. This row is also
1506
- what the interleaved field list lost when its two section headings went
1507
- (see C-LAYOUT's amendment): the label for the list as a whole. */}
1508
- {canInsights && (
 
 
 
 
 
 
 
1509
  <div className="cg-record-tabs" role="tablist" aria-label="Record view">
1510
- {(["fields", "details"] as const).map((key) => (
 
 
 
 
 
 
 
 
 
 
 
1511
  <button
1512
- key={key}
1513
  type="button"
1514
  role="tab"
1515
- id={`${tabsId}-${key}`}
1516
- aria-selected={activeTab === key}
1517
  aria-controls={`${tabsId}-panel`}
1518
- className={"cg-record-tab" + (activeTab === key ? " is-on" : "")}
1519
- onClick={() => setTab(key)}
 
1520
  >
1521
- {key === "fields" ? "Fields" : "Details"}
 
 
 
1522
  </button>
1523
  ))}
1524
  </div>
@@ -1527,314 +1733,53 @@ export default function RecordDetail({
1527
  <div
1528
  className="cg-detail-body"
1529
  id={`${tabsId}-panel`}
1530
- role={canInsights ? "tabpanel" : undefined}
1531
- aria-labelledby={canInsights ? `${tabsId}-${activeTab}` : undefined}
1532
  >
1533
- {activeTab === "details" && scope ? (
1534
- <div className="cg-record-insights">
1535
- {/* ⭐ WAVE-27 item 20 (R5 / C10) β€” ONE SECTION PER LINK FIELD, each an embedded
1536
- grid of the linked database showing exactly this record's linked rows.
1537
-
1538
- ⚠ THE ROWS ARE THE PREMISE, NOT A FILTER, which is the same idea `locked`
1539
- states for the time series below: you are reading ONE record, so "which rows"
1540
- is settled by the record and the embedded grid's toolbar narrows within them.
1541
- `embeddedRecordIds` is the projection that already enforces that
1542
- (`CustomerGrid.tsx:621-628`), so nothing new decides it here. */}
1543
- {linkSections.map((sec) => (
1544
- <section className="cg-detail-section cg-detail-linksec" key={sec.field.key}>
1545
- <h3 className="cg-detail-sechead">
1546
- {sec.ids.length === 0 ? (
1547
- <span>{sec.field.label}</span>
1548
- ) : (
1549
- <button
1550
- type="button"
1551
- className="cg-detail-sectoggle"
1552
- aria-expanded={openLinks.has(sec.field.key)}
1553
- onClick={() =>
1554
- setOpenLinks((prev) => {
1555
- const next = new Set(prev);
1556
- if (next.has(sec.field.key)) next.delete(sec.field.key);
1557
- else next.add(sec.field.key);
1558
- return next;
1559
- })
1560
- }
1561
- >
1562
- {sec.field.label}
1563
- </button>
1564
- )}
1565
- <span className="cg-detail-seccount">
1566
- {sec.ids.length.toLocaleString()}{" "}
1567
- {sec.ids.length === 1 ? "record" : "records"}
1568
- </span>
1569
- </h3>
1570
- {sec.ids.length === 0 ? (
1571
- // Stated, never an empty grid. An embedded grid of nothing looks like a
1572
- // surface that failed to load; a sentence says which of the two it is.
1573
- <p className="cg-detail-secempty">
1574
- Nothing linked yet. Open the {sec.field.label} cell on the Fields tab to
1575
- link records.
1576
  </p>
1577
- ) : !openLinks.has(sec.field.key) ? null : (
1578
- <div className="cg-detail-linkgrid">
1579
- {/* ⚠ LAZY, and it is load-bearing rather than a performance nicety:
1580
- `CustomerGrid` mounts THIS component, so a static import here would be
1581
- a module cycle. `React.lazy` breaks it at the module graph (the import
1582
- only resolves when a section actually renders) and composes with the
1583
- route-level splitting rather than fighting it. */}
1584
- {/* β›” THE SHARED MARK, NEVER A SENTENCE (owner R6, and `verify_icons`
1585
- enforces it across every source file β€” it caught a "Loading…" here on
1586
- this gate's first run). `aria-label` is REQUIRED by C-SPIN: "no words"
1587
- means no words ON SCREEN, and deleting the label would take the wait
1588
- away from a screen reader entirely. */}
1589
- <Suspense
1590
- fallback={
1591
- <div className="cg-detail-secempty">
1592
- <span className="lp-spin" role="status" aria-label="Loading" />
1593
- </div>
1594
- }
1595
- >
1596
- {/* β›” ONE ATTRIBUTE IS MISSING ON PURPOSE AND IT IS THE VIEW-KIND
1597
- SWITCHER β€” `embeddedMode="browse"`. R5 asks for the FULL switcher
1598
- here; `CustomerGrid.tsx:4113` suppresses the mode control for every
1599
- embedded grid (`serverWindowed || embedded ? undefined : …`), so the
1600
- prop that distinguishes a BROWSE embed from the link PICKER embed
1601
- does not exist yet. It is requested as dated amendment A3 to contract
1602
- C10 in the wave-27 split doc (SESSION C owns `CustomerGrid.tsx`).
1603
-
1604
- Everything else in this section is already correct β€” the target
1605
- table, the pinned rows and the toolbar all work today β€” so this ships
1606
- useful rather than waiting. When the prop lands, this becomes one
1607
- added line and nothing else moves. It is deliberately NOT smuggled in
1608
- through a cast: a spread that passed an unknown prop would typecheck
1609
- forever and silently do nothing, which is the failure mode this wave
1610
- keeps paying for. */}
1611
- <LinkedGrid
1612
- scope={sec.table}
1613
- embedded
1614
- embeddedRecordIds={sec.ids}
1615
- />
1616
- </Suspense>
1617
- </div>
1618
- )}
1619
- </section>
1620
- ))}
1621
- {/* ⭐⭐ W41-T44 (owner instruction 25, R12, contracts C4/C5/C7) β€” RELATIONAL.
1622
- It mounts BESIDE the link sections and wears their shape: a section, a
1623
- disclosure heading with a count, and nothing rendered until it is asked for.
1624
- DESIGN Β§4, new nav joins the existing rhythm rather than inventing a control
1625
- shape, so the choices are the same `.cg-radio-row` rows the toolbar's own
1626
- Relational popover uses (`Toolbar.tsx`) and not a second kind of picker. */}
1627
- <section className="cg-detail-section cg-detail-relsec">
1628
- <h3 className="cg-detail-sechead">
1629
- {relTargets.length === 0 ? (
1630
- <span>Related</span>
1631
- ) : (
1632
- <button
1633
- type="button"
1634
- className="cg-detail-sectoggle"
1635
- aria-expanded={relOpen}
1636
- onClick={() => setRelOpen((open) => !open)}
1637
- >
1638
- Related
1639
- </button>
1640
- )}
1641
- <span className="cg-detail-seccount">
1642
- {relTargets.length.toLocaleString()}{" "}
1643
- {relTargets.length === 1 ? "database" : "databases"}
1644
- </span>
1645
- </h3>
1646
- {relTargets.length === 0 ? (
1647
- /* ⚠ AN EMPTY OFFER IS A TRUTHFUL ANSWER, not a failure: R9 derives the offer
1648
- from this table's LINK FIELDS and this one has none yet. Said in a sentence,
1649
- never as a chooser with nothing in it. */
1650
- <p className="cg-detail-secempty">
1651
- No related database yet. Add a Link column on this table to pivot to one.
1652
- </p>
1653
- ) : !relOpen ? null : (
1654
- <div className="cg-rel-record">
1655
- <div className="cg-pop-title">Related database</div>
1656
- <label className="cg-radio-row">
1657
- <input
1658
- type="radio"
1659
- name="cg-rel-record-target"
1660
- checked={!relVia}
1661
- onChange={() => setRelVia(null)}
1662
- />
1663
- <span>Stay on this record</span>
1664
- </label>
1665
- {relTargets.map((t) => (
1666
- <label key={t.viaField} className="cg-radio-row">
1667
- <input
1668
- type="radio"
1669
- name="cg-rel-record-target"
1670
- checked={relVia === t.viaField}
1671
- onChange={() => setRelVia(t.viaField)}
1672
- />
1673
- <span>{t.label}</span>
1674
- </label>
1675
- ))}
1676
- {/* R10 β€” the window belongs to the PIVOT, not to the target, so it exists
1677
- only once a target is chosen. A window with no relation to apply it to
1678
- is a control that cannot mean anything. */}
1679
- {relTarget && (
1680
- <>
1681
- <div className="cg-pop-title cg-rel-window-title">Time window</div>
1682
- {PIVOT_WINDOWS.map((w) => (
1683
- <label key={w} className="cg-radio-row">
1684
- <input
1685
- type="radio"
1686
- name="cg-rel-record-window"
1687
- checked={relWindow === w}
1688
- onChange={() => setRelWindow(w)}
1689
- />
1690
- <span>{PIVOT_WINDOW_LABELS[w]}</span>
1691
- </label>
1692
- ))}
1693
- </>
1694
- )}
1695
-
1696
- {relTarget && !relFilter && (
1697
- /* β›” CONTRACT C4 β€” NO BRIDGE ID, NO REQUEST. Refused rather than sent
1698
- unfiltered: a pivot with no leaf naming this record would return the
1699
- whole table's related rows and this panel would present them under one
1700
- record's name, which is a wrong answer rather than a missing one. Two
1701
- causes land here (the table has no Odoo ID column, or this record's is
1702
- blank) and the sentence covers both without claiming either. */
1703
- <p className="cg-rel-note" role="status">
1704
- This record carries no Odoo ID, so there is nothing to match its related
1705
- records on.
1706
- </p>
1707
- )}
1708
-
1709
- {relPivot.status === "loading" && (
1710
- /* wave17 GRID item 3 / owner R6: one small bare rotating icon, NO WORDS.
1711
- `aria-label` is not a word on screen and stays, because `.lp-spin` is an
1712
- empty span and the wait would otherwise be announced as nothing at all
1713
- (C-SPIN). No `--lg`: the mark sits inside a section, not alone on a
1714
- surface. */
1715
- <p className="cg-rel-note">
1716
- <span className="lp-spin" role="status" aria-label="Loading" />
1717
- </p>
1718
- )}
1719
-
1720
- {relRefusal && (
1721
- /* β›” C10's REFUSAL, SAID OUT LOUD, and `subject` is ON SCREEN because it
1722
- names WHICH database the wall stands in front of, which is the one thing
1723
- the reader can go and ask for. The `reason` is the server's word: only
1724
- it knows which wall it hit, and a sentence authored here would be this
1725
- panel guessing. An empty result in this slot would read as "no related
1726
- records", which is a wrong answer where "you may not see this" is the
1727
- true one. */
1728
- <p className="cg-rel-note" role="alert">
1729
- {relRefusal.subject
1730
- ? `${relRefusal.subject}: ${relRefusal.reason}`
1731
- : relRefusal.reason}
1732
- </p>
1733
- )}
1734
-
1735
- {relPivot.status === "absent" && (
1736
- /* β›”β›” NOTHING, PLUS ONE LINE. C10's endpoint is W41-T20 and it is not on
1737
- this branch. An absent answer means "not built yet", never "false", and
1738
- never an empty table. Same sentence as the grid's, deliberately: two
1739
- spellings of one state is two states to the reader. */
1740
- <p className="cg-rel-note" role="status">
1741
- The related view is not available yet, so there is nothing to show.
1742
- </p>
1743
- )}
1744
-
1745
- {relColumnless && (
1746
- <p className="cg-rel-note" role="status">
1747
- The related view answered with no columns, so there is nothing to lay out
1748
- yet.
1749
- </p>
1750
- )}
1751
-
1752
- {relServed && relAnswer && (
1753
- <div
1754
- className="cg-rel-head"
1755
- title={relAnswer.path.length ? relAnswer.path.join(" > ") : undefined}
1756
- >
1757
- <span className="cg-rel-path">
1758
- {`This record to ${relTarget?.label ?? ""}`}
1759
- </span>
1760
- <span className="cg-rel-counts">
1761
- {`${relAnswer.targetCount.toLocaleString()} ` +
1762
- `${relTarget?.label ?? "records"}`}
1763
- </span>
1764
- <span className="cg-rel-window">{PIVOT_WINDOW_LABELS[relWindow]}</span>
1765
- </div>
1766
- )}
1767
-
1768
- {relServed && relAnswer && relAnswer.rows.length === 0 && (
1769
- /* ⭐ THE ONLY STATE ENTITLED TO SAY THIS. The endpoint answered, it was
1770
- allowed to answer, and the answer is none. */
1771
- <p className="cg-rel-note" role="status">
1772
- No related records for this record in this time window.
1773
- </p>
1774
- )}
1775
-
1776
- {relServed && relAnswer && relAnswer.rows.length > 0 && (
1777
- <div className="cg-rel-rows">
1778
- <table className="cg-rel-table">
1779
- <thead>
1780
- <tr>
1781
- {relColumns.map((f) => (
1782
- <th key={f.key} scope="col">
1783
- {f.label}
1784
- </th>
1785
- ))}
1786
- </tr>
1787
- </thead>
1788
- <tbody>
1789
- {/* β›” STANDING RULE 1 β€” every row the server sent is painted. No
1790
- slice, no window, no client cap on connected-source data. */}
1791
- {relAnswer.rows.map((row, i) => (
1792
- <tr key={typeof row.pid === "number" ? row.pid : i}>
1793
- {relColumns.map((f) => {
1794
- const cell = row[f.key];
1795
- /* A BLANK IS A BLANK: null and undefined print nothing rather
1796
- than the words "null" or a 0 that then reads as a figure. */
1797
- return (
1798
- <td key={f.key}>
1799
- {cell === null || cell === undefined ? "" : String(cell)}
1800
- </td>
1801
- );
1802
- })}
1803
- </tr>
1804
- ))}
1805
- </tbody>
1806
- </table>
1807
- </div>
1808
- )}
1809
-
1810
- {relShort && relAnswer && (
1811
- <p className="cg-rel-note">
1812
- {`Showing ${relAnswer.rows.length.toLocaleString()} of ` +
1813
- `${relAnswer.targetCount.toLocaleString()}. The server sent fewer ` +
1814
- `records than it counted and did not say why. The pivot endpoint ` +
1815
- `should report the cause of that limit and how to lift it.`}
1816
- </p>
1817
- )}
1818
- </div>
1819
- )}
1820
- </section>
1821
- {/* The time series STAYS, as ONE section (R5's own wording). `locked` says the pid
1822
- set is the PREMISE, not a control: you are reading one customer, so the filter
1823
- surface is the record itself (the owner's words). The panel keeps its own
1824
- bucket/span/field controls live against local state. */}
1825
- <section className="cg-detail-section">
1826
- <TimeSeriesPanel
1827
- scope={scope}
1828
- pids={insightPids}
1829
- fields={fields}
1830
- /* wave17 item 5 / R9 β€” the population `insightPids` names, which here is one
1831
- record. sum-vs-avg is then moot: both reduce to this record's own value. */
1832
- rows={insightRows}
1833
- display={tsDisplay}
1834
- onDisplay={(next) => setTsDisplay((d) => ({ ...d, ...next }))}
1835
- locked
1836
- />
1837
- </section>
1838
  </div>
1839
  ) : (
1840
  <>
@@ -1848,8 +1793,12 @@ export default function RecordDetail({
1848
 
1849
  {/* Wave-8 I12c (C5) β€” Documents. Rendered only when the host actually
1850
  serves them: a section with a dead upload control on a deployment
1851
- that has no document storage would be a promise the app cannot keep. */}
1852
- {onDocAdd && onDocFetch && onDocDelete && (
 
 
 
 
1853
  <Documents
1854
  pid={Number(record.pid)}
1855
  docs={docs ?? []}
@@ -1859,6 +1808,33 @@ export default function RecordDetail({
1859
  onDelete={onDocDelete}
1860
  />
1861
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1862
  </>
1863
  )}
1864
  </div>
@@ -1871,7 +1847,10 @@ export default function RecordDetail({
1871
  a key that only changed on the number would REUSE this component across a surface
1872
  switch, painting one record's comments under another's name until the fetch
1873
  returned. */}
1874
- {showComments && scope != null && (
 
 
 
1875
  <RecordComments
1876
  key={`${scope}:${Number(record.pid)}`}
1877
  scope={scope}
 
1
+ import { lazy, Suspense, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef,
2
+ useState } from "react";
3
  import type { ReactNode, TextareaHTMLAttributes } from "react";
4
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
5
 
6
  /**
7
+ * ⭐⭐ W51-T06 (R5, contract C6) β€” THE GRID A RELATED TAB MOUNTS.
8
+ *
9
+ * β›” IT IS NOT `LinkedGrid` AND IT IS NOT THE SAME MOUNT. Wave 27's `LinkedGrid` passed
10
+ * `embedded` + `embeddedRecordIds`: the whole target table fetched and filtered to an id list in
11
+ * the browser, with its view rail suppressed. R5 asks for the opposite of both halves β€” the
12
+ * OTHER DATABASE'S OWN SAVED VIEWS, rail included, over rows the SERVER already narrowed. So the
13
+ * identifier is gone with the props it carried, and what survives is the lazy mechanism.
14
  *
15
  * β›” LAZY BECAUSE THE IMPORT IS A CYCLE, not because it is big. `CustomerGrid` mounts
16
  * `RecordDetail`; a static import back the other way is `A -> B -> A`, which bundlers resolve by
 
18
  * module happens to evaluate first, i.e. the kind that survives every local test and lands in
19
  * production. `React.lazy` defers the resolution to first RENDER, by which point both modules
20
  * exist. It also composes with item 34's route-level splitting instead of fighting it: a reader
21
+ * who never opens a related tab never downloads a second copy of anything.
22
  */
23
+ const RelatedGrid = lazy(() => import("./CustomerGrid"));
24
  import {
25
  automationDetail,
26
  automationState,
 
42
  import JsonViewer, { CodeViewer } from "./JsonViewer";
43
  import { StarRow, StarIcon } from "./Stars";
44
  import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditField, ratingMax } from "./types";
45
+ /* ⭐⭐ W51-T06 (R2/R5, C6) β€” THE RELATED VOCABULARY IS IMPORTED, NEVER RESTATED, which is the
46
+ same discipline the retired pivot vocabulary was held to and for the same reason: `types.ts`
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, DisplaySpec, 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.
 
340
  );
341
  }
342
 
343
+ /* ════════════════════════════════════════════════════════════════════════════════════════
344
+ ⭐⭐ W51-T06 (R2/R5, contract C6) β€” THE RECORD-LEVEL PIVOT AND ITS BRIDGE CONSTANT ARE GONE,
345
+ AND WHAT REPLACED THEM IS SMALLER RATHER THAN LARGER.
 
 
 
346
 
347
+ Wave 41 asked this panel to work out for itself which column of the record was an Odoo id,
348
+ build a one-leaf filter out of it, and post that to a pivot endpoint. Every one of those
349
+ three steps was the CLIENT deciding what is related to what, and the constant naming the two
350
+ bridge columns was the only place in the product where that answer was written down.
 
 
 
351
 
352
+ R2 moves the whole decision server-side: `GET /api/v1/grid/{table}/related` answers with the
353
+ forward links, the reverse links and the Odoo bridges this account may follow, and the read
354
+ takes `{table, record, via}` and compiles the pin into SQL. So the panel names an EDGE and
355
+ renders what comes back. There is no join here, no id to guess and no column to spell.
356
+ ⚠ `PIVOT_PATH`, `buildPivotRequest` and `pivotResponse` are NOT orphaned by this and stay in
357
+ `types.ts`: `CustomerGrid` still calls all three for the grid's own pivot region, which is a
358
+ different surface and is not this ticket's subject.
359
+ ════════════════════════════════════════════════════════════════════════════════════════ */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
 
361
  /** The record drawer's equivalent of the grid picker's `Add option` row. */
362
  function ChoiceCreateInput({
 
400
  }
401
 
402
  /**
403
+ * ⭐⭐ W51-T06 (R2/R5, C6) β€” THE FOUR STATES A **RELATED TAB** CAN BE IN, and they are the
404
+ * shape of the record view now that the record-level pivot and its endpoint are gone.
 
 
405
  *
406
+ * β›” `refused` IS NOT AN EMPTY RESULT AND NOT AN ERROR SCREEN. It is a DECLARED edge whose
407
+ * pinned read cannot be served yet, carrying the SERVER's own sentence: `ut_odoo_invoices` is
408
+ * materialised rather than read through, so its door takes no predicate, and an ordinary user
409
+ * table's door (`routes_tables.table_rows`) takes none either. R6's second sentence makes that
410
+ * a REPORTED limit with a cause and a recommendation, never a tab that quietly shows nothing
411
+ * and never a tab that quietly shows EVERYTHING.
412
+ * ⚠ `ready` is the only state that mounts a grid. Collapsing `refused` into it would paint the
413
+ * whole target database under a chip that names one record.
414
  */
415
+ type RelatedTabState =
416
+ | { status: "probing" }
417
+ | { status: "ready" }
418
+ | { status: "refused"; reason: string };
419
+
420
+ /**
421
+ * ⭐ W51-T06 CLAUSE 9 β€” ONE HOP of the record view's navigation, carrying everything needed to
422
+ * render it. See the shadow note inside the component for why the row and the field contract
423
+ * travel with the pid instead of being fetched here.
424
+ */
425
+ interface RecordFrame {
426
+ table: string;
427
+ pid: number;
428
+ label: string;
429
+ record: Row;
430
+ fields: Field[];
431
+ }
432
+
433
+ /**
434
+ * ⭐⭐ CLAUSE 10's STORE, AND IT IS `localStorage` BECAUSE R5 SAYS **"nothing new is stored"**.
435
+ *
436
+ * β›” THE VIEW ITSELF IS NOT STORED HERE, ONLY WHICH ONE WAS LAST OPEN. The views are the target
437
+ * database's own saved views, written through its own door; this remembers a reading position,
438
+ * per person, per browser, and no server record learns it.
439
+ * ⚠ Every access is wrapped: a private window, a full quota or a disabled store all throw from
440
+ * `localStorage` itself, and a record drawer that cannot open because a preference could not be
441
+ * read is a much worse defect than a preference that does not persist.
442
+ */
443
+ /* ⚠ IT SHARES THE `aios-grid:` NAMESPACE WITH THE WORKSPACE BUCKETS AND CANNOT COLLIDE WITH
444
+ ONE, checked rather than assumed: `CustomerGrid::readLocal` keys on `aios-grid:${storageKey}`
445
+ and a real storage key is `<key>_table_workspace`-shaped (or `local:<scope>`), neither of
446
+ which can spell `record-tab-views`. One prefix keeps the app's own keys findable in a browser
447
+ inspector; a second prefix would hide this one from whoever goes looking. */
448
+ const TAB_VIEWS_KEY = "aios-grid:record-tab-views";
449
+
450
+ function readTabViews(): Record<string, string> {
451
+ try {
452
+ const raw = localStorage.getItem(TAB_VIEWS_KEY);
453
+ if (!raw) return {};
454
+ const parsed = JSON.parse(raw) as unknown;
455
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
456
+ const out: Record<string, string> = {};
457
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>))
458
+ if (typeof value === "string" && value) out[key] = value;
459
+ return out;
460
+ } catch {
461
+ return {};
462
+ }
463
+ }
464
+
465
+ function writeTabViews(value: Record<string, string>): void {
466
+ try {
467
+ localStorage.setItem(TAB_VIEWS_KEY, JSON.stringify(value));
468
+ } catch {
469
+ /* a preference that cannot be written is a preference that does not persist, and nothing
470
+ more; the tab still opens on the database's own resolution. */
471
+ }
472
+ }
473
+
474
+ /**
475
+ * The renderer SCOPE a target table is drawn under.
476
+ *
477
+ * β›” IT READS THE TOPIC CONSTANTS RATHER THAN RESTATING THEIR STRINGS, and it does NOT import
478
+ * `CustomerGrid::scopeForLinkTable` even though that is the same mapping: a static import from
479
+ * this module into `CustomerGrid` is the `A -> B -> A` cycle the lazy mount at the top of this
480
+ * file exists to avoid, and it would leave one side `undefined` at module-evaluation time. The
481
+ * two registry modules are the only keys whose scope is not their own name, and the constants
482
+ * that say so are the same ones `topicForScope` answers from, so there is no second spelling.
483
+ */
484
+ /**
485
+ * ⭐ THE ONE STATE WITH NO SERVER SENTENCE, AND IT IS DECLARED RATHER THAN IMPROVISED.
486
+ *
487
+ * `relations.py` authors a sentence for every refusal it can see: an unknown relation, an
488
+ * unreadable source value, a declared-but-unserved target. It cannot author one for "the
489
+ * read-through roster does not name this table on this deployment", because that is a fact about
490
+ * the CLIENT's read path rather than about the relation. So this is the fourth sentence, it
491
+ * exists for exactly one state, and it says the same three things the server's own do: what was
492
+ * asked, why it cannot be answered, and what to do instead.
493
+ * β›” NO EM DASH AND NO EN DASH: this reaches a screen (standing rule 2).
494
+ */
495
+ function unpinnableNote(target: string): string {
496
+ return `'${target}' is not read through the live mirror on this deployment, so its rows door `
497
+ + `takes no relation pin and these records cannot be narrowed to this one. Open that `
498
+ + `database on its own and filter it there, or ask for its stored read to accept a pin`;
499
+ }
500
+
501
+ function relatedScope(target: string): SurfaceScope {
502
+ if (target === CUSTOMER_TOPIC.key) return CUSTOMER_TOPIC.scope as SurfaceScope;
503
+ if (target === PRODUCT_TOPIC.key) return PRODUCT_TOPIC.scope as SurfaceScope;
504
+ return target as SurfaceScope;
505
+ }
506
 
507
  export default function RecordDetail({
508
+ /* ⭐⭐ W51-T06 CLAUSE 9 β€” THE HOST'S RECORD IS THE **BASE**, NOT NECESSARILY WHAT IS ON SCREEN.
509
+ Clicking a row in a related tab navigates this panel to that record, and a back arrow
510
+ returns. Renaming the two props and re-binding `fields` / `record` a dozen lines down is
511
+ what lets the ENTIRE body below stay unchanged: one place decides which record is being
512
+ rendered, rather than forty call sites each asking. */
513
+ fields: baseFields,
514
+ record: baseRecord,
515
  titleKey,
516
  positionLabel,
517
  canPrev,
 
539
  const panelRef = useRef<HTMLDivElement>(null);
540
  const titleId = useId();
541
  const tabsId = useId();
542
+ /**
543
+ * ⭐⭐ W51-T06 CLAUSE 9 β€” THE NAVIGATION STACK, and it is a STACK rather than one slot because
544
+ * a related tab of a pushed record is itself navigable: customer -> order -> order line is one
545
+ * back arrow per hop, in the order they were taken.
546
+ *
547
+ * β›” IT IS CLEARED WHEN THE HOST CHANGES RECORD. `onPrev`/`onNext` move the BASE record under
548
+ * this panel; a stack left standing across that move would leave the reader looking at an
549
+ * order that belongs to the previous customer, with a back arrow to a record nobody is on.
550
+ */
551
+ const [stack, setStack] = useState<RecordFrame[]>([]);
552
+ const frame = stack.length > 0 ? stack[stack.length - 1] : null;
553
+ /**
554
+ * β›”β›” THE SHADOW IS THE WHOLE MECHANISM, AND IT IS DELIBERATE RATHER THAN CLEVER. Every one of
555
+ * the ~40 references below (`renderRow`, the ordering, the editors, the viewers) reads `fields`
556
+ * and `record`; re-pointing them ONCE here is a four-line change, where threading a second pair
557
+ * through each of them would be forty places to get one of them wrong.
558
+ * ⚠ A PUSHED FRAME CARRIES ITS OWN FIELD CONTRACT, handed over by the grid that was already
559
+ * holding it (`CustomerGrid::openRecord`). This panel cannot resolve a row of another database
560
+ * on its own: that door takes no predicate, and a filter leaf naming `pid` is dropped on the
561
+ * way in, which is a filter that matches everything.
562
+ */
563
+ const fields = frame ? frame.fields : baseFields;
564
+ const record = frame ? frame.record : baseRecord;
565
+ useEffect(() => {
566
+ setStack((prev) => (prev.length ? [] : prev));
567
+ }, [baseRecord.pid, scope]);
568
+ /**
569
+ * ⭐ CLAUSE 9's FORWARD HALF. The row, the fields and the table all arrive from the grid that
570
+ * already had them; only the LABEL is derived here, and only from what came with the row.
571
+ * ⚠ `title` on a frame is the frame's own label: `titleKey` belongs to the base table and
572
+ * reading it off a foreign row answers "Untitled" for every one of them.
573
+ */
574
+ const pushFrame = useCallback(
575
+ (pid: number, table: string, row?: Row, rowFields?: Field[]) => {
576
+ if (!row || !rowFields || rowFields.length === 0) return;
577
+ const first = rowFields[0];
578
+ const named = first ? String(row[first.key] ?? "") : "";
579
+ setStack((prev) => [...prev, {
580
+ table,
581
+ pid,
582
+ label: named || `Record ${pid}`,
583
+ record: row,
584
+ fields: rowFields,
585
+ }]);
586
+ },
587
+ []
588
+ );
589
+ const popFrame = useCallback(() => setStack((prev) => prev.slice(0, -1)), []);
590
+ const title = frame ? frame.label : String(record[titleKey] ?? "Untitled");
591
  // Wave 19 (item 12): `scope` joins the predicate β€” the comments rail addresses a server
592
  // endpoint per topic now, so a host that names no surface gets no rail rather than a rail
593
  // pointed at a guess. In practice CustomerGrid always names one; this is the fail-closed edge.
 
663
 
664
  // `defaultOrder` is the whole vocabulary, so this is a PERMUTATION of it and nothing else β€”
665
  // a saved layout can reorder the panel, never change what is in it. See recordLayout.ts.
666
+ /* ⚠ W51-T06 β€” THE SAVED ORDER BELONGS TO THE BASE TABLE. A pushed frame's fields are
667
+ another database's, so its stored order names none of them; `resolveFieldOrder` would
668
+ prune every key and answer the default anyway, and saying so here is cheaper than
669
+ leaving a reader to work out why a drag on a frame does nothing durable. */
670
+ const orderedKeys = resolveFieldOrder(
671
+ frame ? undefined : (pendingOrder ?? recordLayout), defaultOrder);
672
 
673
  // The key being dragged, twice over, written only in `onDragStart`/`onDragEnd` and always
674
  // together. The REF is what the handlers read: `dragover` must call preventDefault for a
 
702
 
703
  const commitOrder = (next: string[]) => {
704
  if (next === orderedKeys) return; // moveKey/nudgeKey return the input on a no-op
705
+ // β›” W51-T06 β€” A FRAME NEVER WRITES THE HOST'S LAYOUT. `recordLayout` is a per-user order
706
+ // for the BASE table; persisting a frame's arrangement into it would fill that preference
707
+ // with keys the base table does not have, which the resolver then prunes on every open.
708
+ if (frame) return;
709
  setPendingOrder(next);
710
  onRecordLayout?.(next);
711
  };
712
 
713
+ /* ═══════════════════════════════════════════════════════════════════════════════════════
714
+ ⭐⭐ W51-T06 Β· RULINGS R2 + R5 Β· CONTRACT C6 β€”
715
+ **FIELDS, THEN ONE TAB PER RELATED DATABASE, RESOLVED SERVER-SIDE.**
716
+
717
+ R2: *"A 'Linked database' tab exists for FORWARD link fields, REVERSE links … and the ODOO
718
+ BRIDGES … one tab per related table, resolved server-side."*
719
+ R5: *"A related tab is the OTHER DATABASE'S OWN SAVED VIEWS plus the pinned record: its view
720
+ rail included … **nothing new is stored.**"*
721
+
722
+ β›”β›” WHAT THIS REPLACES, AND WHY IT IS NOT THE SAME THING WEARING NEW WORDS. The Details tab
723
+ held two mechanisms, and both decided client-side what is related to what:
724
+ Β· `linkSections` mounted one EMBEDDED grid per link column, and an embedded grid fetches
725
+ its WHOLE table and filters to an id list in the browser. On a connected source that is
726
+ standing rule 1 in the direction that matters.
727
+ Β· the record pivot read a bridge column off the row, built a one-leaf filter out of it and
728
+ posted it to `grid/pivot` β€” the client naming a join.
729
+ Both are gone. The edges come from `GET /api/v1/grid/{table}/related`, already narrowed to
730
+ what this account may open, and the rows come from a read the SERVER pinned.
731
+
732
+ ⭐ NOTHING NEW IS STORED, and that clause is load-bearing three times over:
733
+ 1. the pinned record is a PROP the filter bar draws, never a filter-tree leaf, so no saved
734
+ view on the target database is poisoned with one record's pin (clause 8);
735
+ 2. the views a related tab offers are the target database's OWN saved views, written
736
+ through its own door under its own permissions (clause 7);
737
+ 3. the last-opened view per tab lives in `localStorage`, per person, per browser
738
+ (clause 10) β€” no server record learns which tab anybody last looked at.
739
+ ═══════════════════════════════════════════════════════════════════════════════════════ */
740
+
741
+ /** The DATABASE this record lives in, as the wire spells it (`customer_data`, `ut_*`). */
742
+ /* ⚠ IT FOLLOWS THE FRAME. A pushed record has its OWN related databases, so navigating
743
+ to an order and asking what an order is related to is the same code path as the first
744
+ hop, not a special case. */
745
+ const recordTable = frame ? frame.table : topicForScope(scope ?? "customer").key;
746
+
747
  /**
748
+ * R2's answer for this table. Empty until it arrives and empty on any failure, which is the
749
+ * honest degradation: a record whose relations cannot be listed still opens on its Fields tab.
750
+ */
751
+ const [entries, setEntries] = useState<RelatedEntry[]>([]);
752
+ /**
753
+ * ⭐ CLAUSE 2's OTHER HALF β€” `target key -> the DATABASE's own name`.
 
 
 
 
 
754
  *
755
+ * β›” THE `/related` ENTRY'S OWN `label` IS NOT IT, measured in `relations.py` rather than
756
+ * assumed: a FORWARD entry is labelled with the FIELD's label, which is exactly what clause 2
757
+ * wants as the SUBTITLE. The roster behind the link picker (`GET /tables?brief=1`) is the one
758
+ * producer of a database's display name in this product, so the name comes from there and the
759
+ * entry's own label is only the fallback.
760
  */
761
+ const [tableLabels, setTableLabels] = useState<Record<string, string>>({});
762
+ useEffect(() => {
763
+ // No scope, no tabs: the same fail-closed edge the comments rail takes. A pid means nothing
764
+ // without the table it belongs to, and guessing one asks a question nobody asked.
765
+ if (scope == null) {
766
+ setEntries([]);
767
+ return;
768
+ }
769
+ let live = true;
770
+ void fetchRelated(recordTable).then((got) => {
771
+ if (live) setEntries(got);
772
+ });
773
+ void fetchLinkTargets().then((targets) => {
774
+ if (!live) return;
775
+ const map: Record<string, string> = {};
776
+ for (const target of targets) map[target.key] = target.label;
777
+ setTableLabels(map);
778
+ });
779
+ return () => {
780
+ live = false;
781
+ };
782
+ }, [scope, recordTable]);
783
+
784
+ /** Clause 1 + clause 2 β€” the tab strip, in the server's order (forward, reverse, bridge). */
785
+ const tabs = useMemo(
786
+ () => relatedTabs(entries, (target) => tableLabels[target] ?? ""),
787
+ [entries, tableLabels]
788
+ );
789
+
790
  /**
791
+ * Which tab is open, by EDGE KEY. `"fields"` is the default and the fallback: a tab whose edge
792
+ * has disappeared (a link column deleted while the drawer was open) drops back to Fields
793
+ * rather than rendering a panel for an edge that is no longer offered.
794
+ */
795
+ const [tab, setTab] = useState("fields");
796
+ const activeTab = tabs.some((entry) => entry.entry.key === tab) ? tab : "fields";
797
+ const activeRelated = tabs.find((entry) => entry.entry.key === activeTab) ?? null;
798
+
799
+ /**
800
+ * ⭐⭐ CLAUSE 10 β€” THE LAST-OPENED VIEW **PER TAB**, PER PERSON, IN `localStorage`.
801
  *
802
+ * β›” PER TAB, NOT PER DATABASE. R2 gives two links between the same pair two tabs, so two tabs
803
+ * can point at one database; a memory keyed by the target alone would make each of them reopen
804
+ * on the other's view. The key is `<this table>:<edge key>`, and the EDGE KEY is what makes it
805
+ * unique: `relations._entry`'s own note says the entry key is the only member of `via` that
806
+ * identifies an edge on its own, precisely because `{direction, on}` does not.
807
+ * ⚠ `writeTabViews` runs inside the updater rather than beside it, so the write and the
808
+ * decision that there IS something to write are one expression. Under StrictMode the updater
809
+ * is invoked twice in development, which writes the same value twice; the write is idempotent
810
+ * and that is cheaper than a second effect whose only job is to mirror this state.
811
  */
812
+ const [tabViews, setTabViews] = useState<Record<string, string>>(readTabViews);
813
+ const tabViewKey = activeRelated ? `${recordTable}:${activeRelated.entry.key}` : "";
814
+ const rememberTabView = useCallback(
815
+ (viewId: string) => {
816
+ if (!tabViewKey) return;
817
+ setTabViews((prev) => {
818
+ // β›” THE SAME OBJECT ON A NO-OP. This callback fires from an effect in the mounted grid
819
+ // that depends on the view id; returning a fresh map for an unchanged value would
820
+ // re-render this panel, re-create the prop, and re-run that effect. React bails out on
821
+ // identity, so identity is what has to be preserved.
822
+ if (prev[tabViewKey] === viewId) return prev;
823
+ const next = { ...prev, [tabViewKey]: viewId };
824
+ writeTabViews(next);
825
+ return next;
826
+ });
827
+ },
828
+ [tabViewKey]
829
  );
830
 
 
 
 
 
 
 
 
831
  /**
832
+ * ⭐ CLAUSE 6 β€” THE PIN, and it is the whole of what makes these rows this record's.
833
+ *
834
+ * ⚠ MEMOISED ON A SERIALISED KEY. The grid takes this as an effect dependency; a fresh object
835
+ * per render would re-read on every keystroke in the drawer.
836
  */
837
+ const relatedPinKey = activeRelated
838
+ ? JSON.stringify({
839
+ table: recordTable,
840
+ record: Number(record.pid),
841
+ via: activeRelated.entry.via,
842
+ label: title,
843
+ })
844
+ : "";
845
+ const relatedPin = useMemo(
846
+ () => (relatedPinKey
847
+ ? (JSON.parse(relatedPinKey) as
848
+ { table: string; record: number; via: RelatedVia; label: string })
849
+ : null),
850
+ [relatedPinKey]
851
+ );
852
+
853
  /**
854
+ * ⭐⭐ CAN THIS EDGE BE SERVED, AND IF NOT, IN WHOSE WORDS? See `RelatedTabState`.
 
 
855
  *
856
+ * β›” TWO REASONS A DECLARED EDGE CANNOT BE PINNED TODAY, AND THE CLIENT CAN ONLY SEE ONE OF
857
+ * THEM ON ITS OWN. `served: false` is carried by the entry (`ut_odoo_invoices` is materialised
858
+ * and absent from `GRID_SOURCES`); the second is a target that is not read through at all,
859
+ * which `odoo-tables/status` answers and the entry does not. Both end in the same place: ask
860
+ * the pinned door for ONE row and print the sentence it refuses with.
861
+ * β›” THE SENTENCE IS THE SERVER'S, NOT THIS FILE'S. `relations.py` writes three of them, each
862
+ * naming a cause and a recommendation (R6's second sentence). A fourth spelled here would be a
863
+ * second opinion about one wire contract.
864
+ *
865
+ * β›”β›” THE **ROSTER** DECIDES WHETHER THE TAB MOUNTS. THE PROBE ONLY SUPPLIES WORDS, AND AN
866
+ * EARLIER DRAFT HAD THIS INVERTED WITH A WHOLE-DATABASE BUG IN IT.
867
+ * The mount has to be gated on THE SAME FACT THE READ CONSULTS, and the read consults
868
+ * `readThroughTables()` (`useCustomerData`: the pin reaches the server only for a `ut_*` scope
869
+ * that roster names). The probe asks a DIFFERENT question of a DIFFERENT door. Those two come
870
+ * apart on one flaky `odoo-tables/status` call, which fails SOFT to the empty set by design:
871
+ * the roster would answer "not read through", the genuinely-served orders door would answer
872
+ * 200 to the probe, the tab would mount `ready`, and `useCustomerData` would fall back to the
873
+ * whole-book read. The result is the ENTIRE orders table painted under a chip that reads
874
+ * "Linked to <one customer>" - a wrong answer wearing the right chrome, which is exactly the
875
+ * failure class this ticket exists to delete.
876
+ * β‡’ Not pinnable by the roster β‡’ REFUSED, whatever the probe says. The probe's only job is to
877
+ * fetch the server's sentence for the state, and `unpinnableNote` covers the one state that
878
+ * has no server sentence (the roster says no while the door answers 200).
879
  */
880
+ const [tabState, setTabState] = useState<RelatedTabState>({ status: "probing" });
 
 
 
 
 
 
 
 
 
 
881
  useEffect(() => {
882
+ if (!activeRelated || !relatedPin) {
883
+ setTabState({ status: "probing" });
884
  return;
885
  }
886
  let live = true;
887
+ setTabState({ status: "probing" });
888
+ const target = activeRelated.entry.target;
889
+ const pin = { table: relatedPin.table, record: relatedPin.record, via: relatedPin.via };
890
+ void (async () => {
891
+ const through = await readThroughTables();
892
+ if (!live) return;
893
+ // β›” THE ONE MOUNT CONDITION, and it is the read path's own. See the note above.
894
+ const pinnable = activeRelated.entry.served && through.has(target);
895
+ if (pinnable) {
896
+ setTabState({ status: "ready" });
897
+ return;
 
 
 
 
 
 
 
 
 
 
898
  }
899
+ const reason = await probeRelatedRead(target, pin);
900
+ if (!live) return;
901
+ setTabState({ status: "refused", reason: reason ?? unpinnableNote(target) });
902
  })();
903
  return () => {
904
  live = false;
905
  };
906
+ }, [activeRelated, relatedPin]);
907
+
908
+ /* ⭐ The time series KEEPS ITS SURFACE. R5 replaces the Details tab with the related tabs and
909
+ says nothing about retiring the record's own time series, and deleting a working panel
910
+ because its container was renamed would be this ticket removing behaviour nobody asked it
911
+ to remove. It moves to the foot of the Fields tab, which is where the record's own data
912
+ already lives. */
913
+ // `mode: "timeseries"` is the only required member of DisplaySpec and it is a truthful one
914
+ // here: this IS the time-series reading of the record. Every other key is absent, which the
915
+ // panel reads as "use my defaults".
916
+ const [tsDisplay, setTsDisplay] = useState<DisplaySpec>({ mode: "timeseries" });
917
+ // ⚠ Memoised, not `[Number(record.pid)]` inline: the panel's fetch effect depends on `pids`
918
+ // by identity, so a fresh array every render would re-fetch on every render β€” forever.
919
+ const insightPids = useMemo(() => [Number(record.pid)], [record.pid]);
920
+ // wave17 item 5 β€” the same population as `insightPids`, as VALUES, so a snapshot metric can
921
+ // read this record's own numbers. Memoised for the identical reason the pid list is.
922
+ const insightRows = useMemo(() => [record], [record]);
923
 
924
  /**
925
  * The six-dot handle. `draggable` sits HERE and not on the row: a draggable ancestor
 
982
  // ONE verdict, `types.mayEditField` β€” stratum + read-only-by-nature + permissions.
983
  // No second permission test anywhere below: a `formula` or `created_time` field must stay
984
  // read-only after item 9, and that is this function's answer, not a type check of mine.
985
+ /* β›”β›” W51-T06 CLAUSE 9 β€” A PUSHED FRAME IS READ-ONLY, AND IT HAS TO BE. Every write door
986
+ this panel owns (`onNotesChange`, `onNotesCommit`, `onChoiceAdded`) was handed over by the
987
+ host for the BASE record's table; firing one from a frame would PATCH a customer's column
988
+ with an order's value, on a door that answers 200. The field permission wall still runs
989
+ underneath this for the base record; nothing here loosens it. */
990
+ const mayEdit = !frame && mayEditField(field, viewer);
991
  // The ONE exception, and it is a vocabulary problem rather than a permission one: a `user`
992
  // field with no supplied people has nothing to offer, so it reads rather than pretends.
993
  const noVocabulary = field.type === "user" && !userOptions?.length;
 
1591
  >
1592
  <div className="cg-detail-header">
1593
  <div className="cg-detail-nav">
1594
+ {/* ⭐⭐ W51-T06 CLAUSE 9 β€” THE BACK ARROW, AND IT **REPLACES** PREV/NEXT RATHER THAN
1595
+ JOINING THEM. Prev/next walk the HOST grid's row order, which a pushed record is
1596
+ not in: offering them here would move the base record silently underneath the
1597
+ one on screen. One way in, one way out, and the way out is the way back.
1598
+ ⚠ The glyph is the same `β€Ή` the previous-record key uses, on purpose: this is
1599
+ the same gesture (go back one) reading the same direction, and inventing a second
1600
+ arrow shape for it would make two controls out of one idea. */}
1601
+ {frame ? (
1602
+ <button
1603
+ type="button"
1604
+ className="cg-detail-navbtn"
1605
+ onClick={popFrame}
1606
+ aria-label="Back to the record you came from"
1607
+ title="Back to the record you came from"
1608
+ >
1609
+ β€Ή
1610
+ </button>
1611
+ ) : (
1612
+ <>
1613
  <button
1614
  type="button"
1615
  className="cg-detail-navbtn"
 
1630
  >
1631
  β€Ί
1632
  </button>
1633
+ </>
1634
+ )}
1635
  {/* ⭐⭐ W35-T29 (R5, R6) β€” THE SAME RECORD STAR AS THE GRID'S, in the drawer.
1636
  β›” THE SAME STATE, NOT A SECOND ONE: `starred`/`onStar` come from the grid's own
1637
  `useRecordStars`, so starring here and starring in the row are one act on one list.
 
1645
  star floated alone in the middle of the bar, attached to nothing. Owner: *"the
1646
  'Star record' place is so out of placed there. Put it just beside the < > under
1647
  record detail."* Inside `.cg-detail-nav` it is one of three 28px keys, and the
1648
+ position caption reads after them.
1649
+ ⚠ W51-T06 β€” AND NOT ON A PUSHED FRAME. The star belongs to the record this
1650
+ drawer was opened for; painted over a frame it would star the customer while the
1651
+ reader is looking at one of their orders, which is a write nobody asked for on a
1652
+ record nobody is on. */}
1653
+ {!frame && onStar && (
1654
  <button
1655
  type="button"
1656
  className={"cg-detail-star" + (starred ? " is-on" : "")}
 
1662
  <RecordStarMark size={16} filled={starred} />
1663
  </button>
1664
  )}
1665
+ {/* ⚠ W51-T06 β€” the caption counts the HOST grid's rows, so a pushed frame has
1666
+ no position in it and says nothing rather than a number about somewhere else. */}
1667
+ <span className="cg-detail-pos">{frame ? "" : positionLabel}</span>
1668
  </div>
1669
  <button
1670
  type="button"
 
1686
  </div>
1687
  </div>
1688
 
1689
+ {/* ⭐⭐ W51-T06 CLAUSE 1 + CLAUSE 2 β€” FIELDS, THEN ONE TAB PER `/related` ENTRY.
1690
+ β›” ONE TAB PER EDGE, NOT PER TARGET, and R2 says so in as many words: two links
1691
+ between the same pair give two tabs. The strip is keyed by the EDGE key, which
1692
+ is the only thing that is unique when two of them point at one database.
1693
+ ⭐ THE LABEL IS THE TARGET DATABASE'S NAME; the field appears as a SUBTITLE and
1694
+ only where it is doing work (two edges, one target). A second line under a tab
1695
+ that has no sibling would be over-explaining (DESIGN section 4).
1696
+ ⚠ A `served: false` tab IS IN THIS STRIP. A declared relation that cannot be
1697
+ pinned yet is a REPORTED limit, and hiding it would make the limit invisible
1698
+ rather than absent. */}
1699
+ {tabs.length > 0 && (
1700
  <div className="cg-record-tabs" role="tablist" aria-label="Record view">
1701
+ <button
1702
+ type="button"
1703
+ role="tab"
1704
+ id={`${tabsId}-fields`}
1705
+ aria-selected={activeTab === "fields"}
1706
+ aria-controls={`${tabsId}-panel`}
1707
+ className={"cg-record-tab" + (activeTab === "fields" ? " is-on" : "")}
1708
+ onClick={() => setTab("fields")}
1709
+ >
1710
+ Fields
1711
+ </button>
1712
+ {tabs.map((entry) => (
1713
  <button
1714
+ key={entry.entry.key}
1715
  type="button"
1716
  role="tab"
1717
+ id={`${tabsId}-${entry.entry.key}`}
1718
+ aria-selected={activeTab === entry.entry.key}
1719
  aria-controls={`${tabsId}-panel`}
1720
+ className={"cg-record-tab cg-record-tab--rel"
1721
+ + (activeTab === entry.entry.key ? " is-on" : "")}
1722
+ onClick={() => setTab(entry.entry.key)}
1723
  >
1724
+ <span className="cg-record-tab-label">{entry.label}</span>
1725
+ {entry.subtitle && (
1726
+ <span className="cg-record-tab-sub">{entry.subtitle}</span>
1727
+ )}
1728
  </button>
1729
  ))}
1730
  </div>
 
1733
  <div
1734
  className="cg-detail-body"
1735
  id={`${tabsId}-panel`}
1736
+ role={tabs.length > 0 ? "tabpanel" : undefined}
1737
+ aria-labelledby={tabs.length > 0 ? `${tabsId}-${activeTab}` : undefined}
1738
  >
1739
+ {activeRelated && relatedPin && scope ? (
1740
+ <div className="cg-record-related">
1741
+ {/* ⭐⭐ CLAUSES 4 + 6 + 7 β€” THE TARGET DATABASE'S OWN GRID, over rows the SERVER
1742
+ narrowed to this record.
1743
+ β›” NO `embedded` AND NO `embeddedRecordIds`. That pair is the mode that hides
1744
+ the view rail and pulls the whole table into the browser to filter it there;
1745
+ R5 asks for the target's own saved views WITH the rail, over a pre-filtered
1746
+ read. Passing `related` and passing `embedded` are mutually exclusive by
1747
+ design, and this mount passes only the first.
1748
+ β›” THE GRID IS THE PANEL, not a card inside one. DESIGN section 4 allows ONE
1749
+ containment layer and the drawer is already it; a bordered box around a grid
1750
+ inside a drawer inside a modal is the card-in-card the section names. */}
1751
+ {tabState.status === "refused" ? (
1752
+ /* ⭐ R6's SECOND SENTENCE β€” the limit, its cause and what to do instead, in the
1753
+ SERVER's words. `role="status"` rather than `alert`: a declared relation that
1754
+ is not served yet is a reported boundary, not a failure. */
1755
+ <p className="cg-record-related-note" role="status">{tabState.reason}</p>
1756
+ ) : tabState.status === "probing" ? (
1757
+ /* Owner R6 β€” one small bare rotating mark, NO WORDS on screen. The `aria-label`
1758
+ is not a word on screen and stays, or the wait is announced as nothing at all
1759
+ (C-SPIN). */
1760
+ <p className="cg-record-related-note">
1761
+ <span className="lp-spin" role="status" aria-label="Loading" />
1762
+ </p>
1763
+ ) : (
1764
+ <Suspense
1765
+ fallback={
1766
+ <p className="cg-record-related-note">
1767
+ <span className="lp-spin" role="status" aria-label="Loading" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1768
  </p>
1769
+ }
1770
+ >
1771
+ <RelatedGrid
1772
+ scope={relatedScope(activeRelated.entry.target)}
1773
+ related={relatedPin}
1774
+ /* ⭐ CLAUSE 9 β€” a row click NAVIGATES THIS PANEL rather than stacking a
1775
+ second drawer on top of the one it is already inside. */
1776
+ onOpenRecord={pushFrame}
1777
+ /* ⭐ CLAUSE 10 β€” the view THIS TAB was last left on, and the way back. */
1778
+ relatedViewId={tabViews[tabViewKey]}
1779
+ onRelatedViewChange={rememberTabView}
1780
+ />
1781
+ </Suspense>
1782
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1783
  </div>
1784
  ) : (
1785
  <>
 
1793
 
1794
  {/* Wave-8 I12c (C5) β€” Documents. Rendered only when the host actually
1795
  serves them: a section with a dead upload control on a deployment
1796
+ that has no document storage would be a promise the app cannot keep.
1797
+ ⚠ W51-T06 β€” AND ONLY ON THE HOST'S OWN RECORD (`!frame`). The document handlers
1798
+ belong to the record this drawer was opened for; a pushed frame is a row of another
1799
+ database, and feeding its pid to them would file one record's upload against
1800
+ another's. */}
1801
+ {!frame && onDocAdd && onDocFetch && onDocDelete && (
1802
  <Documents
1803
  pid={Number(record.pid)}
1804
  docs={docs ?? []}
 
1808
  onDelete={onDocDelete}
1809
  />
1810
  )}
1811
+
1812
+ {/* ⭐⭐ W51-T06 β€” THE TIME SERIES KEEPS ITS SURFACE, at the foot of the Fields tab.
1813
+ β›” IT DID NOT GO WITH THE DETAILS TAB, and that is a decision rather than an
1814
+ oversight. The done-when deletes the TAB and its two client-side relation
1815
+ mechanisms; the time series is neither, it answers a question about THIS record's
1816
+ own numbers, and removing a working panel because its container was renamed would
1817
+ be this ticket taking away behaviour nobody asked it to take away.
1818
+ `locked` says the pid set is the PREMISE, not a control: you are reading one
1819
+ record, so the filter surface is the record itself (the owner's words).
1820
+ ⚠ NOT ON A PUSHED FRAME: the panel addresses an endpoint per SCOPE, and this
1821
+ drawer's scope is the host record's. A frame's pid sent under it would ask the
1822
+ customer endpoint about an order id and be answered, plausibly and wrongly. */}
1823
+ {!frame && scope != null && (
1824
+ <section className="cg-detail-section">
1825
+ <TimeSeriesPanel
1826
+ scope={scope}
1827
+ pids={insightPids}
1828
+ fields={fields}
1829
+ /* wave17 item 5 / R9 β€” the population `insightPids` names, which here is one
1830
+ record. sum-vs-avg is then moot: both reduce to this record's own value. */
1831
+ rows={insightRows}
1832
+ display={tsDisplay}
1833
+ onDisplay={(next) => setTsDisplay((d) => ({ ...d, ...next }))}
1834
+ locked
1835
+ />
1836
+ </section>
1837
+ )}
1838
  </>
1839
  )}
1840
  </div>
 
1847
  a key that only changed on the number would REUSE this component across a surface
1848
  switch, painting one record's comments under another's name until the fetch
1849
  returned. */}
1850
+ {/* ⚠ W51-T06 β€” NOT ON A PUSHED FRAME. The rail addresses an endpoint per
1851
+ scope+pid, and this drawer's scope is the HOST record's; a frame's pid under it
1852
+ would ask the customer endpoint about an order id and be answered. */}
1853
+ {!frame && showComments && scope != null && (
1854
  <RecordComments
1855
  key={`${scope}:${Number(record.pid)}`}
1856
  scope={scope}
web/src/customer-grid/RouteNav.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useEffect, useMemo, useRef, useState } from "react";
2
  import type { ReactElement } from "react";
3
  import { createPortal } from "react-dom";
4
  import { FolderMark } from "./icons";
@@ -12,6 +12,9 @@ import { normalizedRouteMapLinks, routePrintStops, routeReversePrintLabels } fro
12
  import type { NormalizedRouteMapLink } from "./routeLinks";
13
  import { submitRouteStopMove } from "./routeStopMove";
14
  import { boundedGoogleMapsUrl } from "./routeZoneTypes";
 
 
 
15
  import type {
16
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
17
  RouteAssignee, RouteDeliveryDto, RouteDeliveryRequest,
@@ -295,6 +298,20 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
295
  const [assignmentBusy, setAssignmentBusy] = useState(false);
296
  const [deleteConfirm, setDeleteConfirm] = useState(false);
297
  const [menu, setMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  const [renameId, setRenameId] = useState<string | null>(null);
299
  const [busy, setBusy] = useState(false);
300
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
@@ -944,6 +961,37 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
944
  const timerLabel = !dragging && settledLabel ? settledLabel : estimateLabel;
945
  const timerTone = !dragging && routeAnswer ? routeTimeTone(routeAnswer.current) : "estimated";
946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
947
  if (route) {
948
  // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order`
949
  // column was refused until an administrator migrated it, because unlocking an unmigrated one
@@ -980,7 +1028,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
980
  };
981
  return (
982
  <section className="cg-w44-route-nav" aria-label={`${route.name} route`}>
983
- <button type="button" className="cg-w44-route-back" onClick={() => onActiveRouteChange(null)}>
984
  Back to routes
985
  </button>
986
  {/* ── W46-T23 / INSTRUCTION 19: THE ONE PLACE A ROUTE IS RENAMED. ──────────────
@@ -1725,7 +1773,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1725
  Move into {target.name}
1726
  </button>)}
1727
  <button type="button" role="menuitem"
1728
- onClick={() => { setMenu(null); if (window.confirm(`Delete ${folder.name}? Its contents move to Routes.`)) finish(onFolderDelete(folder)); }}>Delete</button>
1729
  </AnchoredOverlay>
1730
  )}
1731
  </div>
@@ -1822,7 +1870,7 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1822
  {item.folderId && <button type="button" role="menuitem"
1823
  onClick={() => { setMenu(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
1824
  <button type="button" role="menuitem" disabled={!mayRouteAction(item, "delete")}
1825
- onClick={() => { setMenu(null); if (window.confirm(`Delete ${item.name}?`)) finish(onDelete(item)); }}>Delete</button>
1826
  </AnchoredOverlay>
1827
  )}
1828
  </div>
@@ -1903,6 +1951,34 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1903
  </div>
1904
  </div>}
1905
  {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1906
  </section>
1907
  );
1908
  }
 
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
  import type { ReactElement } from "react";
3
  import { createPortal } from "react-dom";
4
  import { FolderMark } from "./icons";
 
12
  import type { NormalizedRouteMapLink } from "./routeLinks";
13
  import { submitRouteStopMove } from "./routeStopMove";
14
  import { boundedGoogleMapsUrl } from "./routeZoneTypes";
15
+ // W51-T28 / R6 + C8 β€” the wave-51 base kit's ONE confirm dialog. Consumed, never re-implemented.
16
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
17
+ import { useEscapeClose } from "../ui/useEscapeClose";
18
  import type {
19
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
20
  RouteAssignee, RouteDeliveryDto, RouteDeliveryRequest,
 
298
  const [assignmentBusy, setAssignmentBusy] = useState(false);
299
  const [deleteConfirm, setDeleteConfirm] = useState(false);
300
  const [menu, setMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
301
+ /* ⭐⭐ W51-T28 / R6 β€” THE PENDING DELETE IS HOISTED TO THE COMPONENT, AND THAT IS THE WHOLE
302
+ TRICK. Both row menus close themselves (`setMenu(null)`) in the same handler that used to
303
+ raise `window.confirm`, and each menu is a conditional subtree
304
+ (`{menu && menu.id === item.id && (<AnchoredOverlay …>`). A dialog rendered inside that
305
+ subtree unmounts in the same commit and the person sees nothing at all. So the menu records
306
+ WHAT was asked for, and the dialog is mounted from the component's own returned JSX, outside
307
+ every menu conditional and outside `renderLevel`.
308
+ ⚠ ONE state serves both deletes because it is DISCRIMINATED. Two booleans would let a folder
309
+ delete and a route delete be pending at once, which is two dialogs on one screen. */
310
+ const [pendingDelete, setPendingDelete] = useState<
311
+ | { kind: "folder"; folder: MapRouteFolderDto }
312
+ | { kind: "route"; item: MapRouteDto }
313
+ | null
314
+ >(null);
315
  const [renameId, setRenameId] = useState<string | null>(null);
316
  const [busy, setBusy] = useState(false);
317
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
 
961
  const timerLabel = !dragging && settledLabel ? settledLabel : estimateLabel;
962
  const timerTone = !dragging && routeAnswer ? routeTimeTone(routeAnswer.current) : "estimated";
963
 
964
+ /* ═════════ W51-T28 / C8 β€” ESCAPE BACKS OUT OF AN OPEN SAVED ROUTE ══════════════════════
965
+ *
966
+ * ⭐ THE LADDER THIS COMPLETES, TOP DOWN: the kit dialog, then the open Route, then the map
967
+ * NAVIGATOR itself. The third rung is genuinely unreachable from this file and from MapView:
968
+ * `mapNavigator === "routes"` is `routePanelOpen && !zoneNavigatorOpen`, and `routePanelOpen`
969
+ * is `useState` in `CustomerGrid.tsx:3206` handed down as a read-only prop with no close
970
+ * callback and no event channel. An optional prop nobody passes, or a client-side emit with no
971
+ * listener, would each look exactly like a working close to a source scan while doing nothing
972
+ * at all, so neither is here and no gate leg claims the rung.
973
+ *
974
+ * β›” THE CLAIM IS DROPPED WHILE THE TITLE IS BEING RENAMED, and that is not fussiness. The
975
+ * arbiter's listener is CAPTURE PHASE on `document` and calls `stopPropagation`, so it runs
976
+ * ahead of React's own handlers and the rename input's `Escape`-cancels-the-draft would simply
977
+ * never fire again. Standing down while `titleDraft` is live leaves that behaviour exactly as
978
+ * it shipped, and one Escape still means one close everywhere else.
979
+ *
980
+ * β›” `!deleteConfirm` IS THE SAME RULE APPLIED TO THE OTHER LIVE OVERLAY IN THIS PANEL. The
981
+ * inline `role="alertdialog"` delete confirm below does not register with the arbiter and is
982
+ * deliberately left as it is, because `verify_w44_map_routes.py`'s `route-update-delete` leg
983
+ * pins that markup. Without this term Escape would resolve past it and close the whole Route
984
+ * out from under an open confirm, which is a behaviour this ticket would have INTRODUCED.
985
+ * ⚠ AND IT IS REACHED, THOUGH A GREP SAYS OTHERWISE. `grep deleteConfirm` finds no setter,
986
+ * because the setter is `setDeleteConfirm` and the capital D breaks the substring; `Delete
987
+ * Route` calls it, so that confirm really does open.
988
+ *
989
+ * ⚠ `cancelEditFirst` STAYS FALSE, matching the two Zone panels. One press, one close, which is
990
+ * what every other overlay in this app already does.
991
+ */
992
+ const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]);
993
+ useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes);
994
+
995
  if (route) {
996
  // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order`
997
  // column was refused until an administrator migrated it, because unlocking an unmigrated one
 
1028
  };
1029
  return (
1030
  <section className="cg-w44-route-nav" aria-label={`${route.name} route`}>
1031
+ <button type="button" className="cg-w44-route-back" onClick={backToRoutes}>
1032
  Back to routes
1033
  </button>
1034
  {/* ── W46-T23 / INSTRUCTION 19: THE ONE PLACE A ROUTE IS RENAMED. ──────────────
 
1773
  Move into {target.name}
1774
  </button>)}
1775
  <button type="button" role="menuitem"
1776
+ onClick={() => { setMenu(null); setPendingDelete({ kind: "folder", folder }); }}>Delete</button>
1777
  </AnchoredOverlay>
1778
  )}
1779
  </div>
 
1870
  {item.folderId && <button type="button" role="menuitem"
1871
  onClick={() => { setMenu(null); finish(onRouteMove(item, null)); }}>Move to Routes</button>}
1872
  <button type="button" role="menuitem" disabled={!mayRouteAction(item, "delete")}
1873
+ onClick={() => { setMenu(null); setPendingDelete({ kind: "route", item }); }}>Delete</button>
1874
  </AnchoredOverlay>
1875
  )}
1876
  </div>
 
1951
  </div>
1952
  </div>}
1953
  {error && <span className="cg-w44-route-empty" role="status">{error}</span>}
1954
+ {/* β›” RENDERED FROM THE COMPONENT ROOT, OUTSIDE `renderLevel` AND OUTSIDE EVERY MENU
1955
+ CONDITIONAL. See the note over `pendingDelete`: a dialog inside the menu subtree that
1956
+ set it would never paint. `ConfirmDialog` portals to <body> itself, so its position in
1957
+ this tree governs only its LIFETIME, and that is exactly what needed fixing. */}
1958
+ <ConfirmDialog
1959
+ open={pendingDelete !== null}
1960
+ title={pendingDelete ? `Delete ${pendingDelete.kind === "folder" ? pendingDelete.folder.name : pendingDelete.item.name}?` : ""}
1961
+ body={pendingDelete?.kind === "folder"
1962
+ ? "Its contents move to Routes."
1963
+ : "The Route and its saved stop order are removed; the customer records are untouched."}
1964
+ confirmLabel={pendingDelete?.kind === "folder" ? "Delete folder" : "Delete route"}
1965
+ tone="destructive"
1966
+ busy={busy}
1967
+ /* β›” `finish` IS INLINED HERE RATHER THAN CALLED, and not for style. `finish` swallows
1968
+ the promise, so there is no moment at which this dialog could learn the write had
1969
+ settled; clearing `pendingDelete` before the dispatch instead would close the dialog in
1970
+ the same batched render and `busy={busy}` would never paint on anything. The error still
1971
+ lands in the rail exactly where the native confirm's did. */
1972
+ onConfirm={() => {
1973
+ const target = pendingDelete;
1974
+ if (!target || busy) return;
1975
+ setBusy(true);
1976
+ void (target.kind === "folder" ? onFolderDelete(target.folder) : onDelete(target.item))
1977
+ .then(setError)
1978
+ .finally(() => { setBusy(false); setPendingDelete(null); });
1979
+ }}
1980
+ onCancel={() => setPendingDelete(null)}
1981
+ />
1982
  </section>
1983
  );
1984
  }
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -170,6 +170,57 @@ import {
170
  */
171
  const NEST_HOLD_MS = 6_000;
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  function ShareMark({ size = 13 }: { size?: number }) {
174
  return (
175
  <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden>
@@ -2188,6 +2239,15 @@ export default function ViewSidebar({
2188
  // keep in step, and the bug being fixed here is exactly what happens when two
2189
  // layers disagree about what absence means. For an unshared view the two are
2190
  // equivalent β€” `groupByFolder` maps the sentinel onto the same root bucket.
 
 
 
 
 
 
 
 
 
2191
  if (id) onItemMove?.(id, folderId ?? ROOT_FOLDER_ID);
2192
  },
2193
  }
@@ -2247,24 +2307,33 @@ export default function ViewSidebar({
2247
  */
2248
  pendingFileRef.current = null;
2249
  if (!arrived) return;
2250
- // The same verdict the drag site asks (`mayFileView` over `mayEditView`, W34-T22), so a view
2251
- // that could not be filed by dragging cannot be filed by being born here either.
2252
  /**
2253
  * ⭐⭐ W50-T11 / D-249 β€” AND IT SAYS SO. This return was silent, and a silent refusal on a
2254
  * door the user just used reads as the app losing the click: they pick "New view in folder",
2255
  * the view appears at the top level, and nothing anywhere explains why. DESIGN Β§4 asks a
2256
- * refusal to be a plain sentence naming its subject, so this one names the view and the
2257
- * reason rather than reporting that something failed.
2258
- * β›” THE PREDICATE IS UNCHANGED. `mayFileView` still returns true for a shared view whatever
2259
- * its role β€” that IS D-249's ruling (R4, W34-T22) and reversing it here would silently undo
2260
- * a shipped fix. What changes is only that the minority case which was already refused now
2261
- * has a voice.
 
 
 
 
 
 
 
 
 
 
 
2262
  */
2263
- if (!mayFileView(arrived, mayEditView(arrived, viewer))) {
2264
- signal(
2265
- TOAST_EVENT,
2266
- `"${viewDisplayName(arrived)}" is read only for you, so it stays at the top level.`
2267
- );
2268
  return;
2269
  }
2270
  onItemMove?.(arrived.id, pending.into);
@@ -3880,6 +3949,16 @@ export default function ViewSidebar({
3880
  {moveFor && moveView && (() => {
3881
  const currentId = folderIdOf ? folderIdOf(moveFor.viewId) : null;
3882
  const fileInto = (folderId: string | null) => {
 
 
 
 
 
 
 
 
 
 
3883
  onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID);
3884
  setMoveFor(null);
3885
  };
 
170
  */
171
  const NEST_HOLD_MS = 6_000;
172
 
173
+ /**
174
+ * ⭐⭐ WAVE 51 Β· T35 (ruling R18) β€” A VIEW SHARED TO YOU READ-ONLY IS NOT YOURS TO FILE.
175
+ *
176
+ * Owner, R18, 2026-09-03: *"a READ-ONLY shared view REFUSES a folder move with a sentence
177
+ * ('Shared to you by <owner>; only they can move it') and snaps back; D-249's exit condition is
178
+ * rewritten to this."*
179
+ *
180
+ * β›” THIS IS A DELIBERATE REVERSAL AND IT DOES NOT TOUCH `mayFileView`, which is the part that
181
+ * matters most to get right. D-249 (R4, W34-T22) made a read-only shared view DRAGGABLE, because
182
+ * a gesture that cannot begin has nothing to explain and the owner's report was silence. R18 does
183
+ * not take the gesture away, it gives the gesture a VOICE: the drag still starts, the row still
184
+ * offers "Move to", and the refusal arrives as a sentence at the moment of the drop. So
185
+ * `mayFileView` stays exactly what it was β€” `view.shared === true || mayEdit`, the AFFORDANCE
186
+ * test at the drag site and on the `...` menu β€” and this narrower predicate sits BESIDE it as the
187
+ * ACTION test. Reversing `mayFileView` itself would make the row inert again and put back the
188
+ * exact defect D-249 was raised to fix. [[two-gates-can-assert-opposite-things]]
189
+ *
190
+ * ⚠ `assigned` counts as read-only here without a special case, because `mayEditView`'s first
191
+ * line already refuses an assigned view; an assigned view that is also shared refuses too, which
192
+ * is the answer either ruling would give on its own.
193
+ */
194
+ export function isReadOnlyShare(view: SavedView, viewer?: Viewer): boolean {
195
+ return view.shared === true && !mayEditView(view, viewer);
196
+ }
197
+
198
+ /**
199
+ * ⭐⭐ W51-T35 (R18) β€” THE ONE SENTENCE A REFUSED FOLDER MOVE CARRIES, or `null` to proceed.
200
+ *
201
+ * β›” ONE FUNCTION FOR EVERY DOOR, and that is the point rather than tidiness. A view can be filed
202
+ * from four places β€” the rail's drag-and-drop, the "Move to" popover on the `...` menu, a view
203
+ * created inside a folder, and the grid's own `onItemMove` sink β€” and a refusal that is worded at
204
+ * each door separately arrives in four shapes that drift apart one wave at a time. The caller
205
+ * asks here, prints what it gets back, and emits nothing when it gets a sentence.
206
+ *
207
+ * β›” THE CALLER MUST REFUSE **BEFORE** IT EMITS, never by reverting after (D-636). A revert-after
208
+ * implementation looks identical on screen and still leaves an `item_move` on the wire, which the
209
+ * host may well store. The snap-back R18 asks for is then automatic and needs no mechanism: the
210
+ * row never moved, because nothing was sent.
211
+ *
212
+ * ⚠ `createdBy` IS OPTIONAL (`types.ts::SavedView`) and absent on host-seeded and pre-wave-9
213
+ * views, so the owner's name cannot be assumed. The fallback still refuses and still explains,
214
+ * rather than printing "Shared to you by undefined".
215
+ */
216
+ export function viewMoveRefusal(view: SavedView, viewer?: Viewer): string | null {
217
+ if (!isReadOnlyShare(view, viewer)) return null;
218
+ const owner = (view.createdBy ?? "").trim();
219
+ return owner
220
+ ? `Shared to you by ${owner}; only they can move it.`
221
+ : "This view was shared to you; only its owner can move it.";
222
+ }
223
+
224
  function ShareMark({ size = 13 }: { size?: number }) {
225
  return (
226
  <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden>
 
2239
  // keep in step, and the bug being fixed here is exactly what happens when two
2240
  // layers disagree about what absence means. For an unshared view the two are
2241
  // equivalent β€” `groupByFolder` maps the sentinel onto the same root bucket.
2242
+ // ⭐⭐ W51-T35 (R18) β€” THE REFUSAL IS HERE, BEFORE THE EMIT, AND IT SNAPS BACK BY
2243
+ // NOT MOVING. `dropHandlers` is a plain arrow rebuilt every render, so `views` and
2244
+ // `viewer` are the current ones and no dependency array can hold a stale grant.
2245
+ const dragged = id ? views.find((view) => view.id === id) : undefined;
2246
+ const refusal = dragged ? viewMoveRefusal(dragged, viewer) : null;
2247
+ if (refusal) {
2248
+ signal(TOAST_EVENT, refusal);
2249
+ return;
2250
+ }
2251
  if (id) onItemMove?.(id, folderId ?? ROOT_FOLDER_ID);
2252
  },
2253
  }
 
2307
  */
2308
  pendingFileRef.current = null;
2309
  if (!arrived) return;
2310
+ // The same verdict every other filing door asks, so a view that cannot be filed by dragging
2311
+ // cannot be filed by being born here either.
2312
  /**
2313
  * ⭐⭐ W50-T11 / D-249 β€” AND IT SAYS SO. This return was silent, and a silent refusal on a
2314
  * door the user just used reads as the app losing the click: they pick "New view in folder",
2315
  * the view appears at the top level, and nothing anywhere explains why. DESIGN Β§4 asks a
2316
+ * refusal to be a plain sentence naming its subject, so this one gives the reason rather than
2317
+ * reporting that something failed.
2318
+ *
2319
+ * β›”β›” W51-T35 (R18) β€” THE PREDICATE HERE IS NOW `viewMoveRefusal`, AND THE SENTENCE IS R18'S.
2320
+ * ⚠ THE PARAGRAPH THIS REPLACES SAID THE OPPOSITE and it was right at the time: *"the
2321
+ * predicate is unchanged; `mayFileView` still returns true for a shared view whatever its
2322
+ * role, that IS D-249's ruling (R4, W34-T22), and reversing it here would silently undo a
2323
+ * shipped fix."* R18 is the owner reversing the EXIT CONDITION on purpose β€” a read-only
2324
+ * shared view now refuses a folder move with a sentence β€” so the tombstone stays rather than
2325
+ * the claim. `mayFileView` itself is STILL unchanged and still gates the drag and the `...`
2326
+ * menu; what moved is which predicate an ACTION door asks. See `viewMoveRefusal` above.
2327
+ *
2328
+ * ⚠ `mayFileView` NO LONGER RUNS AT THIS DOOR, and that costs nothing observable: the arrival
2329
+ * is a view this user just created, so it is their own, unshared and unassigned, and
2330
+ * `mayFileView` was true on every path that can reach here. The one case it refused that
2331
+ * `viewMoveRefusal` does not is a view neither shared nor editable, which cannot be a view
2332
+ * that was born from this pane one commit ago.
2333
  */
2334
+ const refusal = viewMoveRefusal(arrived, viewer);
2335
+ if (refusal) {
2336
+ signal(TOAST_EVENT, refusal);
 
 
2337
  return;
2338
  }
2339
  onItemMove?.(arrived.id, pending.into);
 
3949
  {moveFor && moveView && (() => {
3950
  const currentId = folderIdOf ? folderIdOf(moveFor.viewId) : null;
3951
  const fileInto = (folderId: string | null) => {
3952
+ // ⭐⭐ W51-T35 (R18) β€” THE `...` MENU'S FOLDER SUBMENU SAYS THE SAME THING THE DRAG DOES.
3953
+ // The row is still OFFERED (`canFileMenuView` keeps asking `mayFileView`, the affordance
3954
+ // test), because a menu item that vanishes explains nothing; the sentence is what
3955
+ // explains. Refused BEFORE the emit, so there is no placement to take back.
3956
+ const refusal = viewMoveRefusal(moveView, viewer);
3957
+ if (refusal) {
3958
+ signal(TOAST_EVENT, refusal);
3959
+ setMoveFor(null);
3960
+ return;
3961
+ }
3962
  onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID);
3963
  setMoveFor(null);
3964
  };
web/src/customer-grid/aggregations.ts CHANGED
@@ -15,10 +15,12 @@ import { isNumericFieldType } from "./types";
15
  // note. Two copies is how a cell painted blank while the total under it counted 1,234.50.
16
  import { numericOrUndefined } from "./display";
17
  import type {
18
- AggName, Field, Row, SummaryAggName, SummaryChoice, SummaryMap,
19
  } from "./types";
20
  // ⭐⭐ W29-T74 β€” IMPORTED, NOT RE-DECLARED, which is what `iconShapes.ts` always claimed.
21
- import { FIELD_AGGS, FIELD_AGG_LABELS, SUMMARY_AGGS, SUMMARY_AGG_LABELS } from "./iconShapes";
 
 
22
 
23
  /**
24
  * ⭐⭐ WAVE-29 CONTRACT C7 β€” **THE CLIENT MIRROR of `platform/aios_grid.FIELD_AGGS`**, published
@@ -100,11 +102,33 @@ export function cleanPercent(p: number | undefined): number {
100
  return Math.max(0, Math.min(100, p));
101
  }
102
 
103
- /** ⭐ WAVE 50 Β· W50-T03 β€” the SUMMARY BAR's vocabulary and its words, re-exported under this
104
- * module's own name for the same reason `FIELD_AGGS` is: every runtime consumer imports
105
- * `./aggregations`, and a second declaration is a second thing to keep in step. */
106
- export { SUMMARY_AGGS };
107
- export const SUMMARY_LABELS: Record<SummaryAggName, string> = SUMMARY_AGG_LABELS;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  /**
110
  * ⭐⭐ W50-T03 / OWNER RULING R2 β€” **WHAT THIS COLUMN MAY BE SUMMARISED BY, AND IT IS THE TYPE
@@ -118,11 +142,17 @@ export const SUMMARY_LABELS: Record<SummaryAggName, string> = SUMMARY_AGG_LABELS
118
  *
119
  * `count` and `count_distinct` read ROWS and VALUES rather than numbers, so they are legal on
120
  * every type; the six numeric folds are offered only where a number can exist.
 
 
 
 
 
 
121
  */
122
- export function summaryOptions(field: Field): readonly SummaryAggName[] {
123
  return isNumericFieldType(field.type)
124
  ? SUMMARY_AGGS
125
- : SUMMARY_AGGS.filter((a) => a === "count" || a === "count_distinct");
126
  }
127
 
128
  /** Today's behaviour, unchanged, for every caller that has no view map to offer (the per-group
@@ -199,10 +229,53 @@ function foldNumeric(nums: number[], agg: SummaryAggName, p: number | undefined)
199
  return percentile([...nums].sort((a, b) => a - b), cleanPercent(p));
200
  }
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  export function computeAggs(
203
  rows: Row[],
204
  fields: Field[],
205
- summary?: SummaryMap
 
 
 
 
 
 
 
 
 
206
  ): Record<string, string> {
207
  const out: Record<string, string> = {};
208
  for (const f of fields) {
@@ -227,12 +300,20 @@ export function computeAggs(
227
  out[f.key] = seen.size.toLocaleString();
228
  continue;
229
  }
230
- if (!isNumericFieldType(f.type)) continue;
231
- const nums: number[] = [];
232
- for (const r of rows) {
233
- const n = numOf(r[f.key]);
234
- if (n !== undefined) nums.push(n);
 
 
 
 
 
 
235
  }
 
 
236
  if (!nums.length) continue; // blank, never zero
237
  const clean = Math.round(foldNumeric(nums, agg, choice.p) * 100) / 100; // drop float artifacts
238
  // ⭐ W41-T40 (instruction 16) β€” A SUMMARY WEARS ITS COLUMN'S UNIT. `display.cellText` paints
@@ -281,12 +362,18 @@ export function computeAggNumbers(
281
  out[f.key] = seen.size;
282
  continue;
283
  }
284
- if (!isNumericFieldType(f.type)) continue;
285
- const nums: number[] = [];
286
- for (const r of rows) {
287
- const n = numOf(r[f.key]);
288
- if (n !== undefined) nums.push(n);
 
 
 
 
289
  }
 
 
290
  if (!nums.length) continue; // blank, never zero
291
  out[f.key] = foldNumeric(nums, agg, choice.p);
292
  }
@@ -314,8 +401,21 @@ export function computeAggNumbers(
314
  */
315
  export const SHARE_AGGS: readonly SummaryAggName[] = ["sum", "count"];
316
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  export function sharesTheTotal(choice: SummaryChoice): boolean {
318
- return choice.agg !== "none" && SHARE_AGGS.includes(choice.agg);
 
319
  }
320
 
321
  /**
@@ -340,35 +440,25 @@ export function formatShare(
340
  }
341
 
342
  /**
343
- * ⭐⭐ W50-T04 / OWNER RULING R3 β€” **WHAT A GROUP HEADER PAINTS, PER COLUMN.**
 
 
 
 
 
344
  *
345
- * R3: *"every group header carries the same summary bar as the footer (every chosen aggregate,
346
- * count, % of total)."* So the string is the group's own aggregate followed by its share of the
347
- * VIEW's total for that column β€” `"$12,340 12.4%"` β€” and a column whose fold does not compose
348
- * (see `SHARE_AGGS`) carries the aggregate alone.
 
349
  *
350
- * ⚠ TWO SPACES, NOT A SEPARATOR GLYPH. A group header is a dense strip and the two quantities
351
- * are already visually distinct (one wears a unit, the other a `%`); a bullet or a slash between
352
- * them is chrome, and a dash of any width is forbidden outright in copy that reaches a screen.
 
 
353
  */
354
- export function groupHeaderAggs(
355
- fields: Field[],
356
- summary: SummaryMap,
357
- groupText: Record<string, string>,
358
- groupNums: Record<string, number>,
359
- grandNums: Record<string, number>
360
- ): Record<string, string> {
361
- const out: Record<string, string> = {};
362
- for (const f of fields) {
363
- const text = groupText[f.key];
364
- if (text === undefined) continue;
365
- const share = sharesTheTotal(resolveSummary(f, summary))
366
- ? formatShare(groupNums[f.key], grandNums[f.key])
367
- : undefined;
368
- out[f.key] = share === undefined ? text : `${text} ${share}`;
369
- }
370
- return out;
371
- }
372
 
373
  /** The formatting half of the fold, extracted so C1's SERVER numbers wear the same unit the
374
  * client's own fold does. Two formatters is how the same column reads "$1,204" on a small
@@ -387,13 +477,25 @@ function wearColumnUnit(field: Field, clean: number): string {
387
  * that a fold with nothing to measure returns nothing, because `0` is a measurement.
388
  * ⚠ The two counting aggregates are plain integers: a count of rows in a money column is not
389
  * money, and dressing it as "$412" is a number nobody can reconcile.
 
 
 
 
 
 
 
 
 
390
  */
391
  export function formatServerAgg(
392
  field: Field,
393
  choice: SummaryChoice,
394
- value: number | null | undefined
 
395
  ): string | undefined {
396
  if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
 
 
397
  if (choice.agg === "count" || choice.agg === "count_distinct")
398
  return Math.round(value).toLocaleString();
399
  return wearColumnUnit(field, Math.round(value * 100) / 100);
 
15
  // note. Two copies is how a cell painted blank while the total under it counted 1,234.50.
16
  import { numericOrUndefined } from "./display";
17
  import type {
18
+ AggName, Field, Row, SummaryAggName, SummaryChoice, SummaryMap, SummaryPickAgg,
19
  } from "./types";
20
  // ⭐⭐ W29-T74 β€” IMPORTED, NOT RE-DECLARED, which is what `iconShapes.ts` always claimed.
21
+ import {
22
+ FIELD_AGGS, FIELD_AGG_LABELS, SUMMARY_AGGS as WIRE_SUMMARY_AGGS, SUMMARY_AGG_LABELS,
23
+ } from "./iconShapes";
24
 
25
  /**
26
  * ⭐⭐ WAVE-29 CONTRACT C7 β€” **THE CLIENT MIRROR of `platform/aios_grid.FIELD_AGGS`**, published
 
102
  return Math.max(0, Math.min(100, p));
103
  }
104
 
105
+ /**
106
+ * ⭐⭐ WAVE 51 Β· W51-T02 (owner ruling R3) β€” **THE PICKER'S VOCABULARY IS THE WIRE'S PLUS
107
+ * `share`, AND IT IS DECLARED HERE RATHER THAN WHERE THE WIRE ONE LIVES.**
108
+ *
109
+ * β›” WHY THE DECLARATION MOVED (W50-T03 re-exported the icon array bare). C1's summary
110
+ * vocabulary is EIGHT names and it exists twice β€” `iconShapes.SUMMARY_AGGS` and
111
+ * `platform/aios_grid.SUMMARY_AGGS` β€” with `verify_grid_ux.py::summary_bar_shape` holding the
112
+ * two byte-for-byte so neither engine can widen the wire alone. R3's "% of total" is a PICKER
113
+ * choice, never a wire agg: its numerator and denominator are ordinary wire aggregates (a
114
+ * numeric column's `sum`, anything else's `count`) and the division is client-side. Adding it to
115
+ * either array would break that parity leg and would tell lane F's route to compile an
116
+ * aggregate that does not exist in SQL.
117
+ *
118
+ * ⚠ AND THE TWO FILES IT WOULD OTHERWISE HAVE TO TOUCH BELONG TO OTHER LANES (`iconShapes.ts` to
119
+ * lane C, `aios_grid.py` to lane B), so the wire array is IMPORTED under an alias and the
120
+ * picker's array is spread out of it. One list still, plus one name this module owns β€” the
121
+ * wire cannot drift, because nothing here writes to it.
122
+ */
123
+ export const SUMMARY_AGGS: readonly SummaryPickAgg[] = [...WIRE_SUMMARY_AGGS, "share"];
124
+
125
+ /** The picker's words. `share` reads "% of total" (sentence case, DESIGN.md Β§2) and the other
126
+ * eight come from the icon module's table unchanged, for the reason above: one table, extended
127
+ * where the extra name is declared rather than where the wire one is. */
128
+ export const SUMMARY_LABELS: Record<SummaryPickAgg, string> = {
129
+ ...SUMMARY_AGG_LABELS,
130
+ share: "% of total",
131
+ };
132
 
133
  /**
134
  * ⭐⭐ W50-T03 / OWNER RULING R2 β€” **WHAT THIS COLUMN MAY BE SUMMARISED BY, AND IT IS THE TYPE
 
142
  *
143
  * `count` and `count_distinct` read ROWS and VALUES rather than numbers, so they are legal on
144
  * every type; the six numeric folds are offered only where a number can exist.
145
+ *
146
+ * ⭐⭐ W51-T02 / R3 β€” **`share` IS LEGAL ON EVERY TYPE, AND THAT IS THE RULING'S SECOND HALF.**
147
+ * R3: *"the primary column: Count / % of total"*. A share of a text column is that group's ROW
148
+ * COUNT over the view's, which is a question every column can answer; on a numeric column it is
149
+ * that column's own SUM over the view's. So it joins the two counting aggregates in the
150
+ * non-numeric arm rather than being filtered out with the six folds.
151
  */
152
+ export function summaryOptions(field: Field): readonly SummaryPickAgg[] {
153
  return isNumericFieldType(field.type)
154
  ? SUMMARY_AGGS
155
+ : SUMMARY_AGGS.filter((a) => a === "count" || a === "count_distinct" || a === "share");
156
  }
157
 
158
  /** Today's behaviour, unchanged, for every caller that has no view map to offer (the per-group
 
229
  return percentile([...nums].sort((a, b) => a - b), cleanPercent(p));
230
  }
231
 
232
+ /** Every readable number in one column of `rows`. β›” ONE numeric reading (`numOf`), shared with
233
+ * the canvas renderer β€” see this module's head note; two readings is how a cell painted blank
234
+ * while the total under it counted 1,234.50. */
235
+ function numbersOf(rows: Row[], key: string): number[] {
236
+ const nums: number[] = [];
237
+ for (const r of rows) {
238
+ const n = numOf(r[key]);
239
+ if (n !== undefined) nums.push(n);
240
+ }
241
+ return nums;
242
+ }
243
+
244
+ /**
245
+ * ⭐⭐ W51-T02 / R3 β€” **WHAT A `share` DIVIDES, AND IT IS ONE FUNCTION SO A NUMERATOR AND A
246
+ * DENOMINATOR CANNOT BE MEASURED TWO DIFFERENT WAYS.**
247
+ *
248
+ * A numeric column's share is its own SUM over the view's sum. Every other column's β€” the
249
+ * primary key column above all, which is instruction 4's whole subject β€” is that bucket's ROW
250
+ * COUNT over the view's row count, because a column of text has no quantity to add up.
251
+ *
252
+ * β›” BLANK, NEVER ZERO, on the numeric arm: a set holding no readable number at all is `undefined`
253
+ * rather than `0`, exactly as `computeAggs` returns nothing there. A row COUNT of zero is a real
254
+ * measurement and stays `0` β€” `formatShare` then refuses the division only if the WHOLE is zero.
255
+ * β›” NOTHING IS ROUNDED HERE. Rounding a numerator and a denominator separately is how a column
256
+ * of shares stops adding to 100 (`computeAggNumbers`' own note).
257
+ */
258
+ function shareBase(rows: Row[], field: Field): number | undefined {
259
+ if (!isNumericFieldType(field.type)) return rows.length;
260
+ const nums = numbersOf(rows, field.key);
261
+ // ⚠ `foldNumeric`, not a second `reduce`: the sum a share divides and the sum the bar prints
262
+ // must be ONE arithmetic, which is the same argument W50-T04 extracted that function for.
263
+ return nums.length ? foldNumeric(nums, "sum", undefined) : undefined;
264
+ }
265
+
266
  export function computeAggs(
267
  rows: Row[],
268
  fields: Field[],
269
+ summary?: SummaryMap,
270
+ /**
271
+ * ⭐⭐ W51-T02 / R3 β€” the VIEW's totals, keyed exactly as `computeAggNumbers` returns them, and
272
+ * the ONLY thing a `share` may divide by. Absent means "this fold IS the view" β€” the bottom
273
+ * bar, which therefore reads 100.0% under "% of total", which is what the done-when says.
274
+ * β›” It is never the sum of the groups and never the painted list: R4 fixed the base at the
275
+ * MATCHED, UNFOLDED set and a base that followed the fold would change every share on screen
276
+ * as somebody tidied it.
277
+ */
278
+ totals?: Record<string, number>
279
  ): Record<string, string> {
280
  const out: Record<string, string> = {};
281
  for (const f of fields) {
 
300
  out[f.key] = seen.size.toLocaleString();
301
  continue;
302
  }
303
+ /* ⭐⭐ W51-T02 / R3 β€” "% OF TOTAL" IS A PERCENT WHATEVER THE COLUMN'S UNIT, WHICH IS WHY IT
304
+ RETURNS BEFORE `wearColumnUnit` EVER SEES IT. A share dressed in a money column's unit
305
+ prints "$12.4" where it means "12.4%" β€” a number that is true of nothing, and one no type
306
+ and no screenshot can catch. `formatShare` owns the arithmetic and the one decimal, and
307
+ refuses a zero or absent denominator rather than painting `0%`. */
308
+ if (agg === "share") {
309
+ const base = shareBase(rows, f);
310
+ const whole = totals?.[f.key];
311
+ const text = formatShare(base, whole === undefined ? base : whole);
312
+ if (text !== undefined) out[f.key] = text;
313
+ continue;
314
  }
315
+ if (!isNumericFieldType(f.type)) continue;
316
+ const nums = numbersOf(rows, f.key);
317
  if (!nums.length) continue; // blank, never zero
318
  const clean = Math.round(foldNumeric(nums, agg, choice.p) * 100) / 100; // drop float artifacts
319
  // ⭐ W41-T40 (instruction 16) β€” A SUMMARY WEARS ITS COLUMN'S UNIT. `display.cellText` paints
 
362
  out[f.key] = seen.size;
363
  continue;
364
  }
365
+ /* ⭐⭐ W51-T02 / R3 β€” a `share` UNDRESSED is its BASE, not its percentage, and that is what
366
+ makes this function the denominator source. `groupAnalytics` folds this over the whole
367
+ matched set and hands the result back in as `computeAggs`' `totals`, so the group's base
368
+ and the view's base are measured by one function over two scopes. Summary mode also sorts
369
+ on it, and ordering by the base is the same order as by the share under one denominator. */
370
+ if (agg === "share") {
371
+ const base = shareBase(rows, f);
372
+ if (base !== undefined) out[f.key] = base;
373
+ continue;
374
  }
375
+ if (!isNumericFieldType(f.type)) continue;
376
+ const nums = numbersOf(rows, f.key);
377
  if (!nums.length) continue; // blank, never zero
378
  out[f.key] = foldNumeric(nums, agg, choice.p);
379
  }
 
401
  */
402
  export const SHARE_AGGS: readonly SummaryAggName[] = ["sum", "count"];
403
 
404
+ /**
405
+ * β›”β›” W51-T02 β€” **THIS IS THE ROW-LEVEL `Show as` GATE, AND R3 EXPLICITLY KEEPS IT.** R3, in its
406
+ * own words: *"The row-level Show as (wave 50 R4) STAYS on the field."* Its one caller is
407
+ * `CustomerGrid.tsx::getCellContent`, which composes a CELL's value with its share of the view
408
+ * total through `ui/fmt.ts::withShare` under `field.showAs`.
409
+ *
410
+ * β›” IT IS NOT WHAT PAINTS A GROUP HEADER ANY MORE. W50-T04's `groupHeaderAggs` used this to
411
+ * append an automatic SECOND number to every composable column's header, which is exactly what
412
+ * instruction 1 called out; the header now paints one value, the bar's picker's choice, and
413
+ * "% of total" is one of the choices rather than an extra.
414
+ * ⚠ `share` can never be a member: it IS a share, and a share of a share is not a quantity.
415
+ */
416
  export function sharesTheTotal(choice: SummaryChoice): boolean {
417
+ if (choice.agg === "none" || choice.agg === "share") return false;
418
+ return SHARE_AGGS.includes(choice.agg);
419
  }
420
 
421
  /**
 
440
  }
441
 
442
  /**
443
+ * ⭐⭐ W51-T02 / OWNER RULING R3 β€” **`groupHeaderAggs` IS GONE, AND ITS ABSENCE IS THE TICKET.**
444
+ *
445
+ * W50-T04 declared a function here that composed `"$12,340 12.4%"` β€” the column's aggregate,
446
+ * then an AUTOMATIC share of the view total for every fold in `SHARE_AGGS`. Instruction 1, in
447
+ * the owner's words: *"Under the Group function with numerics, do not show BOTH common size %
448
+ * and the sum/average/median: the toggle for sum/average/median includes the common size."*
449
  *
450
+ * R3 replaced it: *"The bottom-bar picker OWNS group headers and the bar: one value, the
451
+ * picker's choice, with '% of total' as an option."* So a group header is now `computeAggs` over
452
+ * that group's bucket under the view's summary map, with the view's own totals handed in as the
453
+ * share denominator β€” the SAME function the bottom bar folds itself with, at a smaller scope.
454
+ * There is nothing left to compose, so there is no composer.
455
  *
456
+ * ⚠ WHAT THE HEADER STILL CARRIES BESIDE ITS COLUMNS is the group's ROW COUNT as a share of the
457
+ * view's, appended to the group LABEL (`CustomerGrid.tsx::groupAnalytics`' `share` map). That is
458
+ * a property of the grouping rather than of a column, it is not gated on `sharesTheTotal`, and
459
+ * `export.ts::summaryExportSheet` files it as the "% of total" column of the Summary-mode
460
+ * export. Deleting it would empty a shipped column to answer a ruling that speaks about columns.
461
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
 
463
  /** The formatting half of the fold, extracted so C1's SERVER numbers wear the same unit the
464
  * client's own fold does. Two formatters is how the same column reads "$1,204" on a small
 
477
  * that a fold with nothing to measure returns nothing, because `0` is a measurement.
478
  * ⚠ The two counting aggregates are plain integers: a count of rows in a money column is not
479
  * money, and dressing it as "$412" is a number nobody can reconcile.
480
+ *
481
+ * ⭐⭐ W51-T02 / R3 β€” **AND A `share` IS A PERCENT WHATEVER THE COLUMN'S UNIT, so it returns
482
+ * before `wearColumnUnit` too.** On a server-windowed table there is no page to fold: `value` is
483
+ * the server's aggregate for this group (a numeric column's `sum`, anything else's `count`,
484
+ * which is what `CustomerGrid.tsx::summaryRequest` asks for in a share column's name) and
485
+ * `whole` is C1's TOP-LEVEL overall answer for the same column. Both come from the aggregates
486
+ * endpoint, so the share describes the whole predicate rather than the loaded window.
487
+ * β›” NO SERVER ANSWER IS NO DENOMINATOR AND THEREFORE NO SHARE β€” `formatShare` refuses an absent
488
+ * or zero `whole` and this returns `undefined`, which the callers paint as blank. Never `0%`.
489
  */
490
  export function formatServerAgg(
491
  field: Field,
492
  choice: SummaryChoice,
493
+ value: number | null | undefined,
494
+ whole?: number | null | undefined
495
  ): string | undefined {
496
  if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
497
+ if (choice.agg === "share")
498
+ return formatShare(value, typeof whole === "number" ? whole : undefined);
499
  if (choice.agg === "count" || choice.agg === "count_distinct")
500
  return Math.round(value).toLocaleString();
501
  return wearColumnUnit(field, Math.round(value * 100) / 100);
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 } from "./types";
59
- import type { CustomersPayload, Field, FilterNode, GridLimit, GridWorkspace, HostEvent, Row,
60
- SortSpec, TopicConfig } from "./types";
61
  import type { TsPayload, TsRequest } from "./timeSeriesData";
62
 
63
  const JSON_HEADERS = { "Content-Type": "application/json" };
@@ -323,6 +323,17 @@ export interface RowWindowRequest {
323
  filterConj?: string;
324
  sorts?: SortSpec | null;
325
  search?: string;
 
 
 
 
 
 
 
 
 
 
 
326
  }
327
 
328
  /**
@@ -354,6 +365,13 @@ export function windowRowsPath(tableKey: string, req: RowWindowRequest): string
354
  if (req.sorts && req.sorts.length) q.set("sorts", JSON.stringify(req.sorts));
355
  const search = (req.search ?? "").trim();
356
  if (search) q.set("search", search);
 
 
 
 
 
 
 
357
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
358
  }
359
 
@@ -539,6 +557,17 @@ export interface AggregateRequest {
539
  search?: string;
540
  groupBy?: string;
541
  aggs: { colId: string; agg: string; p?: number }[];
 
 
 
 
 
 
 
 
 
 
 
542
  }
543
 
544
  /** C1's response, as this client reads it. `null` for a column means the server ANSWERED and
@@ -603,6 +632,9 @@ export async function fetchAggregates(
603
  filterConj: req.filterConj === "or" ? "or" : "and",
604
  search: (req.search ?? "").trim(),
605
  ...(req.groupBy ? { groupBy: req.groupBy } : {}),
 
 
 
606
  aggs: req.aggs,
607
  }),
608
  }
@@ -614,6 +646,70 @@ export async function fetchAggregates(
614
  return aggregatePayload(await readJson(res));
615
  }
616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
  /**
618
  * `GET /api/v1/workspace` β€” the saved views, custom fields, folders and cohorts
619
  * for the session user (S1's amendment, 2026-07-30). It exists because X2 pins
@@ -1584,7 +1680,30 @@ export async function fetchCalendarMetrics(
1584
  */
1585
  export const MAX_REPLAY = 24;
1586
 
1587
- let pending: HostEvent[] = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1588
  let inFlight = false;
1589
 
1590
  /**
@@ -1631,7 +1750,7 @@ export function _resetQueue(): void {
1631
  }
1632
 
1633
  export function _pendingIds(): string[] {
1634
- return pending.map((e) => e.id);
1635
  }
1636
 
1637
  /**
@@ -1652,15 +1771,22 @@ export function _pendingIds(): string[] {
1652
  async function drain(): Promise<void> {
1653
  if (inFlight || pending.length === 0) return;
1654
  inFlight = true;
1655
- const batch = pending;
1656
- pending = [];
 
 
 
 
 
 
 
1657
  let requeue = false;
1658
  try {
1659
  const res = await fetch(`${API_V1}/grid/events`, {
1660
  method: "POST",
1661
  credentials: CREDENTIALS,
1662
  headers: JSON_HEADERS,
1663
- body: JSON.stringify({ events: batch, scopeKey: surfaceScope }),
1664
  });
1665
  // A dead session is NOT retryable β€” replaying into a 401 forever would
1666
  // turn one expired cookie into an unbounded request loop.
@@ -1716,7 +1842,9 @@ function applyEventResult(body: unknown): void {
1716
  /** The sink hostBridge falls through to in standalone. Returns true: the event
1717
  * is now OURS (queued and owned), which is all the caller ever needed. */
1718
  function standaloneSink(event: HostEvent): boolean {
1719
- pending.push(event);
 
 
1720
  if (pending.length > MAX_REPLAY) pending.shift();
1721
  void drain();
1722
  return true;
 
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" };
 
323
  filterConj?: string;
324
  sorts?: SortSpec | null;
325
  search?: string;
326
+ /**
327
+ * ⭐⭐ W51-T06 / C6 β€” THE PINNED READ. `{table, record, via}`: narrow this window to the rows
328
+ * related to ONE record of another database, ahead of `filters`.
329
+ *
330
+ * β›” IT IS PART OF THE PATH, therefore part of the CACHE KEY, and that is not a nicety.
331
+ * `rowsCache` is keyed by path (see `windowRowsPath`), so a pin that stayed out of the string
332
+ * would make a pinned read a cache HIT on the unpinned one this browser already holds β€” the
333
+ * whole table painted under a tab that names one record, served from memory, with no request
334
+ * to see in the network panel.
335
+ */
336
+ related?: RelatedPin | null;
337
  }
338
 
339
  /**
 
365
  if (req.sorts && req.sorts.length) q.set("sorts", JSON.stringify(req.sorts));
366
  const search = (req.search ?? "").trim();
367
  if (search) q.set("search", search);
368
+ /* ⭐⭐ W51-T06 / C6 β€” THE PIN RIDES AS A JSON QUERY STRING, copying the `filters` precedent one
369
+ argument over, because `GET /odoo-tables/{key}/rows` is a GET and its `related` argument is
370
+ `Query(default=None)` (`routes_odoo_tables.py::odoo_table_rows`). β›” THE AGGREGATES DOOR IS
371
+ A POST AND TAKES THE SAME OBJECT AS A BODY KEY β€” see `fetchAggregates`. Two transports, one
372
+ payload; assuming both were bodies is the half-wired contract that paints the right rows
373
+ under a summary computed over the whole table. */
374
+ if (req.related) q.set("related", JSON.stringify(req.related));
375
  return `odoo-tables/${encodeURIComponent(tableKey)}/rows?${q.toString()}`;
376
  }
377
 
 
557
  search?: string;
558
  groupBy?: string;
559
  aggs: { colId: string; agg: string; p?: number }[];
560
+ /**
561
+ * ⭐⭐ W51-T06 / C6 β€” THE SAME PIN THE WINDOW CARRIES, or the summaries describe a different
562
+ * population than the rows under them.
563
+ *
564
+ * β›”β›” THIS IS THE HALF-WIRING TRAP, NAMED. Wire only `/rows` and the grid shows one record's
565
+ * related rows under a count and a summary bar folded over the WHOLE table: a plausible
566
+ * number, which is exactly the fabricated aggregate `no-unverifiable-aggregates` exists to
567
+ * forbid. `_compiled_read` is shared between the two doors server-side, so the ONLY way they
568
+ * can pin differently is this argument being dropped on one of them.
569
+ */
570
+ related?: RelatedPin | null;
571
  }
572
 
573
  /** C1's response, as this client reads it. `null` for a column means the server ANSWERED and
 
632
  filterConj: req.filterConj === "or" ? "or" : "and",
633
  search: (req.search ?? "").trim(),
634
  ...(req.groupBy ? { groupBy: req.groupBy } : {}),
635
+ /* β›” A BODY KEY HERE, A QUERY STRING ON `/rows` (`windowRowsPath`). Same object, two
636
+ transports, because this door is a POST and that one is a GET. */
637
+ ...(req.related ? { related: req.related } : {}),
638
  aggs: req.aggs,
639
  }),
640
  }
 
646
  return aggregatePayload(await readJson(res));
647
  }
648
 
649
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
650
+ // ⭐⭐ W51-T06 Β· RULING R2 Β· CONTRACT C6 β€” WHAT THIS DATABASE IS RELATED TO, AND WHETHER THE
651
+ // RELATION CAN BE PINNED TODAY.
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
+
678
+ /**
679
+ * ⭐⭐ CAN THIS EDGE BE SERVED AS A PINNED READ, AND IF NOT, IN WHOSE WORDS?
680
+ *
681
+ * β›”β›” THE SENTENCE HAS EXACTLY ONE AUTHOR, AND IT IS THE SERVER. `relations.py` already writes
682
+ * three of them (`unknown_via_refusal`, `unresolvable_source_refusal`,
683
+ * `unserved_target_refusal`), each naming a cause and a recommendation. Spelling a fourth here
684
+ * would be a second opinion about one wire contract, which is how a feature ships with both
685
+ * halves correct and disagreeing [[two-lanes-one-contract-dead-feature]]. So this asks for ONE
686
+ * row and reports what came back: `null` when the pin is served, the server's own sentence when
687
+ * it is not.
688
+ *
689
+ * β›” AND IT IS WHY THE TAB DOES NOT SIMPLY MOUNT AND HOPE. `useCustomerData`'s failure channel
690
+ * is `DATA_ERROR_EVENT`, which REPLACES the surface with an error card; a declared-but-unserved
691
+ * relation is a reported limit, not a broken screen. `bridge_customer_open_invoices` is the one
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
  /**
714
  * `GET /api/v1/workspace` β€” the saved views, custom fields, folders and cohorts
715
  * for the session user (S1's amendment, 2026-07-30). It exists because X2 pins
 
1680
  */
1681
  export const MAX_REPLAY = 24;
1682
 
1683
+ /**
1684
+ * ⭐⭐ W51-T06 (R5, clause 7) β€” AN EVENT CARRIES THE SCOPE IT WAS CREATED UNDER, STAMPED AT
1685
+ * ENQUEUE.
1686
+ *
1687
+ * β›”β›” IT USED TO BE READ AT DRAIN, AND A SECOND WRITABLE GRID MAKES THAT A SILENT WRONG WRITE.
1688
+ * `drain` sent `scopeKey: surfaceScope` β€” the module global, read whenever the flush happened.
1689
+ * That was safe while exactly one grid on the page could write: the only nested grid was the
1690
+ * link-record embed, which is `bindSurface: false` AND `writable: false`, so it emitted nothing.
1691
+ * A related tab (R5) mounts the TARGET database's own grid with its own view rail and its own
1692
+ * saved-view writes, so two grids on two scopes are now live at once β€” and a `view_upsert`
1693
+ * queued from the related tab could flush after the parent's next render and be filed against
1694
+ * the PARENT's database. A 200, no error, one view on the wrong table.
1695
+ *
1696
+ * β›” THE FIX IS THE STAMP, NOT A LOCK. Each queued event remembers its own scope; `drain` sends
1697
+ * the LEADING RUN of one scope per request and comes back for the rest, so ordering is
1698
+ * preserved exactly (`field_upsert` before `view_upsert` is still a field that exists before a
1699
+ * view that shows it) and a single-scope session batches byte-identically to before.
1700
+ */
1701
+ interface QueuedEvent {
1702
+ event: HostEvent;
1703
+ scope: SurfaceScope;
1704
+ }
1705
+
1706
+ let pending: QueuedEvent[] = [];
1707
  let inFlight = false;
1708
 
1709
  /**
 
1750
  }
1751
 
1752
  export function _pendingIds(): string[] {
1753
+ return pending.map((q) => q.event.id);
1754
  }
1755
 
1756
  /**
 
1771
  async function drain(): Promise<void> {
1772
  if (inFlight || pending.length === 0) return;
1773
  inFlight = true;
1774
+ /* ⭐⭐ W51-T06 β€” THE LEADING RUN OF ONE SCOPE, NOT THE WHOLE QUEUE. `scopeKey` is a property
1775
+ of the REQUEST, so a batch may only carry events that agree about it; the rest stay queued
1776
+ in order and ride the follow-up drain the `finally` below already schedules. With one grid
1777
+ writing (every session before a related tab existed) the run IS the whole queue and this is
1778
+ byte-identical to the previous behaviour. */
1779
+ const scopeKey = pending[0].scope;
1780
+ const cut = pending.findIndex((q) => q.scope !== scopeKey);
1781
+ const batch = cut < 0 ? pending : pending.slice(0, cut);
1782
+ pending = cut < 0 ? [] : pending.slice(cut);
1783
  let requeue = false;
1784
  try {
1785
  const res = await fetch(`${API_V1}/grid/events`, {
1786
  method: "POST",
1787
  credentials: CREDENTIALS,
1788
  headers: JSON_HEADERS,
1789
+ body: JSON.stringify({ events: batch.map((q) => q.event), scopeKey }),
1790
  });
1791
  // A dead session is NOT retryable β€” replaying into a 401 forever would
1792
  // turn one expired cookie into an unbounded request loop.
 
1842
  /** The sink hostBridge falls through to in standalone. Returns true: the event
1843
  * is now OURS (queued and owned), which is all the caller ever needed. */
1844
  function standaloneSink(event: HostEvent): boolean {
1845
+ // ⭐⭐ W51-T06 β€” STAMPED HERE, at the moment the event is created, which is the only moment
1846
+ // the surface it belongs to is knowable. See `QueuedEvent`.
1847
+ pending.push({ event, scope: surfaceScope });
1848
  if (pending.length > MAX_REPLAY) pending.shift();
1849
  void drain();
1850
  return true;
web/src/customer-grid/iconShapes.ts CHANGED
@@ -932,6 +932,26 @@ export const SHARE_SHAPE: IconShape[] = [
932
  { d: "M10.6 4.1a2.2 2.2 0 0 1 0 4.2M11.4 9.7c1.6.3 2.7 1.4 2.7 2.9" },
933
  ];
934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935
  export const HEADER_ICONS: Record<string, (c: { fgColor: string; bgColor: string }) => string> = {
936
  ...TYPE_SPRITES,
937
  /**
 
932
  { d: "M10.6 4.1a2.2 2.2 0 0 1 0 4.2M11.4 9.7c1.6.3 2.7 1.4 2.7 2.9" },
933
  ];
934
 
935
+ /**
936
+ * ⭐ W51-T10 β€” THE SHEET MODULE'S GLYPH, AS DATA. A page ruled into cells: one outlined sheet with
937
+ * two rules across and two down.
938
+ *
939
+ * β›” IT IS TRANSCRIBED FROM `shell/Shell.tsx::SheetIcon`, NOT DRAWN AGAIN. Same 16x16 box, same
940
+ * coordinates, same 1.35 stroke; the only change is that the component's
941
+ * `<rect x=2.3 y=2.7 width=11.4 height=10.6 rx=1.3>` is written below as the equivalent
942
+ * rounded-rectangle PATH, because an `IconShape` is path data and one serializer paints the whole
943
+ * vocabulary. The corners are the same 1.3 radius arcs the rect asked for.
944
+ *
945
+ * ⚠ THE GEOMETRY MOVED HERE BECAUSE THE COMPONENT COULD NOT. `Shell.tsx` is another lane's file
946
+ * this wave, so `SheetIcon` cannot be exported and cannot be imported; the Sheet rail's create
947
+ * menu still has to wear the mark the shell's nav row wears, and a second hand-drawn sheet would
948
+ * be a second icon language the first time either was touched. One shape, three renderers.
949
+ */
950
+ export const SHEET_SHAPE: IconShape[] = [
951
+ { d: "M3.6 2.7h8.8a1.3 1.3 0 0 1 1.3 1.3v8a1.3 1.3 0 0 1-1.3 1.3H3.6a1.3 1.3 0 0 1-1.3-1.3V4a1.3 1.3 0 0 1 1.3-1.3z" },
952
+ { d: "M2.3 6.2h11.4M2.3 9.8h11.4M6.4 2.7v10.6M10.1 2.7v10.6" },
953
+ ];
954
+
955
  export const HEADER_ICONS: Record<string, (c: { fgColor: string; bgColor: string }) => string> = {
956
  ...TYPE_SPRITES,
957
  /**
web/src/customer-grid/summary/SummaryBar.tsx CHANGED
@@ -186,8 +186,16 @@ function SummaryPicker({
186
  onDismiss={onDismiss}
187
  >
188
  {row("None", choice.agg === "none", { agg: "none" })}
 
 
 
 
 
 
 
 
189
  {options
190
- .filter((agg) => agg !== "percentile")
191
  .map((agg) => row(SUMMARY_LABELS[agg], choice.agg === agg, { agg }))}
192
  {options.includes("percentile") && (
193
  <span className="cg-sum-pgroup">
@@ -223,6 +231,8 @@ function SummaryPicker({
223
  </span>
224
  </span>
225
  )}
 
 
226
  </AnchoredOverlay>
227
  );
228
  }
 
186
  onDismiss={onDismiss}
187
  >
188
  {row("None", choice.agg === "none", { agg: "none" })}
189
+ {/* ⭐⭐ W51-T02 / R3 β€” **`share` IS FILTERED OUT HERE AND RENDERED LAST, BECAUSE THE
190
+ PERCENTILE GROUP SITS BETWEEN THEM.** The done-when's order is None / Sum / Average /
191
+ Median / Min / Max / Count / Unique / Percentile / % of total, and Percentile is not a
192
+ row but a labelled group with five points and a custom door. Left in this map, "%
193
+ of total" would print BEFORE the group it is supposed to follow β€” the array's order and
194
+ the menu's order are not the same thing once one member expands. On a text or primary
195
+ column there is no percentile group at all, so the three rows read Count / Unique /
196
+ % of total, which is the ruling's list for that column verbatim. */}
197
  {options
198
+ .filter((agg) => agg !== "percentile" && agg !== "share")
199
  .map((agg) => row(SUMMARY_LABELS[agg], choice.agg === agg, { agg }))}
200
  {options.includes("percentile") && (
201
  <span className="cg-sum-pgroup">
 
231
  </span>
232
  </span>
233
  )}
234
+ {options.includes("share")
235
+ && row(SUMMARY_LABELS.share, choice.agg === "share", { agg: "share" })}
236
  </AnchoredOverlay>
237
  );
238
  }
web/src/customer-grid/types.ts CHANGED
@@ -2790,6 +2790,28 @@ export type AggName = "sum" | "average" | "median" | "min" | "max" | "count";
2790
  */
2791
  export type SummaryAggName = AggName | "count_distinct" | "percentile";
2792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2793
  /**
2794
  * One column's summary choice, as stored in `ViewConfig.summary`.
2795
  *
@@ -2799,7 +2821,7 @@ export type SummaryAggName = AggName | "count_distinct" | "percentile";
2799
  * ⚠ `p` is meaningful only for `percentile` and is the 0-100 percent point C1 puts on the wire.
2800
  */
2801
  export interface SummaryChoice {
2802
- agg: SummaryAggName | "none";
2803
  p?: number;
2804
  }
2805
 
@@ -2874,7 +2896,14 @@ export type FilterOp =
2874
  | "aboveAvg"
2875
  | "belowAvg"
2876
  | "inQuartile"
2877
- | "inDecile";
 
 
 
 
 
 
 
2878
 
2879
  /**
2880
  * C-OPS β€” the RANK family: operators whose truth depends on the OTHER rows, not on this row's
@@ -2937,6 +2966,7 @@ const FILTER_OPS_LIST = [
2937
  "gt", "gte", "lt", "lte", "between", "within",
2938
  "topN", "bottomN", "inTopPct", "inBottomPct",
2939
  "aboveAvg", "belowAvg", "inQuartile", "inDecile",
 
2940
  ] as const;
2941
 
2942
  /** Compile-time `never` assertion β€” instantiating it with anything else is an error. */
@@ -2945,7 +2975,7 @@ type _NoneMissing = AssertNever<Exclude<FilterOp, (typeof FILTER_OPS_LIST)[numbe
2945
  type _NoneExtra = AssertNever<Exclude<(typeof FILTER_OPS_LIST)[number], FilterOp>>;
2946
  export type { _NoneMissing, _NoneExtra };
2947
 
2948
- /** All 20 operators, as data. Mirrors `aios_grid.FILTER_OPS` / `filter_sql.FILTER_OPS`. */
2949
  export const FILTER_OPS: readonly FilterOp[] = FILTER_OPS_LIST;
2950
 
2951
  /** Membership test for the engine's fail-closed `default:` branch. */
@@ -2962,6 +2992,28 @@ export const VALUE_FREE_OPS: ReadonlySet<FilterOp> = new Set<FilterOp>([
2962
  "belowAvg",
2963
  ]);
2964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2965
  /** How sibling conditions at ONE nesting level combine. Airtable allows exactly
2966
  * one conjunction per level (not per condition) β€” see FilterGroup. */
2967
  export type Conjunction = "and" | "or";
@@ -3095,6 +3147,45 @@ export function cohortIds(value: string | undefined): string[] {
3095
  return out;
3096
  }
3097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3098
  /**
3099
  * ⭐⭐ W37-T26 / CONTRACT C4 β€” **THE CYCLE REFUSAL, WHICH IS THE TICKET'S `done-when` AND NOT AN
3100
  * AFTERTHOUGHT.** View X filtered on "is in View Y" where Y is filtered on X is an infinite loop:
@@ -3236,6 +3327,18 @@ export interface FilterRule {
3236
  op: FilterOp | CohortOp | ViewOp;
3237
  value: string;
3238
  value2?: string;
 
 
 
 
 
 
 
 
 
 
 
 
3239
  /**
3240
  * CG-8. Present on a MEASURE condition: the window the measure is summed over. Its presence
3241
  * is what MAKES this a measure condition β€” no column condition has one, which is why every
@@ -3298,6 +3401,12 @@ export function isRuleActive(rule: FilterRule): boolean {
3298
  // whitespace value is INACTIVE rather than active-and-unanswerable. First, for the reason the
3299
  // cohort line above it is first.
3300
  if (rule.colId === VIEW_FIELD) return viewRuleId(rule.value) !== "";
 
 
 
 
 
 
3301
  if (VALUE_FREE_OPS.has(rule.op as FilterOp)) return true;
3302
  // "is within" is driven by its RANGE, never by `value`.
3303
  if (rule.op === "within") return normalizeWindow(rule.dateWindow) != null;
@@ -4007,6 +4116,138 @@ export interface RelationalTarget {
4007
  */
4008
  export const PIVOT_PATH = "grid/pivot";
4009
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4010
  /** C10's request, verbatim. */
4011
  export interface PivotRequest {
4012
  source: string;
 
2790
  */
2791
  export type SummaryAggName = AggName | "count_distinct" | "percentile";
2792
 
2793
+ /**
2794
+ * ⭐⭐ WAVE 51 Β· W51-T02 (owner ruling R3) β€” **THE PICKER'S VOCABULARY, WHICH IS THE WIRE'S PLUS
2795
+ * ONE, AND THE SPLIT IS WHAT KEEPS THE WIRE BYTE-IDENTICAL ON BOTH ENGINES.**
2796
+ *
2797
+ * R3 puts "% of total" on the bottom-bar picker, so `share` is a choice a reader can store. It
2798
+ * is NOT a wire name: `platform/aios_grid.SUMMARY_AGGS` is C1's eight-name clause and
2799
+ * `verify_grid_ux.py::summary_bar_shape` holds it byte-for-byte against `iconShapes.SUMMARY_AGGS`
2800
+ * β€” one array on each engine, and neither may drift alone.
2801
+ *
2802
+ * β›” SO `SummaryAggName` DOES NOT GROW, AND THAT IS A COMPILE FACT RATHER THAN A PREFERENCE.
2803
+ * `iconShapes.ts:850` declares `SUMMARY_AGG_LABELS: Record<SummaryAggName, string>` over exactly
2804
+ * the eight wire names; adding a ninth member to this union makes that literal incomplete and
2805
+ * reds a file this ticket may not open. The picker's extra name therefore lives in its own
2806
+ * union, the same way `aggregations.ts` declares the picker's ARRAY locally over the imported
2807
+ * wire one.
2808
+ *
2809
+ * ⚠ A `share` never reaches C1's `/aggregates` route. Its numerator and denominator are ordinary
2810
+ * wire aggregates (a numeric column's `sum`, anything else's `count`) and the division happens
2811
+ * client-side, which is why the wire vocabulary does not need the word at all.
2812
+ */
2813
+ export type SummaryPickAgg = SummaryAggName | "share";
2814
+
2815
  /**
2816
  * One column's summary choice, as stored in `ViewConfig.summary`.
2817
  *
 
2821
  * ⚠ `p` is meaningful only for `percentile` and is the 0-100 percent point C1 puts on the wire.
2822
  */
2823
  export interface SummaryChoice {
2824
+ agg: SummaryPickAgg | "none";
2825
  p?: number;
2826
  }
2827
 
 
2896
  | "aboveAvg"
2897
  | "belowAvg"
2898
  | "inQuartile"
2899
+ | "inDecile"
2900
+ // W51-T07 (instruction 25) - the MULTI-VALUE family. See MULTI_VALUE_OPS below: these five
2901
+ // read their operand from the leaf's `values` list, never from `value`.
2902
+ | "isAnyOf"
2903
+ | "isNoneOf"
2904
+ | "hasAnyOf"
2905
+ | "hasAllOf"
2906
+ | "hasNoneOf";
2907
 
2908
  /**
2909
  * C-OPS β€” the RANK family: operators whose truth depends on the OTHER rows, not on this row's
 
2966
  "gt", "gte", "lt", "lte", "between", "within",
2967
  "topN", "bottomN", "inTopPct", "inBottomPct",
2968
  "aboveAvg", "belowAvg", "inQuartile", "inDecile",
2969
+ "isAnyOf", "isNoneOf", "hasAnyOf", "hasAllOf", "hasNoneOf",
2970
  ] as const;
2971
 
2972
  /** Compile-time `never` assertion β€” instantiating it with anything else is an error. */
 
2975
  type _NoneExtra = AssertNever<Exclude<(typeof FILTER_OPS_LIST)[number], FilterOp>>;
2976
  export type { _NoneMissing, _NoneExtra };
2977
 
2978
+ /** All 25 operators, as data. Mirrors `aios_grid.FILTER_OPS` / `filter_sql.FILTER_OPS`. */
2979
  export const FILTER_OPS: readonly FilterOp[] = FILTER_OPS_LIST;
2980
 
2981
  /** Membership test for the engine's fail-closed `default:` branch. */
 
2992
  "belowAvg",
2993
  ]);
2994
 
2995
+ /**
2996
+ * ⭐ W51-T07 (owner instruction 25) β€” the MULTI-VALUE family: operators whose operand is a LIST
2997
+ * of allowed values rather than one typed string.
2998
+ *
2999
+ * `isAnyOf` / `isNoneOf` answer a single-valued cell (status / select / user); `hasAnyOf` /
3000
+ * `hasAllOf` / `hasNoneOf` answer a multi-select cell, which is a comma-joined SET.
3001
+ *
3002
+ * β›” THE MEMBERSHIP TEST IS LOAD-BEARING IN ALL FOUR ENGINES, and for the same reason
3003
+ * VALUE_FREE_OPS above is. These leaves leave `value` BLANK, and every engine carries a
3004
+ * historical "blank value means the rule is half-typed, so ignore it" short-circuit. An ignored
3005
+ * leaf shows EVERY row under a count nobody would doubt. So each engine intercepts these ops on
3006
+ * the OP, before any type dispatch and before any blank-value guard, and `isRuleActive` below
3007
+ * answers them from `values` instead. Mirrored by `filter_sql.MULTI_VALUE_OPS`.
3008
+ */
3009
+ export const MULTI_VALUE_OPS: ReadonlySet<FilterOp> = new Set<FilterOp>([
3010
+ "isAnyOf",
3011
+ "isNoneOf",
3012
+ "hasAnyOf",
3013
+ "hasAllOf",
3014
+ "hasNoneOf",
3015
+ ]);
3016
+
3017
  /** How sibling conditions at ONE nesting level combine. Airtable allows exactly
3018
  * one conjunction per level (not per condition) β€” see FilterGroup. */
3019
  export type Conjunction = "and" | "or";
 
3147
  return out;
3148
  }
3149
 
3150
+ /**
3151
+ * ⭐ W51-T07 β€” how many values one multi-value condition may name.
3152
+ *
3153
+ * Bounded for the same reason MAX_COHORT_IDS is: the tree is re-evaluated for EVERY row on
3154
+ * EVERY render, and each named value is one more comparison per row. 100 is generous against a
3155
+ * declared option list a person is expected to read.
3156
+ *
3157
+ * ⚠ Three hand-kept copies (here, `aios_grid.MAX_FILTER_VALUES`, `filter_sql.MAX_FILTER_VALUES`),
3158
+ * held together by verify_filter_engine.py β€” a drifted cap silently asks a NARROWER question on
3159
+ * one side than the other.
3160
+ */
3161
+ export const MAX_FILTER_VALUES = 100;
3162
+
3163
+ /**
3164
+ * The values a multi-value leaf names, parsed out of `values`.
3165
+ *
3166
+ * β›” A REAL LIST, not the comma-joined string `cohortIds` parses, and the difference is the
3167
+ * decision. A cohort id is minted from `[a-z0-9_]` so a comma cannot occur inside one; a SELECT
3168
+ * OPTION is tenant prose, and `Bouquets, mixed` is a perfectly ordinary choice. Joining on a
3169
+ * comma would split that option into two that match nothing, so the leaf persists a JSON array
3170
+ * and every layer down to the SQL binder keeps it as one.
3171
+ *
3172
+ * Same discipline as `cohortIds` otherwise: order preserved (it is the order the user picked),
3173
+ * blanks dropped, duplicates collapsed, each member capped at 120 characters, the list capped
3174
+ * at MAX_FILTER_VALUES. Unknown values are KEPT: an option that no longer exists filters to
3175
+ * nothing, honestly, and the chip that says so is what lets somebody remove it.
3176
+ */
3177
+ export function filterValues(values: readonly string[] | undefined): string[] {
3178
+ const out: string[] = [];
3179
+ if (!Array.isArray(values)) return out;
3180
+ for (const raw of values) {
3181
+ const v = String(raw ?? "").trim().slice(0, 120);
3182
+ if (v === "" || out.includes(v)) continue;
3183
+ out.push(v);
3184
+ if (out.length >= MAX_FILTER_VALUES) break;
3185
+ }
3186
+ return out;
3187
+ }
3188
+
3189
  /**
3190
  * ⭐⭐ W37-T26 / CONTRACT C4 β€” **THE CYCLE REFUSAL, WHICH IS THE TICKET'S `done-when` AND NOT AN
3191
  * AFTERTHOUGHT.** View X filtered on "is in View Y" where Y is filtered on X is an infinite loop:
 
3327
  op: FilterOp | CohortOp | ViewOp;
3328
  value: string;
3329
  value2?: string;
3330
+ /**
3331
+ * ⭐ W51-T07 β€” the operand of a MULTI_VALUE_OPS leaf ("Agent is any of [A, B, C]").
3332
+ *
3333
+ * β›” A LIST, not a comma-joined string, and that is not a style choice. `value` is an opaque
3334
+ * string every layer already truncates and round-trips, so a set could have ridden in it the
3335
+ * way `cohortIds` does β€” but a cohort id cannot contain a comma and a SELECT OPTION can
3336
+ * ("Bouquets, mixed"), so joining would split one real choice into two that match nothing.
3337
+ * The list survives as a list through `clean_filter_tree`, the SQL binder and both row
3338
+ * evaluators. Present only on those five ops; absent everywhere else, which is what keeps
3339
+ * every persisted leaf's cleaned shape byte-identical to what it always was.
3340
+ */
3341
+ values?: string[];
3342
  /**
3343
  * CG-8. Present on a MEASURE condition: the window the measure is summed over. Its presence
3344
  * is what MAKES this a measure condition β€” no column condition has one, which is why every
 
3401
  // whitespace value is INACTIVE rather than active-and-unanswerable. First, for the reason the
3402
  // cohort line above it is first.
3403
  if (rule.colId === VIEW_FIELD) return viewRuleId(rule.value) !== "";
3404
+ // W51-T07 β€” a MULTI-VALUE leaf is driven by the LIST it names and by nothing else. Third in
3405
+ // the same family as the two arms above it, and placed here for the same reason: these ops
3406
+ // leave `value` blank, so the tail rule "blank value means half-typed" would call a fully
3407
+ // built `Agent is any of [A, B, C]` inactive and show every row.
3408
+ if (MULTI_VALUE_OPS.has(rule.op as FilterOp))
3409
+ return filterValues(rule.values).length > 0;
3410
  if (VALUE_FREE_OPS.has(rule.op as FilterOp)) return true;
3411
  // "is within" is driven by its RANGE, never by `value`.
3412
  if (rule.op === "within") return normalizeWindow(rule.dateWindow) != null;
 
4116
  */
4117
  export const PIVOT_PATH = "grid/pivot";
4118
 
4119
+ /* ═══════════════════════════════════════════════════════════════════════════════════════════
4120
+ ⭐⭐ W51-T06 Β· RULINGS R2 + R5 Β· CONTRACT C6 β€” THE RELATED-DATABASE VOCABULARY.
4121
+
4122
+ R2: *"A 'Linked database' tab exists for FORWARD link fields, REVERSE links … and the ODOO
4123
+ BRIDGES … one tab per related table, resolved SERVER-SIDE."* So this file declares the SHAPE
4124
+ of the server's answer and nothing about which edges exist: `platform/core/relations.py` is
4125
+ the one declaration of that, and W51-T05 shipped it.
4126
+
4127
+ β›”β›” `via` TRAVELS BACK VERBATIM, AND REBUILDING IT IS THE SILENT-WRONG-JOIN BUG.
4128
+ `via.key` is the only member that identifies an edge on its own. `customer_data` really does
4129
+ carry two bridges reading `{direction: "bridge", on: "partner_id"}` β€” orders, and order
4130
+ lines β€” and `relations.pick` answers None on an ambiguous bag rather than returning the first
4131
+ hit. A client that reconstructed `via` from `{direction, on}` would ask for a customer's order
4132
+ LINES and be served their ORDERS: right shape, wrong question, every gate green.
4133
+ ═══════════════════════════════════════════════════════════════════════════════════════════ */
4134
+
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
+ *
4150
+ * ⚠ `served: false` IS NOT AN ERROR AND NOT A HIDDEN TAB. It records that the target grid is
4151
+ * served from its stored copy rather than read through the mirror, so its window takes no
4152
+ * predicate and the pin cannot be pushed into it yet. `bridge_customer_open_invoices` is the
4153
+ * one such edge today. The tab RENDERS and REFUSES with the server's own sentence.
4154
+ */
4155
+ export interface RelatedEntry {
4156
+ key: string;
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
+ *
4167
+ * β›” NO `label` AND NO DISPLAY WORDS. The chip's sentence is a rendering concern; putting it on
4168
+ * the wire would fork the rows cache key (`windowRowsPath`) on a rename and ask the server for
4169
+ * two different reads of one edge.
4170
+ */
4171
+ export interface RelatedPin {
4172
+ table: string;
4173
+ record: number;
4174
+ via: RelatedVia;
4175
+ }
4176
+
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
+ /**
4187
+ * The server's `/related` envelope, read defensively. An unreadable body is an EMPTY list, never
4188
+ * a throw: a record whose relations cannot be listed still has to open its Fields tab.
4189
+ */
4190
+ export function relatedEntries(body: unknown): RelatedEntry[] {
4191
+ const b = body as { ok?: unknown; related?: unknown } | null;
4192
+ if (!b || b.ok === false || !Array.isArray(b.related)) return [];
4193
+ const out: 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),
4208
+ target,
4209
+ // β›” ABSENT MEANS SERVED. A body from an older server that has not learned the key must
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. */
4252
  export interface PivotRequest {
4253
  source: string;
web/src/customer-grid/useCustomerData.ts CHANGED
@@ -22,10 +22,10 @@
22
  // overlayEdits only holds this session's un-refetched changes.
23
  // ---------------------------------------------------------------------------
24
 
25
- import { useCallback, useEffect, useRef, useState } from "react";
26
  import type { Dispatch, SetStateAction } from "react";
27
  import { topicForScope } from "./types";
28
- import type { CustomersPayload, Field, GridWorkspace, Row } from "./types";
29
  import {
30
  clearTopicRowsCache,
31
  dropTableRowsCache,
@@ -233,6 +233,17 @@ interface CustomerDataOptions {
233
  includeWorkspace?: boolean;
234
  /** Defence in depth for read-only nested grids. */
235
  writable?: boolean;
 
 
 
 
 
 
 
 
 
 
 
236
  }
237
 
238
  export function useCustomerData(
@@ -242,6 +253,22 @@ export function useCustomerData(
242
  const bindSurface = options.bindSurface !== false;
243
  const includeWorkspace = options.includeWorkspace !== false;
244
  const writable = options.writable !== false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  // β›” SET BEFORE THE FIRST FETCH, not in an effect. Every event the grid emits carries this
246
  // scope, and an effect would run AFTER the first render β€” so a write triggered by that render
247
  // would be posted as `customer` from the Cohort surface. Module scope + a synchronous set is
@@ -511,7 +538,19 @@ export function useCustomerData(
511
  // from the workspace that is still in flight beside this call, so it does not exist
512
  // yet. The grid re-asks with the saved view's predicate the moment it does β€” see
513
  // `windowPredicateKey` and the effect that consumes it.
514
- ? fetchTableWindow(tableKey, { offset: 0, limit: WINDOW_ROWS })
 
 
 
 
 
 
 
 
 
 
 
 
515
  : fetchTopicRows(topic),
516
  wsPromise,
517
  ]);
@@ -587,7 +626,10 @@ export function useCustomerData(
587
  // `topic` is a stable module constant per scope (topicForScope β€” ut topics are memoized
588
  // per key for exactly this dependency), so this cannot loop. `rowsBump` re-runs it on the
589
  // rows-stale signal only.
590
- }, [scope, topic, rowsBump, includeWorkspace]);
 
 
 
591
 
592
  // Optimistic overlay write: apply the edit immediately (so the grid cell and
593
  // the detail panel reflect it at once), snapshot the pre-edit entry, then
@@ -683,12 +725,17 @@ export function useCustomerData(
683
  if (offset > 0 && inflightOffset.current === offset) return;
684
  const seq = ++windowSeq.current;
685
  if (offset > 0) inflightOffset.current = offset;
686
- void fetchTableWindow(scope, { ...req, offset }).then((next) => {
 
 
 
 
 
687
  if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
688
  if (seq !== windowSeq.current || !next) return;
689
  setData((prev) => mergeWindow(prev, next, offset));
690
  });
691
- }, [scope]);
692
 
693
  const selectAssignedView = useCallback((viewId: string) => {
694
  // Assigned projections currently exist on the governed Customer surface.
 
22
  // overlayEdits only holds this session's un-refetched changes.
23
  // ---------------------------------------------------------------------------
24
 
25
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
26
  import type { Dispatch, SetStateAction } from "react";
27
  import { topicForScope } from "./types";
28
+ import type { CustomersPayload, Field, GridWorkspace, RelatedPin, Row } from "./types";
29
  import {
30
  clearTopicRowsCache,
31
  dropTableRowsCache,
 
233
  includeWorkspace?: boolean;
234
  /** Defence in depth for read-only nested grids. */
235
  writable?: boolean;
236
+ /**
237
+ * ⭐⭐ W51-T06 / C6 / R5 β€” THE PINNED READ: `{table, record, via}`, forwarded on EVERY read of
238
+ * a read-through grid so the rows arrive already narrowed to one record's related set.
239
+ *
240
+ * β›” THIS IS NOT `embeddedRecordIds` AND MUST NEVER BECOME IT. That path fetches the WHOLE
241
+ * table and filters to an id list in the browser, which on a connected source is standing
242
+ * rule 1 in the direction that matters: an uncapped mirror dragged client-side to be filtered
243
+ * locally. The predicate is compiled to SQL by the same `_compiled_read` the count and the
244
+ * aggregates run through, so `total` describes the pinned set rather than the table.
245
+ */
246
+ related?: RelatedPin | null;
247
  }
248
 
249
  export function useCustomerData(
 
253
  const bindSurface = options.bindSurface !== false;
254
  const includeWorkspace = options.includeWorkspace !== false;
255
  const writable = options.writable !== false;
256
+ /**
257
+ * ⭐⭐ W51-T06 / C6 β€” THE PIN, AS A STRING, AND THAT IS THE WHOLE OF THE STALE-CLOSURE FIX.
258
+ *
259
+ * β›” `requestWindow` IS A `useCallback`, AND A PIN READ OUT OF ITS CLOSURE GOES STALE. Its
260
+ * dependency list decides which copy of this value the SCROLL sends: the first window (fired
261
+ * by the load effect) would be correctly pinned and every page after it would be the whole
262
+ * table, appended underneath, under a count that still described the pinned set. A plausible
263
+ * screen with two populations in it and nothing red anywhere. The serialised form is the
264
+ * dependency BOTH readers take, so the two cannot disagree β€” the same discipline
265
+ * `windowRowsPath` uses to make a path and its cache key one value.
266
+ */
267
+ const relatedKey = options.related ? JSON.stringify(options.related) : "";
268
+ const related = useMemo(
269
+ () => (relatedKey ? (JSON.parse(relatedKey) as RelatedPin) : null),
270
+ [relatedKey]
271
+ );
272
  // β›” SET BEFORE THE FIRST FETCH, not in an effect. Every event the grid emits carries this
273
  // scope, and an effect would run AFTER the first render β€” so a write triggered by that render
274
  // would be posted as `customer` from the Cohort surface. Module scope + a synchronous set is
 
538
  // from the workspace that is still in flight beside this call, so it does not exist
539
  // yet. The grid re-asks with the saved view's predicate the moment it does β€” see
540
  // `windowPredicateKey` and the effect that consumes it.
541
+ /* ⭐⭐ W51-T06 / C6 β€” THE PIN RIDES THE FIRST WINDOW TOO. It is not a predicate the
542
+ grid applies later: it is the PREMISE of the tab, so the very first read has to
543
+ carry it or the tab paints the whole database for one frame and then narrows,
544
+ which is a wrong answer that happens to be brief. */
545
+ ? fetchTableWindow(tableKey, { offset: 0, limit: WINDOW_ROWS, related })
546
+ /* β›” AND THE WHOLE-BOOK DOOR TAKES NO PREDICATE, MEASURED RATHER THAN ASSUMED.
547
+ `routes_tables.table_rows` (which `fetchTopicRows` reaches) accepts no filter
548
+ arguments at all and is in no lane's fence this wave, so a related tab whose target
549
+ is an ordinary user table has no pre-filtered read to call. The honest answer is a
550
+ REPORTED limit, not a client-side filter over the whole table -- that is precisely
551
+ the `embeddedRecordIds` pattern W51-T06 exists to delete. `RecordDetail` therefore
552
+ probes the pinned door first (`probeRelatedRead`) and prints the server's refusal
553
+ instead of mounting this read under a chip that claims one record. */
554
  : fetchTopicRows(topic),
555
  wsPromise,
556
  ]);
 
626
  // `topic` is a stable module constant per scope (topicForScope β€” ut topics are memoized
627
  // per key for exactly this dependency), so this cannot loop. `rowsBump` re-runs it on the
628
  // rows-stale signal only.
629
+ // ⚠ `relatedKey` JOINS THE DEPS, W51-T06. The pin is part of the question this effect asks,
630
+ // so switching from one related tab to another (same target table, different edge) has to
631
+ // re-read. Without it the second tab would paint the first tab's rows.
632
+ }, [scope, topic, rowsBump, includeWorkspace, related, relatedKey]);
633
 
634
  // Optimistic overlay write: apply the edit immediately (so the grid cell and
635
  // the detail panel reflect it at once), snapshot the pre-edit entry, then
 
725
  if (offset > 0 && inflightOffset.current === offset) return;
726
  const seq = ++windowSeq.current;
727
  if (offset > 0) inflightOffset.current = offset;
728
+ /* ⭐⭐ W51-T06 / C6 β€” AND THE SCROLL CARRIES THE PIN, WHICH IS THE HALF A CLOSURE LOSES.
729
+ β›” `related` IS IN THE DEPENDENCY LIST BELOW FOR THIS ONE LINE. Left out, this callback
730
+ would keep the pin it was built with: the first page correct and every appended page the
731
+ WHOLE table, under a `total` that still described the pinned set. Nothing errors, the
732
+ count agrees with itself, and the rows are two different populations stacked. */
733
+ void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
734
  if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
735
  if (seq !== windowSeq.current || !next) return;
736
  setData((prev) => mergeWindow(prev, next, offset));
737
  });
738
+ }, [scope, related]);
739
 
740
  const selectAssignedView = useCallback((viewId: string) => {
741
  // Assigned projections currently exist on the governed Customer surface.
web/src/customer-grid/useVisibleRows.ts CHANGED
@@ -17,12 +17,14 @@ import type {
17
  Conjunction,
18
  Field,
19
  FilterNode,
 
20
  FilterRule,
21
  Row,
22
  SortSpec,
23
  VisibleRow,
24
  } from "./types";
25
- import { FILTER_OPS, cohortIds, isCohortRule, isFilterGroup, isMeasureRule, isRankOp,
 
26
  isViewRule, normalizeViewOp, viewRuleId, ROUTE_PROJECTION_KEY, routeStopPosition,
27
  singleRouteScope, isBlankValue,
28
  isRuleActive, normalizeCohortOp, rhsColId } from "./types";
@@ -158,6 +160,21 @@ function matchFilter(
158
  // is a property of today's call graph and this file outlives it.
159
  if (isRankOp(rule.op)) return false;
160
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  // --- CG-9: the comparand is another CELL of this row, not a typed value ----------------
162
  // Read once, here, so every type branch below coerces it through the LEFT field's type β€” the
163
  // same type this function is already dispatching on. `evalNode` has already established that
@@ -280,6 +297,54 @@ function cmpText(op: FilterRule["op"], a: string, v: string): boolean {
280
  }
281
  }
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  /**
284
  * Evaluate one node of the filter TREE against a row.
285
  * returns true/false = the node decided
 
17
  Conjunction,
18
  Field,
19
  FilterNode,
20
+ FilterOp,
21
  FilterRule,
22
  Row,
23
  SortSpec,
24
  VisibleRow,
25
  } from "./types";
26
+ import { FILTER_OPS, MULTI_VALUE_OPS, filterValues,
27
+ cohortIds, isCohortRule, isFilterGroup, isMeasureRule, isRankOp,
28
  isViewRule, normalizeViewOp, viewRuleId, ROUTE_PROJECTION_KEY, routeStopPosition,
29
  singleRouteScope, isBlankValue,
30
  isRuleActive, normalizeCohortOp, rhsColId } from "./types";
 
160
  // is a property of today's call graph and this file outlives it.
161
  if (isRankOp(rule.op)) return false;
162
 
163
+ // --- ⭐ W51-T07: the MULTI-VALUE family, ON THE OP and before every type branch ----------
164
+ // Placed here for the reason the two value-free lines above are: these leaves carry a BLANK
165
+ // `value`, and each type branch below ends in a "blank value -> active and always true"
166
+ // short-circuit. Falling through even one of them would make `Agent is any of [A, B, C]`
167
+ // match every row under a count nobody would doubt.
168
+ if (MULTI_VALUE_OPS.has(rule.op as FilterOp)) {
169
+ // A numeric or date column does not OFFER these, but a stale saved view can carry one (a
170
+ // column that has since changed type). Matching NOTHING is the decision, in all three
171
+ // engines: `cmpNum`'s documented `default: true` would widen, and comparing a rounded
172
+ // number against its own string form would have the engines disagree about the RENDERING
173
+ // rather than the value (`String(5000)`, `str(5000)` and DuckDB's CAST do not agree).
174
+ if (isNumericType(f.type) || isDateType(f.type)) return false;
175
+ return matchMultiValue(rule.op, raw, filterValues(rule.values));
176
+ }
177
+
178
  // --- CG-9: the comparand is another CELL of this row, not a typed value ----------------
179
  // Read once, here, so every type branch below coerces it through the LEFT field's type β€” the
180
  // same type this function is already dispatching on. `evalNode` has already established that
 
297
  }
298
  }
299
 
300
+ /**
301
+ * ⭐ W51-T07 β€” the MEMBERS of one cell, for the multi-value SET ops.
302
+ *
303
+ * A `multiselect` cell is a comma-joined set (and may still arrive as an ARRAY from the wire,
304
+ * which `String()` joins on the same comma). A single-valued cell is a one-member set, so
305
+ * `hasAnyOf` over a select column means exactly what `isAnyOf` does there β€” one definition, not
306
+ * two that could disagree.
307
+ *
308
+ * Folded and trimmed exactly as `cmpText`'s operands are. A BLANK cell yields NO members, which
309
+ * is the decision the three engines pin as a lock-step case: a blank is not a member of
310
+ * anything, so `hasNoneOf` and `isNoneOf` answer TRUE over it and the other three answer FALSE.
311
+ */
312
+ function cellMembers(raw: unknown): string[] {
313
+ return String(raw ?? "")
314
+ .toLowerCase()
315
+ .split(",")
316
+ .map((s) => s.trim())
317
+ .filter((s) => s !== "");
318
+ }
319
+
320
+ /**
321
+ * ⭐ W51-T07 β€” the five multi-value operators, COMPOSED from the single-value comparator rather
322
+ * than written again beside it.
323
+ *
324
+ * That composition is the ticket's correctness target, not an economy: `isAnyOf [A, B, C]` is
325
+ * literally the OR of three `cmpText("eq", …)` calls, so it is the union of three `eq` leaves
326
+ * by construction, including how each one treats the connector's `(none)` sentinel. A parallel
327
+ * comparison would have to be shown equal to `eq` by testing, and only for the values tested.
328
+ */
329
+ function matchMultiValue(op: FilterRule["op"], raw: unknown, values: string[]): boolean {
330
+ const want = values.map((v) => v.trim().toLowerCase());
331
+ // β›” NO VALUES = UNANSWERABLE = MATCHES NOTHING, uniformly, and this is a SECOND layer:
332
+ // `isRuleActive` already calls such a leaf inactive, so `evalNode` never gets here. It is
333
+ // written anyway because the vacuous cases go the WIDENING way β€” `[].every(...)` is `true`, so
334
+ // `hasAllOf []` would match every row, and `!want.some(...)` would do the same for the two
335
+ // `none` operators. `filter_sql` answers `1=0` for the identical input; one definition.
336
+ if (!want.length) return false;
337
+ if (op === "isAnyOf" || op === "isNoneOf") {
338
+ const a = String(raw ?? "").toLowerCase();
339
+ const hit = want.some((v) => cmpText("eq", a, v));
340
+ return op === "isAnyOf" ? hit : !hit;
341
+ }
342
+ const members = cellMembers(raw);
343
+ if (op === "hasAllOf") return want.every((v) => members.includes(v));
344
+ const hit = want.some((v) => members.includes(v));
345
+ return op === "hasAnyOf" ? hit : !hit;
346
+ }
347
+
348
  /**
349
  * Evaluate one node of the filter TREE against a row.
350
  * returns true/false = the node decided
web/src/filter-kit/FilterBuilderPanel.tsx CHANGED
@@ -12,8 +12,8 @@
12
  // same panel serve a module whose rows this browser has never loaded.
13
  // ---------------------------------------------------------------------------
14
 
15
- import { useCallback, useMemo, useState } from "react";
16
- import type { ReactNode } from "react";
17
  import type {
18
  Conjunction,
19
  Field,
@@ -27,9 +27,10 @@ import type {
27
  Measure,
28
  } from "../customer-grid/types";
29
  import {
30
- COHORT_FIELD, MAX_COHORT_IDS, MAX_FILTER_DEPTH, RANK_OPS, STAT_KINDS, STAT_LABELS,
 
31
  VIEW_FIELD, VIEW_OPS, VIEW_OP_LABELS, normalizeViewOp,
32
- VALUE_FREE_OPS, choiceOptions, cohortIds, filterTreeConj, filterTreeNodes,
33
  filterableFields, isFilterGroup, isMeasureRule, isRankOp, normalizeCohortOp, rhsColId,
34
  } from "../customer-grid/types";
35
  import type { CohortOp, StatKind } from "../customer-grid/types";
@@ -37,6 +38,10 @@ import type { AnchorMode } from "../customer-grid/windows";
37
  import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N } from "../customer-grid/windows";
38
  import { FieldSelectButton } from "../customer-grid/FieldSelect";
39
  import type { FieldSelectItem } from "../customer-grid/FieldSelect";
 
 
 
 
40
  // W47-T13 (owner instruction 15) β€” the remove-a-condition mark, taken from the ONE icon
41
  // vocabulary rather than hand-drawn a second time. `filter-kit/FieldsHidePanel.tsx` already
42
  // imports across this same boundary for `FieldTypeIcon`, so the direction is established.
@@ -180,13 +185,20 @@ function ConditionValue({
180
  statusOptions,
181
  onValue,
182
  onValue2,
 
183
  }: {
184
  rule: FilterRule;
185
  type: Field["type"];
186
  statusOptions: string[];
187
  onValue: (v: string) => void;
188
  onValue2: (v: string) => void;
 
189
  }) {
 
 
 
 
 
190
  if (rule.op === "between") {
191
  const inputType = type === "date" || type === "created_time" ? "date" : "number";
192
  return (
@@ -373,6 +385,211 @@ function CohortPicker({
373
  );
374
  }
375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  // --- Filter: an Airtable-style RECURSIVE condition builder -----------------
377
  // Anatomy per Airtable (captured from the live product 2026-07-25):
378
  // row 0 : static "Where"
@@ -634,6 +851,18 @@ function LeafRow({
634
  // these three" are the same three cohorts asked about differently, and clearing them would
635
  // make the obvious edit destructive.
636
  if (isCohort) return patch({ op });
 
 
 
 
 
 
 
 
 
 
 
 
637
  // C-OPS: a rank op arrives with its N already chosen (see rankDefault) and drops every
638
  // comparand β€” "the top 10 compared with another field" is not a question.
639
  if (isRankOp(op as string))
@@ -657,8 +886,11 @@ function LeafRow({
657
  .filter((f) => f.key !== rule.colId
658
  && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
659
  .map((f) => ({ key: f.key, label: f.label, type: f.type }));
 
 
660
  const canCompareField = !isCohort && rule.op !== "within"
661
  && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op)
 
662
  && rhsOptions.length > 0
663
  && (isMeasure || isNumericType(t) || isDateFamily(t) || isTextComparable(t));
664
  // ⭐ W46-T30 β€” the tail moved, and NOTHING ELSE DID. Everything under a text comparand was
@@ -894,6 +1126,7 @@ function LeafRow({
894
  statusOptions={choicesFor(rule.colId)}
895
  onValue={(v) => patch({ value: v })}
896
  onValue2={(v) => patch({ value2: v })}
 
897
  />
898
  )}
899
  {/* W47-T13 (owner instruction 15) β€” A TRASH MARK, NOT AN Γ—. The glyph was ambiguous
 
12
  // same panel serve a module whose rows this browser has never loaded.
13
  // ---------------------------------------------------------------------------
14
 
15
+ import { useCallback, useMemo, useRef, useState } from "react";
16
+ import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
17
  import type {
18
  Conjunction,
19
  Field,
 
27
  Measure,
28
  } from "../customer-grid/types";
29
  import {
30
+ COHORT_FIELD, MAX_COHORT_IDS, MAX_FILTER_DEPTH, MAX_FILTER_VALUES, MULTI_VALUE_OPS,
31
+ RANK_OPS, STAT_KINDS, STAT_LABELS,
32
  VIEW_FIELD, VIEW_OPS, VIEW_OP_LABELS, normalizeViewOp,
33
+ VALUE_FREE_OPS, choiceOptions, cohortIds, filterTreeConj, filterTreeNodes, filterValues,
34
  filterableFields, isFilterGroup, isMeasureRule, isRankOp, normalizeCohortOp, rhsColId,
35
  } from "../customer-grid/types";
36
  import type { CohortOp, StatKind } from "../customer-grid/types";
 
38
  import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N } from "../customer-grid/windows";
39
  import { FieldSelectButton } from "../customer-grid/FieldSelect";
40
  import type { FieldSelectItem } from "../customer-grid/FieldSelect";
41
+ // ⭐ W51-T07 β€” the house popover shell. `FieldSelectButton` above is SINGLE-select by
42
+ // construction and its file is not this ticket's to widen, so the multi-value picker below is a
43
+ // local control built on the same overlay every other picker in this panel opens through.
44
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
45
  // W47-T13 (owner instruction 15) β€” the remove-a-condition mark, taken from the ONE icon
46
  // vocabulary rather than hand-drawn a second time. `filter-kit/FieldsHidePanel.tsx` already
47
  // imports across this same boundary for `FieldTypeIcon`, so the direction is established.
 
185
  statusOptions,
186
  onValue,
187
  onValue2,
188
+ onValues,
189
  }: {
190
  rule: FilterRule;
191
  type: Field["type"];
192
  statusOptions: string[];
193
  onValue: (v: string) => void;
194
  onValue2: (v: string) => void;
195
+ onValues: (v: string[]) => void;
196
  }) {
197
+ // ⭐ W51-T07 β€” FIRST, and on the OP alone. Every arm below is untouched, which is the
198
+ // done-when's "the old single-value ops keep working for saved filters": a view holding
199
+ // `Status is Growing` renders through exactly the code that always rendered it.
200
+ if (MULTI_VALUE_OPS.has(rule.op as FilterOp))
201
+ return <MultiValuePicker rule={rule} options={statusOptions} onValues={onValues} />;
202
  if (rule.op === "between") {
203
  const inputType = type === "date" || type === "created_time" ? "date" : "number";
204
  return (
 
385
  );
386
  }
387
 
388
+ /** The house tick, drawn to the same 16px path `FieldSelect`'s own list rows wear, so a ticked
389
+ * row reads identically in both popovers. Same glyph, same class, no new icon language. */
390
+ function TickMark() {
391
+ return (
392
+ <svg className="cg-type-check" width="14" height="14" viewBox="0 0 16 16" fill="none"
393
+ aria-hidden>
394
+ <path d="m3.5 8.5 3 3 6-6.5" stroke="currentColor" strokeWidth={1.6}
395
+ strokeLinecap="round" strokeLinejoin="round" />
396
+ </svg>
397
+ );
398
+ }
399
+
400
+ /** The caret every closed picker on this surface wears. `FieldSelect`'s copy is local to that
401
+ * file; this is the same 16px path, not a second mark. */
402
+ function PickerCaret() {
403
+ return (
404
+ <svg className="cg-fsel-caret" width="10" height="10" viewBox="0 0 16 16" fill="none"
405
+ aria-hidden>
406
+ <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth={1.5}
407
+ strokeLinecap="round" strokeLinejoin="round" />
408
+ </svg>
409
+ );
410
+ }
411
+
412
+ /**
413
+ * ⭐ W51-T07 (owner instruction 25) β€” the value control for a MULTI-VALUE condition:
414
+ * `Where [Agent] [is any of] [Naomi] [Ravi] [Sam]`.
415
+ *
416
+ * CHIPS PLUS A TICK LIST, modelled on `CohortPicker` directly above, because it answers the same
417
+ * shape of question and the two must not read as two different controls. What is chosen is said
418
+ * in words beside the operator; what is available is ticked in a popover that STAYS OPEN, so
419
+ * three or more values are chosen in one visit rather than one reopen each.
420
+ *
421
+ * ⚠ NOT `FieldSelectButton`. That control is single-select by construction (`onChange(key)`
422
+ * replaces), and widening it belongs to its own file, not to this ticket. The trigger below
423
+ * borrows its CLASSES so the two look like one control family, and its `is-empty` modifier is
424
+ * what renders an unfinished condition as unfinished (D-229) β€” the same muted placeholder state
425
+ * every other value picker in this panel already uses. There is no second incompleteness mark.
426
+ *
427
+ * β›” EXACTLY ONE `.cg-cond-val` in the row, on the trigger. A chip is not a value control, and
428
+ * the shipped round-trip gate locates the value control by that class.
429
+ *
430
+ * A chosen value the column no longer declares is KEPT and marked `cg-chip--gone` (the same
431
+ * amber the cohort picker uses for a list that is gone), showing the value's own text. It
432
+ * filters to nothing, honestly, and the chip is what lets somebody remove it.
433
+ */
434
+ function MultiValuePicker({
435
+ rule,
436
+ options,
437
+ onValues,
438
+ }: {
439
+ rule: FilterRule;
440
+ options: string[];
441
+ onValues: (values: string[]) => void;
442
+ }) {
443
+ const [open, setOpen] = useState(false);
444
+ const [q, setQ] = useState("");
445
+ const triggerRef = useRef<HTMLButtonElement>(null);
446
+ const listRef = useRef<HTMLDivElement>(null);
447
+
448
+ const chosen = filterValues(rule.values);
449
+ const declared = new Set(options);
450
+ const atCap = chosen.length >= MAX_FILTER_VALUES;
451
+ const needle = q.trim().toLowerCase();
452
+ const shown = needle
453
+ ? options.filter((o) => o.toLowerCase().includes(needle))
454
+ : options;
455
+
456
+ const close = () => {
457
+ setOpen(false);
458
+ setQ("");
459
+ };
460
+ const toggle = (value: string) => {
461
+ if (chosen.includes(value)) return onValues(chosen.filter((c) => c !== value));
462
+ if (atCap) return; // the cap sentence in the popover says why
463
+ onValues([...chosen, value]);
464
+ };
465
+
466
+ /** Arrows walk the rows, and the find box is part of the loop β€” the same contract
467
+ * `FieldSelect`'s list keeps, so one keyboard habit serves both popovers. */
468
+ const onListKeyDown = (event: ReactKeyboardEvent) => {
469
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp"
470
+ && event.key !== "Home" && event.key !== "End") return;
471
+ const rows = Array.from(
472
+ listRef.current?.querySelectorAll<HTMLButtonElement>("button.cg-type-row") ?? []
473
+ ).filter((el) => !el.disabled);
474
+ if (!rows.length) return;
475
+ event.preventDefault();
476
+ const at = rows.indexOf(document.activeElement as HTMLButtonElement);
477
+ if (event.key === "Home") return rows[0].focus();
478
+ if (event.key === "End") return rows[rows.length - 1].focus();
479
+ const step = event.key === "ArrowDown" ? 1 : -1;
480
+ const next = at < 0 ? (step === 1 ? 0 : rows.length - 1)
481
+ : (at + step + rows.length) % rows.length;
482
+ rows[next].focus();
483
+ };
484
+
485
+ return (
486
+ <span className="cg-cond-cohorts">
487
+ {chosen.map((value) => (
488
+ <span key={value} className={"cg-chip" + (declared.has(value) ? "" : " cg-chip--gone")}>
489
+ <span className="cg-chip-text">{value}</span>
490
+ <button
491
+ type="button"
492
+ className="cg-chip-x"
493
+ aria-label={`Remove ${value}`}
494
+ onClick={() => onValues(chosen.filter((c) => c !== value))}
495
+ >
496
+ Γ—
497
+ </button>
498
+ </span>
499
+ ))}
500
+ <button
501
+ ref={triggerRef}
502
+ type="button"
503
+ className={"cg-select cg-fsel cg-cond-val cg-cond-cohort-add"
504
+ + (chosen.length ? "" : " is-empty")}
505
+ aria-label="Filter values"
506
+ aria-haspopup="dialog"
507
+ aria-expanded={open}
508
+ onClick={() => setOpen((o) => !o)}
509
+ >
510
+ <span className="cg-fsel-nomark" aria-hidden />
511
+ {/* Short on purpose: this control is 136px, and the string that has to stay readable
512
+ beside it is a tenant's own option name. Third rule of this file's labels.
513
+ ⭐ AND THESE TWO ARE MEASURED, not judged by eye β€” the sixth time a label has
514
+ outgrown this control is the first time anyone had the number. At the rendered
515
+ 13.8125px Inter the label box is 82px, and the first draft clipped in BOTH states:
516
+ "Add a value…" needs 89px and shipped as "Add a valu…", "Select values…" needs 99px.
517
+ "Add more…" is 76px and "Select…" is 53px, so both fit with room for the caret.
518
+ "Select…" is also what `ConditionValue`'s single-value picker already says one arm
519
+ over, so the empty state now reads the same in both. Re-measure before rewording:
520
+ `getComputedStyle` on `.cg-fsel-label` against a hidden probe span. */}
521
+ <span className="cg-fsel-label">
522
+ {chosen.length ? "Add more…" : "Select…"}
523
+ </span>
524
+ <PickerCaret />
525
+ </button>
526
+ {open && triggerRef.current && (
527
+ <AnchoredOverlay
528
+ anchor={triggerRef.current}
529
+ className="cg-pop cg-fsel-pop"
530
+ onDismiss={close}
531
+ role="dialog"
532
+ ariaLabel="Filter values"
533
+ initialFocus=".cg-fsel-search input"
534
+ dataKind="filter-values"
535
+ >
536
+ <div className="cg-fsel-body" onKeyDown={onListKeyDown}>
537
+ <div className="cg-type-search cg-fsel-search">
538
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
539
+ <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
540
+ <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
541
+ strokeLinecap="round" />
542
+ </svg>
543
+ <input
544
+ type="text"
545
+ value={q}
546
+ placeholder="Find a choice…"
547
+ aria-label="Find a choice"
548
+ onChange={(event) => setQ(event.target.value)}
549
+ />
550
+ </div>
551
+ <div className="cg-type-list" role="listbox" aria-multiselectable ref={listRef}
552
+ aria-label="Filter values">
553
+ {shown.map((value) => {
554
+ const on = chosen.includes(value);
555
+ return (
556
+ <button
557
+ key={value}
558
+ type="button"
559
+ role="option"
560
+ aria-selected={on}
561
+ // Ticking is always allowed; only ADDING past the cap is refused, so a
562
+ // full list can still be edited down without first closing the popover.
563
+ disabled={!on && atCap}
564
+ className={"cg-type-row" + (on ? " is-on" : "")}
565
+ onClick={() => toggle(value)}
566
+ >
567
+ <span className="cg-fsel-nomark" aria-hidden />
568
+ <span className="cg-type-label">{value}</span>
569
+ {on && <TickMark />}
570
+ </button>
571
+ );
572
+ })}
573
+ {shown.length === 0 && (
574
+ // D-236: a column that declares nothing says so in its own words. A search that
575
+ // matched nothing is a DIFFERENT sentence, because it is a different situation.
576
+ <div className="cg-pop-note">
577
+ {options.length === 0 ? "No values yet" : "No value matches"}
578
+ </div>
579
+ )}
580
+ </div>
581
+ {atCap && (
582
+ <div className="cg-pop-note">
583
+ {`A condition can name up to ${MAX_FILTER_VALUES} values. Remove one to add another.`}
584
+ </div>
585
+ )}
586
+ </div>
587
+ </AnchoredOverlay>
588
+ )}
589
+ </span>
590
+ );
591
+ }
592
+
593
  // --- Filter: an Airtable-style RECURSIVE condition builder -----------------
594
  // Anatomy per Airtable (captured from the live product 2026-07-25):
595
  // row 0 : static "Where"
 
851
  // these three" are the same three cohorts asked about differently, and clearing them would
852
  // make the obvious edit destructive.
853
  if (isCohort) return patch({ op });
854
+ // ⭐ W51-T07 β€” a MULTI-VALUE leaf keeps its SET when the set operator changes, for exactly
855
+ // the reason the cohort line above it does: "is any of these three" and "is none of these
856
+ // three" are the same three values asked about differently, and clearing them would make the
857
+ // obvious edit destructive. The comparand goes, because a set question has no other side.
858
+ if (MULTI_VALUE_OPS.has(op as FilterOp))
859
+ return onRule({ ...rule, op: op as FilterOp, value: "", value2: undefined,
860
+ rhs: undefined, dateWindow: undefined,
861
+ values: filterValues(rule.values) });
862
+ // Leaving the family drops the list rather than leaving it to ride along invisibly on a
863
+ // condition that no longer reads it (`clean_filter_tree` emits `values` for these ops only).
864
+ if (MULTI_VALUE_OPS.has(rule.op as FilterOp))
865
+ return onRule({ ...rule, op, values: undefined });
866
  // C-OPS: a rank op arrives with its N already chosen (see rankDefault) and drops every
867
  // comparand β€” "the top 10 compared with another field" is not a question.
868
  if (isRankOp(op as string))
 
886
  .filter((f) => f.key !== rule.colId
887
  && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
888
  .map((f) => ({ key: f.key, label: f.label, type: f.type }));
889
+ // W51-T07: and never for a multi-value op β€” "is any of [a list]" has no second side to
890
+ // compare against, so offering "another field" would promise a question no engine answers.
891
  const canCompareField = !isCohort && rule.op !== "within"
892
  && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op)
893
+ && !MULTI_VALUE_OPS.has(rule.op as FilterOp)
894
  && rhsOptions.length > 0
895
  && (isMeasure || isNumericType(t) || isDateFamily(t) || isTextComparable(t));
896
  // ⭐ W46-T30 β€” the tail moved, and NOTHING ELSE DID. Everything under a text comparand was
 
1126
  statusOptions={choicesFor(rule.colId)}
1127
  onValue={(v) => patch({ value: v })}
1128
  onValue2={(v) => patch({ value2: v })}
1129
+ onValues={(v) => patch({ values: v })}
1130
  />
1131
  )}
1132
  {/* W47-T13 (owner instruction 15) β€” A TRASH MARK, NOT AN Γ—. The glyph was ambiguous
web/src/filter-kit/ops.ts CHANGED
@@ -20,7 +20,7 @@ import type {
20
  Measure,
21
  } from "../customer-grid/types";
22
  import {
23
- COHORT_FIELD, COHORT_OPS, MEASURE_OPS, MEASURE_PAIR_OPS, isFilterGroup,
24
  isDateFamilyType, isNumericFieldType, isRankOp, normalizeCohortOp,
25
  } from "../customer-grid/types";
26
  import type { CohortOp } from "../customer-grid/types";
@@ -72,15 +72,25 @@ export function opsForType(t: FieldType): FilterOp[] {
72
  // `select` and `user` are picked from a fixed list, so they behave like `status`: is / is
73
  // not / empty. `contains` on a chosen value is a substring test against a closed vocabulary β€”
74
  // it would find "Done" inside "Not done" and read as a bug.
 
 
 
 
75
  if (t === "status" || t === "select" || t === "user")
76
- return ["eq", "neq", "isEmpty", "isNotEmpty"];
77
  // A `multiselect` cell is a comma-joined SET, so the useful question is membership β€” "has" β€”
78
  // which is the EXISTING `contains` op over the joined string (no new engine vocabulary; the
79
  // ops are mirrored in filter_sql.py and inventing one here would break the lock-step). The
80
  // value is still picked from the declared options, so the substring caveat above is bounded
81
  // by the user's own choice list. `eq` reads "is exactly": the whole set is that one choice.
 
 
 
 
 
82
  if (t === "multiselect")
83
- return ["contains", "doesNotContain", "eq", "neq", "isEmpty", "isNotEmpty"];
 
84
  // ⭐ Wave-23 C7 β€” `json` gets EXACTLY the two value-free ops, and the omissions are the
85
  // decision. `contains` over a serialized document is a substring test against punctuation and
86
  // key names: `contains "12"` would match a key `id_12`, a value 12, a timestamp and a
@@ -209,6 +219,25 @@ export function opLabel(op: FilterOp, t: FieldType): string {
209
  // Type-independent: Airtable words these identically for every field type.
210
  if (op === "isEmpty") return "is empty";
211
  if (op === "isNotEmpty") return "is not empty";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  if (isDateFamily(t)) {
213
  switch (op) {
214
  case "eq":
 
20
  Measure,
21
  } from "../customer-grid/types";
22
  import {
23
+ COHORT_FIELD, COHORT_OPS, MEASURE_OPS, MEASURE_PAIR_OPS, MULTI_VALUE_OPS, isFilterGroup,
24
  isDateFamilyType, isNumericFieldType, isRankOp, normalizeCohortOp,
25
  } from "../customer-grid/types";
26
  import type { CohortOp } from "../customer-grid/types";
 
72
  // `select` and `user` are picked from a fixed list, so they behave like `status`: is / is
73
  // not / empty. `contains` on a chosen value is a substring test against a closed vocabulary β€”
74
  // it would find "Done" inside "Not done" and read as a bug.
75
+ // ⭐ W51-T07 (owner instruction 25) β€” "is any of" / "is none of" APPENDED, never prepended.
76
+ // The first entry is what `newCondition` seeds, and a new condition that starts on a
77
+ // multi-value op would open with an empty list, i.e. INACTIVE, which reads as a control that
78
+ // does nothing. `eq` stays the default; the set question is the second thing you reach for.
79
  if (t === "status" || t === "select" || t === "user")
80
+ return ["eq", "neq", "isAnyOf", "isNoneOf", "isEmpty", "isNotEmpty"];
81
  // A `multiselect` cell is a comma-joined SET, so the useful question is membership β€” "has" β€”
82
  // which is the EXISTING `contains` op over the joined string (no new engine vocabulary; the
83
  // ops are mirrored in filter_sql.py and inventing one here would break the lock-step). The
84
  // value is still picked from the declared options, so the substring caveat above is bounded
85
  // by the user's own choice list. `eq` reads "is exactly": the whole set is that one choice.
86
+ //
87
+ // ⭐ W51-T07 β€” and the three SET questions beside them, because the substring caveat above is
88
+ // exactly what `hasAnyOf` / `hasAllOf` / `hasNoneOf` remove: they compare whole MEMBERS of the
89
+ // joined set, so "has any of [Done]" can no longer find Done inside Not done. Appended, so
90
+ // `contains` stays the seeded default (see the status branch above).
91
  if (t === "multiselect")
92
+ return ["contains", "doesNotContain", "hasAnyOf", "hasAllOf", "hasNoneOf",
93
+ "eq", "neq", "isEmpty", "isNotEmpty"];
94
  // ⭐ Wave-23 C7 β€” `json` gets EXACTLY the two value-free ops, and the omissions are the
95
  // decision. `contains` over a serialized document is a substring test against punctuation and
96
  // key names: `contains "12"` would match a key `id_12`, a value 12, a timestamp and a
 
219
  // Type-independent: Airtable words these identically for every field type.
220
  if (op === "isEmpty") return "is empty";
221
  if (op === "isNotEmpty") return "is not empty";
222
+ // ⭐ W51-T07 β€” the MULTI-VALUE family, type-independently and BEFORE the type branches, for
223
+ // the reason the rank line at the top of this function is first: a saved view whose column has
224
+ // since changed type must still SAY what it holds rather than falling through to a raw key.
225
+ // The wording matches `cohortOpLabel`, which has answered the same set question since
226
+ // 2026-07-27 β€” one vocabulary for "any of" / "all of" / "none of" across the whole builder.
227
+ if (MULTI_VALUE_OPS.has(op)) {
228
+ switch (op) {
229
+ case "isAnyOf":
230
+ return "is any of";
231
+ case "isNoneOf":
232
+ return "is none of";
233
+ case "hasAnyOf":
234
+ return "has any of";
235
+ case "hasAllOf":
236
+ return "has all of";
237
+ case "hasNoneOf":
238
+ return "has none of";
239
+ }
240
+ }
241
  if (isDateFamily(t)) {
242
  switch (op) {
243
  case "eq":
web/src/filter-kit/standalone.html ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Filter kit standalone</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="./standalone.tsx"></script>
11
+ </body>
12
+ </html>
web/src/filter-kit/standalone.tsx ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // filter-kit / standalone.tsx β€” THE VISUAL-PROOF MOUNT, and nothing else.
3
+ //
4
+ // W51-T07 owed `shots/T07-multi-value-filter.png` and neither of the ordinary routes to a
5
+ // screenshot was open: deployed staging does not carry an unmerged lane branch, and the local
6
+ // app needs `STORE_BACKEND=pg` (the `hf` store repos have been 404 since 2026-08-30), which
7
+ // means Neon, which wave 51's shared-resources table reserves to ROOT. `FilterBuilderPanel`
8
+ // fetches nothing β€” every vocabulary it needs arrives as a prop β€” so it mounts here against
9
+ // fixtures with no backend, no auth and no tenant data at all.
10
+ //
11
+ // β›” THIS FILE NEVER SHIPS. `vite build`'s only input is `index.html`; the dev server serves any
12
+ // `.html` under the project root by path, which is what makes this work with no `vite.config.ts`
13
+ // change (that file belongs to no lane's fence). Confirm after any build that no emitted chunk
14
+ // names it.
15
+ // ---------------------------------------------------------------------------
16
+ import { useState } from "react";
17
+ import { createRoot } from "react-dom/client";
18
+ import { FilterBuilderPanel } from "./FilterBuilderPanel";
19
+ import type { Field, FilterTree } from "../customer-grid/types";
20
+ import "../index.css";
21
+
22
+ // A backend is never reached, but a stray fetch must not throw into the render either.
23
+ globalThis.fetch = (() =>
24
+ Promise.resolve(new Response("{}", { status: 200 }))) as typeof fetch;
25
+
26
+ const FIELDS: Field[] = [
27
+ { key: "name", label: "Customer", type: "text" },
28
+ { key: "agent", label: "Agent", type: "select",
29
+ options: ["Naomi", "Tara", "Devon", "Priya", "Marcus", "Yuki"] },
30
+ { key: "stage", label: "Stage", type: "status",
31
+ options: ["New", "Qualified", "Proposal", "Won", "Lost"] },
32
+ { key: "tags", label: "Tags", type: "multiselect",
33
+ options: ["VIP", "Wholesale", "Net 30", "Seasonal", "Do not call"] },
34
+ { key: "owner", label: "Owner", type: "user" },
35
+ { key: "no_options", label: "Region", type: "select" },
36
+ ] as unknown as Field[];
37
+
38
+ function App() {
39
+ const [filters, setFilters] = useState<FilterTree>({
40
+ conj: "and",
41
+ nodes: [
42
+ // The money shot: three values ticked on a select column.
43
+ { colId: "agent", op: "isAnyOf", value: "", values: ["Naomi", "Tara", "Devon"] },
44
+ // D-229 and D-236 in the same frame: a multi-value leaf with NO values yet, on a column
45
+ // that declares no options at all. It must render INCOMPLETE, never silently inactive,
46
+ // and its popover must say "No values yet" rather than "No value matches".
47
+ { colId: "no_options", op: "isAnyOf", value: "", values: [] },
48
+ ],
49
+ } as unknown as FilterTree);
50
+ return (
51
+ <div style={{ padding: 24, width: 1440, background: "var(--cg-bg, #fff)" }}>
52
+ <FilterBuilderPanel
53
+ fields={FIELDS}
54
+ filters={filters}
55
+ onChange={setFilters}
56
+ userOptions={["ana@example.com", "ben@example.com", "cleo@example.com"]}
57
+ statusValues={{ owner: ["ana@example.com", "ben@example.com", "cleo@example.com"] }}
58
+ />
59
+ <pre id="tree-readback" style={{ marginTop: 24, fontSize: 11 }}>
60
+ {JSON.stringify(filters, null, 2)}
61
+ </pre>
62
+ </div>
63
+ );
64
+ }
65
+
66
+ createRoot(document.getElementById("root")!).render(<App />);
web/src/index.css CHANGED
@@ -19,6 +19,16 @@
19
  to inherit its spacing -- an @imported sheet loses every equal-specificity fight with this one. */
20
  @import "./styles/wave42/hop-editor.css";
21
  @import "./styles/wave42/rail-views.css";
 
 
 
 
 
 
 
 
 
 
22
 
23
  @font-face {
24
  font-family: "Inter";
 
19
  to inherit its spacing -- an @imported sheet loses every equal-specificity fight with this one. */
20
  @import "./styles/wave42/hop-editor.css";
21
  @import "./styles/wave42/rail-views.css";
22
+ /* ⭐ WAVE 51 base kit (W51-T01). Imported HERE and not from the component, unlike every
23
+ wave since 43: ConfirmDialog is shared by three lanes on unrelated pages, and a
24
+ per-component import would land these rules in one lazy chunk and leave the dialog
25
+ unstyled everywhere else, with tsc and the build both green. */
26
+ @import "./styles/wave51/kit.css";
27
+ /* wave 51 -- one stylesheet per lane, pre-created at the wave base so no lane edits THIS file
28
+ (a shared file is a merge collision): A grid.css, C sheet-chrome.css, E sheet-engine.css. */
29
+ @import "./styles/wave51/grid.css";
30
+ @import "./styles/wave51/sheet-chrome.css";
31
+ @import "./styles/wave51/sheet-engine.css";
32
 
33
  @font-face {
34
  font-family: "Inter";
web/src/sheet/BindingEditor.tsx CHANGED
@@ -1,4 +1,5 @@
1
- // sheet/BindingEditor.tsx β€” what a bound cell points at (wave 49, W49-T06, R4/R8/R14).
 
2
  //
3
  // ⭐⭐ R4 SAYS "THE FILTER USES THE EXACT SAME UI AS A VIEW'S FILTER", SO THIS MOUNTS
4
  // `filter-kit/FilterBuilderPanel` ITSELF. That component turned out to need NO change to run here:
@@ -12,16 +13,37 @@
12
  // filter through the same `compile_filter_tree`, so two shapes would mean two dialects and one of
13
  // them would eventually stop being tested.
14
  //
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
16
  // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.
17
 
18
- import { useEffect, useMemo, useState } from "react";
19
  import { fetchWorkspace } from "../customer-grid/apiBridge";
20
  import type { SurfaceScope } from "../customer-grid/apiBridge";
21
  import { FieldTypeIcon } from "../customer-grid/icons";
22
  import type { Field, FilterTree } from "../customer-grid/types";
23
  import { FilterBuilderPanel } from "../filter-kit";
24
  import { isNumericType } from "../filter-kit/ops";
 
25
  import { previewCell } from "./sheetApi";
26
 
27
  const AGGREGATES = [
@@ -39,6 +61,166 @@ const scopeOf = (database: string): SurfaceScope | null => {
39
  return database.startsWith("ut_") ? (database as SurfaceScope) : null;
40
  };
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  export interface BindingEditorProps {
43
  workbookId: string;
44
  addr: string;
@@ -60,12 +242,40 @@ export default function BindingEditor({
60
  const [scopeKind, setScopeKind] = useState<"view" | "filter">("view");
61
  const [viewId, setViewId] = useState<string>("");
62
  const [tree, setTree] = useState<FilterTree>({ conj: "and", nodes: [] });
63
- const [periodRef, setPeriodRef] = useState<string>("");
64
  const [fields, setFields] = useState<Field[]>([]);
65
  const [views, setViews] = useState<{ id: string; name: string }[]>([]);
66
  const [preview, setPreview] = useState<string>("");
67
  const [notice, setNotice] = useState<string>("");
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  // The field and view lists come from the SAME door the grid uses, so a cell can never offer a
70
  // column the grid does not have.
71
  useEffect(() => {
@@ -96,6 +306,12 @@ export default function BindingEditor({
96
  [fields],
97
  );
98
 
 
 
 
 
 
 
99
  /**
100
  * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*)
101
  *
@@ -128,12 +344,22 @@ export default function BindingEditor({
128
  const scope: Record<string, unknown> = scopeKind === "view"
129
  ? { view_id: viewId, view_name: views.find((v) => v.id === viewId)?.name ?? "" }
130
  : { filter: tree };
 
 
 
 
131
  const out: Record<string, unknown> = { database, aggregate: agg, scope };
132
- // R14: a period SOURCE is a `$`-anchored cell reference. The A1 resolver reads it BEFORE the
133
- // query is built, so it is an INPUT to the filter and never a post-filter.
134
- if (periodRef.trim()) out.period = { ref: periodRef.trim() };
 
 
 
 
 
135
  return out;
136
- }, [database, fn, field, scopeKind, viewId, views, tree, periodRef]);
 
137
 
138
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
139
  // which is what lets someone see whether they picked the right thing while they can still change
@@ -152,111 +378,330 @@ export default function BindingEditor({
152
  const ready = Boolean(database) && (fn === "count" || Boolean(field))
153
  && (scopeKind === "filter" || Boolean(viewId));
154
 
155
- return (
156
- <section className="sheet-binding" aria-label={`What ${addr} points at`}>
157
- <h2 className="sheet-binding-title">{`What ${addr} points at`}</h2>
 
 
 
158
 
159
- <label className="sheet-field">
160
- <span>Database</span>
161
- <select value={database} onChange={(e) => setDatabase(e.target.value)}>
162
- {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)}
163
- </select>
164
- </label>
165
 
166
- <div className="sheet-field-row">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  <label className="sheet-field">
168
- <span>Aggregate</span>
169
- <select value={fn} onChange={(e) => setFn(e.target.value)}>
170
- {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)}
171
  </select>
172
  </label>
173
- {/* Count takes no column, and offering one would suggest count(column), which skips
174
- blanks and answers a smaller number than the person meant. */}
175
- {fn !== "count" && (
176
- <div className="sheet-field sheet-field--pick">
177
- <span id="sheet-col-pick-label">Column</span>
178
- {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (R16). See the note on `shownFields`. */}
179
- <div className="cg-type-search sheet-pick-search">
180
- <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
181
- <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
182
- <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
183
- strokeLinecap="round" />
184
- </svg>
185
- <input
186
- type="text"
187
- value={fieldQuery}
188
- placeholder="Find a column…"
189
- aria-label="Find a column"
190
- onChange={(e) => setFieldQuery(e.currentTarget.value)}
191
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  </div>
193
- <div className="cg-type-list sheet-pick-list" role="listbox"
194
- aria-labelledby="sheet-col-pick-label">
195
- {shownFields.map((f) => (
196
- <button
197
- key={f.key}
198
- type="button"
199
- role="option"
200
- aria-selected={f.key === field}
201
- className={"cg-type-row" + (f.key === field ? " is-on" : "")}
202
- onClick={() => setField(f.key)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  >
204
- {/* ⭐ THE ICON COMES BEFORE THE NAME, which is owner instruction 24 and also
205
- what the Fields panel and the grid header already do. One glyph vocabulary,
206
- one source: `iconShapes.ts::TYPE_SHAPES`. */}
207
- <FieldTypeIcon type={f.type} title={f.type} />
208
- <span className="cg-type-label">{f.label}</span>
209
- </button>
210
- ))}
211
- </div>
212
- {/* β›” AN EMPTY LIST SAYS WHY (R16), because a blank box reads as a broken picker and
213
- the two causes need different acts from the reader. */}
214
- {shownFields.length === 0 && (
215
- <p className="sheet-pick-empty">
216
- {numericFields.length === 0
217
- ? "This database has no number column to total."
218
- : "No column matches that search."}
219
- </p>
 
220
  )}
221
  </div>
222
- )}
223
- </div>
224
 
225
- <fieldset className="sheet-scope">
226
- <legend>Rows to include</legend>
227
- <label className="sheet-radio">
228
- <input type="radio" checked={scopeKind === "view"}
229
- onChange={() => setScopeKind("view")} />
230
- <span>A saved view</span>
231
- </label>
232
- {scopeKind === "view" && (
233
- <select value={viewId} onChange={(e) => setViewId(e.target.value)}>
234
- <option value="">Choose a view</option>
235
- {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
236
- </select>
237
- )}
238
- <label className="sheet-radio">
239
- <input type="radio" checked={scopeKind === "filter"}
240
- onChange={() => setScopeKind("filter")} />
241
- <span>A filter I build here</span>
242
- </label>
243
- {scopeKind === "filter" && (
244
- <FilterBuilderPanel fields={fields} filters={tree} onChange={setTree} />
245
- )}
246
- </fieldset>
247
-
248
- <label className="sheet-field">
249
- <span>Period from a cell</span>
250
- <input
251
- type="text"
252
- value={periodRef}
253
- onChange={(e) => setPeriodRef(e.target.value)}
254
- placeholder="$B$1"
255
- />
256
- </label>
257
-
258
- {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
259
- {notice && <p className="sheet-notice" role="alert">{notice}</p>}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
 
261
  <div className="sheet-binding-actions">
262
  <button type="button" className="sheet-action" onClick={runPreview} disabled={!ready}>
 
1
+ // sheet/BindingEditor.tsx β€” what a bound cell points at (wave 49, W49-T06, R4/R8/R14;
2
+ // wave 51, W51-T12, R9/R10/R11).
3
  //
4
  // ⭐⭐ R4 SAYS "THE FILTER USES THE EXACT SAME UI AS A VIEW'S FILTER", SO THIS MOUNTS
5
  // `filter-kit/FilterBuilderPanel` ITSELF. That component turned out to need NO change to run here:
 
13
  // filter through the same `compile_filter_tree`, so two shapes would mean two dialects and one of
14
  // them would eventually stop being tested.
15
  //
16
+ // β›”β›” W51-T12 - THE ROOT NODE IS `.sheet-binding-panel` AND NOT `.sheet-binding`, AND THAT ONE
17
+ // CLASS IS THE WHOLE TICKET. `styles/wave49/sheet.css` declares `.sheet-binding` as
18
+ // `position: fixed; z-index: var(--cg-z-drawer)` - an OVERLAY, floating over the canvas it
19
+ // describes. W50-QA-1 is what that costs: an absolutely positioned panel over the map made every
20
+ // pin beneath it unclickable, and no z-index repairs document-order stacking. The design contract's
21
+ // clause is that the right-side panel is a real COLUMN and the content beside it SHRINKS.
22
+ // `.sheet-page` is already a flex row (`align-items: stretch`) and this component already renders
23
+ // as one of its direct children, so a root of `flex: 0 0 380px` narrows `.sheet-body` - and that is
24
+ // observable as a MEASUREMENT (the grid's own width with the panel open versus closed), which is
25
+ // the one thing a screenshot cannot tell apart from an overlay.
26
+ //
27
+ // ⚠ THE NEW CLASS IS DELIBERATE, NOT COSMETIC. `wave49/sheet.css` loads from inside SheetPage's
28
+ // LAZY chunk and therefore BEATS `styles/wave51/sheet-chrome.css` (imported eagerly by index.css)
29
+ // at equal specificity, so an override of `.sheet-binding`'s `position` written in this lane's
30
+ // sheet would lose the cascade and change nothing on screen
31
+ // ([[a-lazy-chunk-stylesheet-beats-an-eager-one]]). A name nothing else declares has no fight to
32
+ // lose. The INNER classes (`.sheet-field`, `.sheet-scope`, `.sheet-radio`, `.sheet-binding-title`,
33
+ // `.sheet-binding-actions`) are all top-level selectors rather than descendants of `.sheet-binding`,
34
+ // so every one of them keeps its shipped paint.
35
+ //
36
  // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
37
  // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.
38
 
39
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
40
  import { fetchWorkspace } from "../customer-grid/apiBridge";
41
  import type { SurfaceScope } from "../customer-grid/apiBridge";
42
  import { FieldTypeIcon } from "../customer-grid/icons";
43
  import type { Field, FilterTree } from "../customer-grid/types";
44
  import { FilterBuilderPanel } from "../filter-kit";
45
  import { isNumericType } from "../filter-kit/ops";
46
+ import { useEscapeClose } from "../ui/useEscapeClose";
47
  import { previewCell } from "./sheetApi";
48
 
49
  const AGGREGATES = [
 
61
  return database.startsWith("ut_") ? (database as SurfaceScope) : null;
62
  };
63
 
64
+ // ══ THE PERIOD (R9) ═══════════════════════════════════════════════════════════════════════════
65
+ //
66
+ // β›”β›” CONTRACT C2 SPELLS THIS ON THE WIRE AND THE UI DOES NOT GET A VOTE:
67
+ // `period: {unit: "month"|"quarter"|"year", start: "YYYY-MM", locked: boolean, ref?: A1}`. The
68
+ // unit values are LOWERCASE on the wire even though the picker reads Month / Quarter / Year, and
69
+ // `start` is a MONTH string for every unit.
70
+ //
71
+ // ⭐ `start` IS THE PERIOD'S FIRST MONTH, and that is the decision the ticket leaves implicit.
72
+ // `unit` and `start` have to jointly name exactly one period, so Q3 2026 is `2026-07` and the year
73
+ // 2026 is `2026-01`. Stamping today's month under a quarter unit would agree with nothing: the
74
+ // server compiler reads the pair, and two readings of `2026-08` under `quarter` (August, or Q3)
75
+ // are a silent disagreement that no screen shows.
76
+
77
+ export type PeriodUnit = "month" | "quarter" | "year";
78
+
79
+ export interface PeriodBinding {
80
+ unit: PeriodUnit;
81
+ start: string;
82
+ locked: boolean;
83
+ ref?: string;
84
+ }
85
+
86
+ export const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [
87
+ { unit: "month", label: "Month" },
88
+ { unit: "quarter", label: "Quarter" },
89
+ { unit: "year", label: "Year" },
90
+ ];
91
+
92
+ const MONTH_NAMES = [
93
+ "January", "February", "March", "April", "May", "June",
94
+ "July", "August", "September", "October", "November", "December",
95
+ ];
96
+
97
+ /** How many months one step of a unit covers. The only place that arithmetic is stated. */
98
+ const MONTHS_PER_UNIT: Record<PeriodUnit, number> = { month: 1, quarter: 3, year: 12 };
99
+
100
+ /** The noun a sentence uses for one step. Sentence case, and no dash anywhere near it. */
101
+ const UNIT_NOUN: Record<PeriodUnit, string> = {
102
+ month: "month", quarter: "quarter", year: "year",
103
+ };
104
+
105
+ const pad2 = (n: number) => String(n).padStart(2, "0");
106
+
107
+ /** `{year, month}` out of a `"YYYY-MM"`; today when the string is absent or malformed. */
108
+ function splitYm(ym: string): { y: number; m: number } {
109
+ const hit = /^(\d{4})-(\d{2})$/.exec(ym ?? "");
110
+ if (!hit) {
111
+ const now = new Date();
112
+ return { y: now.getFullYear(), m: now.getMonth() + 1 };
113
+ }
114
+ const m = Number(hit[2]);
115
+ return { y: Number(hit[1]), m: m >= 1 && m <= 12 ? m : 1 };
116
+ }
117
+
118
+ const joinYm = (y: number, m: number) => `${y}-${pad2(m)}`;
119
+
120
+ /** THE PERIOD'S FIRST MONTH, which is what `start` means. See the block above. */
121
+ export function normalizePeriodStart(unit: PeriodUnit, ym: string): string {
122
+ const { y, m } = splitYm(ym);
123
+ if (unit === "year") return joinYm(y, 1);
124
+ if (unit === "quarter") return joinYm(y, 1 + 3 * Math.floor((m - 1) / 3));
125
+ return joinYm(y, m);
126
+ }
127
+
128
+ /** Move a start by whole periods. Negative steps go back; this is also the drag rule's maths. */
129
+ export function shiftPeriodStart(unit: PeriodUnit, ym: string, steps: number): string {
130
+ const { y, m } = splitYm(normalizePeriodStart(unit, ym));
131
+ const total = y * 12 + (m - 1) + steps * MONTHS_PER_UNIT[unit];
132
+ return joinYm(Math.floor(total / 12), (total % 12) + 1);
133
+ }
134
+
135
+ /** The period a person reads: "July 2026", "Q3 2026", "2026". */
136
+ export function periodLabel(unit: PeriodUnit, ym: string): string {
137
+ const { y, m } = splitYm(normalizePeriodStart(unit, ym));
138
+ if (unit === "year") return String(y);
139
+ if (unit === "quarter") return `Q${Math.floor((m - 1) / 3) + 1} ${y}`;
140
+ return `${MONTH_NAMES[m - 1]} ${y}`;
141
+ }
142
+
143
+ const todayYm = () => {
144
+ const now = new Date();
145
+ return joinYm(now.getFullYear(), now.getMonth() + 1);
146
+ };
147
+
148
+ /**
149
+ * ⭐⭐ W51-T12 - THE READ-SIDE MIGRATION, AND IT IS A NAMED FUNCTION SO A GATE CAN PIN IT.
150
+ *
151
+ * Before this ticket a binding's period was `{ref}` and nothing else: a raw typed A1 string, with
152
+ * no unit, no start and no lock. Under R9 an UNLOCKED period SHIFTS when the cell is copied across
153
+ * columns, so reading an old binding as unlocked would change what a shipped cell answers the first
154
+ * time somebody dragged it - a value moving on its own, with no edit and no warning.
155
+ *
156
+ * β›” SO A `ref`-ONLY PERIOD BECOMES LOCKED. `unit` and `start` are non-optional in C2 and have to
157
+ * carry something, but on a ref-driven period they are INERT: the referenced cell decides the
158
+ * period, and `locked: true` is what stops the drag rule from touching it either way.
159
+ */
160
+ export function migratePeriod(raw: unknown): PeriodBinding | null {
161
+ if (!raw || typeof raw !== "object") return null;
162
+ const p = raw as Record<string, unknown>;
163
+ const ref = typeof p.ref === "string" && p.ref.trim() ? p.ref.trim() : "";
164
+ const declared = PERIOD_UNITS.some((u) => u.unit === p.unit);
165
+ if (!declared) {
166
+ // The legacy shape. Nothing shifts by surprise: it reads back LOCKED.
167
+ if (!ref) return null;
168
+ return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref };
169
+ }
170
+ const unit = p.unit as PeriodUnit;
171
+ const start = normalizePeriodStart(
172
+ unit, typeof p.start === "string" ? p.start : todayYm(),
173
+ );
174
+ const locked = p.locked === true;
175
+ return ref ? { unit, start, locked, ref } : { unit, start, locked };
176
+ }
177
+
178
+ // ══ THE DRAG RULES (R10) ══════════════════════════════════════════════════════════════════════
179
+ //
180
+ // TWO DIRECTIONAL SETTINGS, and C2 spells them `onDrag: {across: "period"|"none",
181
+ // down: {field: key}|"none"}`. Defaults: across = period, down = none.
182
+
183
+ export type DragAcross = "period" | "none";
184
+
185
+ export interface OnDragBinding {
186
+ across: DragAcross;
187
+ down: { field: string } | "none";
188
+ }
189
+
190
+ /**
191
+ * WHICH COLUMNS "next value of" CAN WALK, and it is NOT `isNumericType`.
192
+ *
193
+ * β›” R10 names a SINGLE-SELECT or a LINK, because those are the only two field kinds with an
194
+ * ORDER to advance through: a select has its declared option order, a link has the linked table's
195
+ * view order. `multiselect` is excluded by name and `multi` is excluded again by flag, because a
196
+ * cell holding a SET has no next value - it has several, and picking one of them would be this
197
+ * component inventing an answer.
198
+ */
199
+ export function isDragDownField(f: Field): boolean {
200
+ if (f.multi) return false;
201
+ return f.type === "select" || f.type === "status" || f.type === "link";
202
+ }
203
+
204
+ /** The saved `onDrag`, defaulted. `down` is carried as a field key, empty meaning nothing. */
205
+ export function readOnDrag(raw: unknown): { across: DragAcross; down: string } {
206
+ const d = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
207
+ const across: DragAcross = d.across === "none" ? "none" : "period";
208
+ const down = d.down;
209
+ if (down && typeof down === "object") {
210
+ const key = (down as Record<string, unknown>).field;
211
+ if (typeof key === "string" && key) return { across, down: key };
212
+ }
213
+ return { across, down: "" };
214
+ }
215
+
216
+ /** `scope.adoptedFrom` (R11): the view was purged and its filter was copied into this cell. */
217
+ function adoptedFromOf(initial: Record<string, unknown> | null | undefined): string {
218
+ const scope = initial?.scope as Record<string, unknown> | undefined;
219
+ const adopted = scope?.adoptedFrom as Record<string, unknown> | undefined;
220
+ const name = adopted?.name;
221
+ return typeof name === "string" ? name : "";
222
+ }
223
+
224
  export interface BindingEditorProps {
225
  workbookId: string;
226
  addr: string;
 
242
  const [scopeKind, setScopeKind] = useState<"view" | "filter">("view");
243
  const [viewId, setViewId] = useState<string>("");
244
  const [tree, setTree] = useState<FilterTree>({ conj: "and", nodes: [] });
 
245
  const [fields, setFields] = useState<Field[]>([]);
246
  const [views, setViews] = useState<{ id: string; name: string }[]>([]);
247
  const [preview, setPreview] = useState<string>("");
248
  const [notice, setNotice] = useState<string>("");
249
 
250
+ // ⚠ THE MIGRATION RUNS ONCE, AT MOUNT, and its result seeds the controls. Running it on every
251
+ // render would re-read `initial` after the person had already changed a control, which is how an
252
+ // editor forgets an edit the moment its parent re-renders for an unrelated reason.
253
+ const migrated = useState(() => migratePeriod(initial?.period))[0];
254
+ const savedDrag = useState(() => readOnDrag(initial?.onDrag))[0];
255
+
256
+ const [unit, setUnit] = useState<PeriodUnit>(migrated?.unit ?? "month");
257
+ const [start, setStart] = useState<string>(
258
+ migrated?.start ?? normalizePeriodStart("month", todayYm()),
259
+ );
260
+ const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false);
261
+ const [periodRef, setPeriodRef] = useState<string>(migrated?.ref ?? "");
262
+ // "Use a cell" is a LINK that REVEALS the A1 input (R9). The input was the whole period control
263
+ // before this ticket and it is not deleted, only demoted to the thing behind that link.
264
+ const [refOpen, setRefOpen] = useState<boolean>(Boolean(migrated?.ref));
265
+ const [across, setAcross] = useState<DragAcross>(savedDrag.across);
266
+ const [downField, setDownField] = useState<string>(savedDrag.down);
267
+
268
+ const adoptedFrom = adoptedFromOf(initial);
269
+
270
+ // ⭐ ESCAPE CLOSES THE PANEL, through the base kit's ONE arbiter (C8) rather than a listener of
271
+ // this component's own. `cancelEditFirst` stays FALSE: the done-when says the panel closes on
272
+ // Escape, and opting in would make the FIRST Escape do nothing whenever focus sat in one of the
273
+ // text inputs this panel is full of.
274
+ const panelRef = useRef<HTMLElement | null>(null);
275
+ const onEscape = useCallback(() => onCancel(), [onCancel]);
276
+ const escapeContainer = useCallback(() => panelRef.current, []);
277
+ useEscapeClose(true, onEscape, { container: escapeContainer });
278
+
279
  // The field and view lists come from the SAME door the grid uses, so a cell can never offer a
280
  // column the grid does not have.
281
  useEffect(() => {
 
306
  [fields],
307
  );
308
 
309
+ /** R10's list, and a DIFFERENT predicate from the one above. See `isDragDownField`. */
310
+ const dragDownFields = useMemo(
311
+ () => fields.filter(isDragDownField),
312
+ [fields],
313
+ );
314
+
315
  /**
316
  * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*)
317
  *
 
344
  const scope: Record<string, unknown> = scopeKind === "view"
345
  ? { view_id: viewId, view_name: views.find((v) => v.id === viewId)?.name ?? "" }
346
  : { filter: tree };
347
+ // R11: a filter ADOPTED from a purged view keeps saying so. The sentence in the panel is the
348
+ // only trace of where that filter came from, and re-saving the cell must not erase it.
349
+ const adopted = (initial?.scope as Record<string, unknown> | undefined)?.adoptedFrom;
350
+ if (scopeKind === "filter" && adopted) scope.adoptedFrom = adopted;
351
  const out: Record<string, unknown> = { database, aggregate: agg, scope };
352
+ // C2's period, spelled the contract's way. R14: a period SOURCE is a `$`-anchored cell
353
+ // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
354
+ // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
355
+ // replacing them, because the pair still names what the cell falls back to.
356
+ const period: Record<string, unknown> = { unit, start, locked };
357
+ if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
358
+ out.period = period;
359
+ out.onDrag = { across, down: downField ? { field: downField } : "none" };
360
  return out;
361
+ }, [database, fn, field, scopeKind, viewId, views, tree, initial,
362
+ unit, start, locked, refOpen, periodRef, across, downField]);
363
 
364
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
365
  // which is what lets someone see whether they picked the right thing while they can still change
 
378
  const ready = Boolean(database) && (fn === "count" || Boolean(field))
379
  && (scopeKind === "filter" || Boolean(viewId));
380
 
381
+ const { y: startYear, m: startMonth } = splitYm(start);
382
+ const thisYear = new Date().getFullYear();
383
+ const years: number[] = [];
384
+ for (let y = thisYear - 6; y <= thisYear + 1; y += 1) years.push(y);
385
+ if (!years.includes(startYear)) years.push(startYear);
386
+ years.sort((a, b) => a - b);
387
 
388
+ const setYear = (y: number) => setStart(normalizePeriodStart(unit, joinYm(y, startMonth)));
389
+ const setMonthOfYear = (m: number) => setStart(normalizePeriodStart(unit, joinYm(startYear, m)));
 
 
 
 
390
 
391
+ const downLabel = dragDownFields.find((f) => f.key === downField)?.label ?? "";
392
+
393
+ return (
394
+ <section
395
+ className="sheet-binding-panel"
396
+ ref={panelRef}
397
+ aria-label={`What ${addr} points at`}
398
+ >
399
+ <header className="sheet-binding-head">
400
+ <h2 className="sheet-binding-title">{`What ${addr} points at`}</h2>
401
+ <button
402
+ type="button"
403
+ className="sheet-binding-close"
404
+ onClick={onCancel}
405
+ aria-label={`Close what ${addr} points at`}
406
+ title="Close"
407
+ >
408
+ <svg viewBox="0 0 16 16" aria-hidden="true" width="13" height="13" fill="none">
409
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.4"
410
+ strokeLinecap="round" />
411
+ </svg>
412
+ </button>
413
+ </header>
414
+
415
+ {/* β›” THE SCROLLER IS THIS WRAPPER, NOT THE PANEL. A 380px column holding the whole filter
416
+ builder is taller than the page, and a panel that scrolls as a whole pushes Save below
417
+ the fold with nothing on screen saying it is there. */}
418
+ <div className="sheet-binding-scroll">
419
  <label className="sheet-field">
420
+ <span>Database</span>
421
+ <select value={database} onChange={(e) => setDatabase(e.target.value)}>
422
+ {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)}
423
  </select>
424
  </label>
425
+
426
+ <div className="sheet-field-row">
427
+ <label className="sheet-field">
428
+ <span>Aggregate</span>
429
+ <select value={fn} onChange={(e) => setFn(e.target.value)}>
430
+ {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)}
431
+ </select>
432
+ </label>
433
+ {/* Count takes no column, and offering one would suggest count(column), which skips
434
+ blanks and answers a smaller number than the person meant. */}
435
+ {fn !== "count" && (
436
+ <div className="sheet-field sheet-field--pick">
437
+ <span id="sheet-col-pick-label">Column</span>
438
+ {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (R16). See the note on `shownFields`. */}
439
+ <div className="cg-type-search sheet-pick-search">
440
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
441
+ <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
442
+ <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
443
+ strokeLinecap="round" />
444
+ </svg>
445
+ <input
446
+ type="text"
447
+ value={fieldQuery}
448
+ placeholder="Find a column…"
449
+ aria-label="Find a column"
450
+ onChange={(e) => setFieldQuery(e.currentTarget.value)}
451
+ />
452
+ </div>
453
+ <div className="cg-type-list sheet-pick-list" role="listbox"
454
+ aria-labelledby="sheet-col-pick-label">
455
+ {shownFields.map((f) => (
456
+ <button
457
+ key={f.key}
458
+ type="button"
459
+ role="option"
460
+ aria-selected={f.key === field}
461
+ className={"cg-type-row" + (f.key === field ? " is-on" : "")}
462
+ onClick={() => setField(f.key)}
463
+ >
464
+ {/* ⭐ THE ICON COMES BEFORE THE NAME, which is owner instruction 24 and also
465
+ what the Fields panel and the grid header already do. One glyph vocabulary,
466
+ one source: `iconShapes.ts::TYPE_SHAPES`. */}
467
+ <FieldTypeIcon type={f.type} title={f.type} />
468
+ <span className="cg-type-label">{f.label}</span>
469
+ </button>
470
+ ))}
471
+ </div>
472
+ {/* β›” AN EMPTY LIST SAYS WHY (R16), because a blank box reads as a broken picker and
473
+ the two causes need different acts from the reader. */}
474
+ {shownFields.length === 0 && (
475
+ <p className="sheet-pick-empty">
476
+ {numericFields.length === 0
477
+ ? "This database has no number column to total."
478
+ : "No column matches that search."}
479
+ </p>
480
+ )}
481
  </div>
482
+ )}
483
+ </div>
484
+
485
+ <fieldset className="sheet-scope">
486
+ <legend>Rows to include</legend>
487
+ <label className="sheet-radio">
488
+ <input type="radio" checked={scopeKind === "view"}
489
+ onChange={() => setScopeKind("view")} />
490
+ <span>A saved view</span>
491
+ </label>
492
+ {scopeKind === "view" && (
493
+ <select value={viewId} onChange={(e) => setViewId(e.target.value)}>
494
+ <option value="">Choose a view</option>
495
+ {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
496
+ </select>
497
+ )}
498
+ <label className="sheet-radio">
499
+ <input type="radio" checked={scopeKind === "filter"}
500
+ onChange={() => setScopeKind("filter")} />
501
+ <span>A filter I build here</span>
502
+ </label>
503
+ {scopeKind === "filter" && (
504
+ <FilterBuilderPanel fields={fields} filters={tree} onChange={setTree} />
505
+ )}
506
+ </fieldset>
507
+
508
+ {/* ══ R9: THE PERIOD ══════════════════════════════════════════════════════════════════ */}
509
+ <fieldset className="sheet-scope sheet-period">
510
+ <legend>Period</legend>
511
+
512
+ <label className="sheet-field">
513
+ <span>Unit</span>
514
+ <select
515
+ value={unit}
516
+ aria-label="Period unit"
517
+ onChange={(e) => {
518
+ const next = e.target.value as PeriodUnit;
519
+ setUnit(next);
520
+ // Re-seat the start on the new unit's first month, or the pair stops naming one
521
+ // period: `2026-08` under `quarter` is not a quarter anybody can compile.
522
+ setStart(normalizePeriodStart(next, start));
523
+ }}
524
+ >
525
+ {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
526
+ </select>
527
+ </label>
528
+
529
+ <div className="sheet-field-row">
530
+ <label className="sheet-field">
531
+ <span>Year</span>
532
+ <select
533
+ value={String(startYear)}
534
+ aria-label="Period year"
535
+ onChange={(e) => setYear(Number(e.target.value))}
536
+ >
537
+ {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
538
+ </select>
539
+ </label>
540
+ {unit === "month" && (
541
+ <label className="sheet-field">
542
+ <span>Month</span>
543
+ <select
544
+ value={String(startMonth)}
545
+ aria-label="Period month"
546
+ onChange={(e) => setMonthOfYear(Number(e.target.value))}
547
  >
548
+ {MONTH_NAMES.map((name, i) => (
549
+ <option key={name} value={String(i + 1)}>{name}</option>
550
+ ))}
551
+ </select>
552
+ </label>
553
+ )}
554
+ {unit === "quarter" && (
555
+ <label className="sheet-field">
556
+ <span>Quarter</span>
557
+ <select
558
+ value={String(Math.floor((startMonth - 1) / 3) + 1)}
559
+ aria-label="Period quarter"
560
+ onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
561
+ >
562
+ {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
563
+ </select>
564
+ </label>
565
  )}
566
  </div>
 
 
567
 
568
+ {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This
569
+ never stamps today's month under a quarter or a year. */}
570
+ <div className="sheet-period-quick">
571
+ <button
572
+ type="button"
573
+ className="sheet-period-pick"
574
+ onClick={() => setStart(normalizePeriodStart(unit, todayYm()))}
575
+ >
576
+ This {UNIT_NOUN[unit]}
577
+ </button>
578
+ <button
579
+ type="button"
580
+ className="sheet-period-pick"
581
+ onClick={() => setStart(shiftPeriodStart(unit, todayYm(), -1))}
582
+ >
583
+ Last {UNIT_NOUN[unit]}
584
+ </button>
585
+ </div>
586
+
587
+ {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
588
+ sentence under it says what each one costs when the cell is copied. */}
589
+ <div className="sheet-period-lock">
590
+ <button
591
+ type="button"
592
+ role="switch"
593
+ aria-checked={locked}
594
+ className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
595
+ onClick={() => setLocked((v) => !v)}
596
+ >
597
+ <span className="sheet-lock-dot" aria-hidden />
598
+ <span>Lock this period</span>
599
+ </button>
600
+ <p className="sheet-period-note">
601
+ {locked
602
+ ? "Locked, so any copy of this cell keeps this period."
603
+ : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} `
604
+ + "per column, and copying up or down keeps it."}
605
+ </p>
606
+ </div>
607
+
608
+ {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
609
+ picker, so the ordinary reader never meets a cell reference and the person who wants
610
+ one is one click away from it. */}
611
+ {!refOpen && (
612
+ <button
613
+ type="button"
614
+ className="sheet-period-link"
615
+ onClick={() => setRefOpen(true)}
616
+ >
617
+ Use a cell
618
+ </button>
619
+ )}
620
+ {refOpen && (
621
+ <label className="sheet-field">
622
+ <span>Period from a cell</span>
623
+ <input
624
+ type="text"
625
+ value={periodRef}
626
+ onChange={(e) => setPeriodRef(e.target.value)}
627
+ placeholder="$B$1"
628
+ />
629
+ </label>
630
+ )}
631
+ </fieldset>
632
+
633
+ {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
634
+ <fieldset className="sheet-scope sheet-drag">
635
+ <legend>When dragged</legend>
636
+
637
+ <label className="sheet-field">
638
+ <span>Across</span>
639
+ <select
640
+ value={across}
641
+ aria-label="When dragged across columns"
642
+ onChange={(e) => setAcross(e.target.value === "none" ? "none" : "period")}
643
+ >
644
+ <option value="period">Period</option>
645
+ <option value="none">Nothing</option>
646
+ </select>
647
+ </label>
648
+
649
+ <label className="sheet-field">
650
+ <span>Down</span>
651
+ <select
652
+ value={downField}
653
+ aria-label="When dragged down rows"
654
+ onChange={(e) => setDownField(e.target.value)}
655
+ >
656
+ <option value="">Nothing</option>
657
+ {dragDownFields.map((f) => (
658
+ <option key={f.key} value={f.key}>{`Next value of ${f.label}`}</option>
659
+ ))}
660
+ </select>
661
+ </label>
662
+
663
+ {dragDownFields.length === 0 && (
664
+ <p className="sheet-period-note">
665
+ This database has no single select or link column to walk, so dragging down repeats
666
+ the same rows.
667
+ </p>
668
+ )}
669
+ </fieldset>
670
+
671
+ {/* ══ WHAT THIS CELL POINTS AT, IN SENTENCES ══════════════════════════════════════════
672
+ The panel's whole reason for being a panel: the period, the lock, the two drag rules
673
+ and, when the view behind it was purged, where its filter came from. */}
674
+ <div className="sheet-binding-summary">
675
+ <p className="sheet-binding-line">
676
+ {refOpen && periodRef.trim()
677
+ ? `Period: taken from cell ${periodRef.trim()}.`
678
+ : `Period: ${periodLabel(unit, start)}.`}
679
+ </p>
680
+ <p className="sheet-binding-line">
681
+ {locked
682
+ ? "The period is locked, so a copy keeps it."
683
+ : `The period is not locked, so it shifts by one ${UNIT_NOUN[unit]} per column.`}
684
+ </p>
685
+ <p className="sheet-binding-line">
686
+ {across === "period"
687
+ ? `Dragged across: the period moves forward one ${UNIT_NOUN[unit]} per column.`
688
+ : "Dragged across: nothing changes."}
689
+ </p>
690
+ <p className="sheet-binding-line">
691
+ {downField
692
+ ? `Dragged down: the next value of ${downLabel}.`
693
+ : "Dragged down: nothing changes."}
694
+ </p>
695
+ {adoptedFrom && (
696
+ <p className="sheet-binding-line sheet-binding-adopted">
697
+ {`Filter adopted from the deleted view ${adoptedFrom}`}
698
+ </p>
699
+ )}
700
+ </div>
701
+
702
+ {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
703
+ {notice && <p className="sheet-notice" role="alert">{notice}</p>}
704
+ </div>
705
 
706
  <div className="sheet-binding-actions">
707
  <button type="button" className="sheet-action" onClick={runPreview} disabled={!ready}>
web/src/sheet/DrillModal.tsx CHANGED
@@ -17,8 +17,9 @@
17
  // the CELL and it is marked on the grid; repeating it here would be answering a question the person
18
  // did not ask, at the moment they asked a different one.
19
 
20
- import { Suspense, lazy, useEffect, useState } from "react";
21
  import type { SurfaceScope } from "../customer-grid/apiBridge";
 
22
  import { drillCell } from "./sheetApi";
23
  import type { CellDrill } from "./sheetApi";
24
 
@@ -65,6 +66,27 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
65
  const [drill, setDrill] = useState<CellDrill | null>(null);
66
  const [error, setError] = useState("");
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  useEffect(() => {
69
  let live = true;
70
  (async () => {
@@ -85,7 +107,7 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
85
  // A refusal is a plain sentence naming the cause and the subject, per the design contract.
86
  // It is NOT rendered inside the popup: the popup is a grid of rows, and an error is not a row.
87
  return (
88
- <div className="sheet-drill-error" role="alert">
89
  <p>{error}</p>
90
  <button type="button" className="sheet-action" onClick={onClose}>
91
  Close
@@ -96,12 +118,11 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
96
 
97
  if (!drill) return null;
98
 
99
- const scope = scopeOf(drill.database);
100
  if (!scope) {
101
  // Named rather than swallowed: a database the popup cannot address is a real gap, and a blank
102
  // popup would look like "no rows" - the wrong answer, delivered convincingly.
103
  return (
104
- <div className="sheet-drill-error" role="alert">
105
  <p>{`Rows for ${drill.database} cannot be opened from a cell yet.`}</p>
106
  <button type="button" className="sheet-action" onClick={onClose}>
107
  Close
 
17
  // the CELL and it is marked on the grid; repeating it here would be answering a question the person
18
  // did not ask, at the moment they asked a different one.
19
 
20
+ import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
21
  import type { SurfaceScope } from "../customer-grid/apiBridge";
22
+ import { useEscapeClose } from "../ui/useEscapeClose";
23
  import { drillCell } from "./sheetApi";
24
  import type { CellDrill } from "./sheetApi";
25
 
 
66
  const [drill, setDrill] = useState<CellDrill | null>(null);
67
  const [error, setError] = useState("");
68
 
69
+ /**
70
+ * ⭐⭐ W51-T12 - THE REFUSAL CARDS CLOSE ON ESCAPE TOO, AND THAT WAS THE HOLE.
71
+ *
72
+ * The SUCCESS path already closes on Escape and needs nothing from this component:
73
+ * `CustomerGrid.tsx::LinkGridModal` calls `useOverlayLayer`, which calls
74
+ * `useEscapeClose(true, onEscape, ...)` (`customer-grid/OverlaySurface.tsx`), so the popup joined
75
+ * the base kit's topmost-wins stack in W51-T01. Verified on this branch rather than assumed.
76
+ *
77
+ * β›” BUT THE TWO ERROR BRANCHES BELOW RENDER OUTSIDE `LinkGridModal` - a bare `.sheet-drill-error`
78
+ * card with its own Close button and nothing else. The overlay stack never hears about them, so
79
+ * before this a reader who drilled into a database the popup cannot address got a card that
80
+ * Escape did nothing to. The claim is registered only while such a card is on screen, so the
81
+ * success path keeps exactly one claimant and the stack is never double-pushed.
82
+ */
83
+ const cardRef = useRef<HTMLDivElement | null>(null);
84
+ const scope = drill ? scopeOf(drill.database) : null;
85
+ const showingCard = Boolean(error) || Boolean(drill && !scope);
86
+ const onEscape = useCallback(() => onClose(), [onClose]);
87
+ const escapeContainer = useCallback(() => cardRef.current as HTMLElement | null, []);
88
+ useEscapeClose(showingCard, onEscape, { container: escapeContainer });
89
+
90
  useEffect(() => {
91
  let live = true;
92
  (async () => {
 
107
  // A refusal is a plain sentence naming the cause and the subject, per the design contract.
108
  // It is NOT rendered inside the popup: the popup is a grid of rows, and an error is not a row.
109
  return (
110
+ <div className="sheet-drill-error" role="alert" ref={cardRef}>
111
  <p>{error}</p>
112
  <button type="button" className="sheet-action" onClick={onClose}>
113
  Close
 
118
 
119
  if (!drill) return null;
120
 
 
121
  if (!scope) {
122
  // Named rather than swallowed: a database the popup cannot address is a real gap, and a blank
123
  // popup would look like "no rows" - the wrong answer, delivered convincingly.
124
  return (
125
+ <div className="sheet-drill-error" role="alert" ref={cardRef}>
126
  <p>{`Rows for ${drill.database} cannot be opened from a cell yet.`}</p>
127
  <button type="button" className="sheet-action" onClick={onClose}>
128
  Close
web/src/sheet/FormulaBar.tsx CHANGED
@@ -266,6 +266,20 @@ export default function FormulaBar({
266
  }
267
  }, [accept, active, commit, matches, open, text]);
268
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  const goToAddr = useCallback(() => {
270
  const next = withinGrid(addrDraft);
271
  if (!next) {
@@ -292,6 +306,50 @@ export default function FormulaBar({
292
  />
293
  </label>
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  <span className="sheet-fx-mark" aria-hidden>
296
  <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
297
  <path
 
266
  }
267
  }, [accept, active, commit, matches, open, text]);
268
 
269
+ /**
270
+ * ⭐ W51-T08 β€” CANCEL IS THE ESCAPE KEY, CONFIRM IS THE ENTER KEY, AND NEITHER IS NEW BEHAVIOUR.
271
+ * The two controls drive the handlers `onKeyDown` already runs, so the bar keeps exactly one
272
+ * notion of "revert" and one notion of "commit". A second code path here is how a button and a
273
+ * keystroke end up disagreeing about what a half typed formula meant.
274
+ */
275
+ const cancel = useCallback(() => {
276
+ setDraft(text);
277
+ setOpen(false);
278
+ }, [text]);
279
+
280
+ /** True while there is nothing to confirm or revert, so both controls read as unavailable. */
281
+ const idle = disabled || !addr || bound;
282
+
283
  const goToAddr = useCallback(() => {
284
  const next = withinGrid(addrDraft);
285
  if (!next) {
 
306
  />
307
  </label>
308
 
309
+ {/* ⭐⭐ W51-T08 β€” CANCEL AND CONFIRM, IN EXCEL'S OWN PLACE: after the name box and before the
310
+ `fx` mark. `onMouseDown` preventing default is the same reason the suggestion rows do it,
311
+ the input's blur fires FIRST and would move the caret out from under the click.
312
+ ⚠ CANCEL IS NOT DESTRUCTIVE INK. It reverts an edit in progress; it deletes nothing, so
313
+ it carries the same quiet muted ink as every other glyph in this row (DESIGN.md Β§3). */}
314
+ <button
315
+ type="button"
316
+ className="sheet-fx-btn"
317
+ aria-label="Cancel this edit"
318
+ title="Cancel this edit"
319
+ disabled={idle}
320
+ onMouseDown={(e) => e.preventDefault()}
321
+ onClick={cancel}
322
+ >
323
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
324
+ <path
325
+ d="M4.6 4.6l6.8 6.8M11.4 4.6l-6.8 6.8"
326
+ stroke="currentColor"
327
+ strokeWidth="1.3"
328
+ strokeLinecap="round"
329
+ />
330
+ </svg>
331
+ </button>
332
+
333
+ <button
334
+ type="button"
335
+ className="sheet-fx-btn sheet-fx-btn--ok"
336
+ aria-label="Confirm this edit"
337
+ title="Confirm this edit"
338
+ disabled={idle}
339
+ onMouseDown={(e) => e.preventDefault()}
340
+ onClick={commit}
341
+ >
342
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
343
+ <path
344
+ d="M3.4 8.4l3.2 3.2L12.6 5"
345
+ stroke="currentColor"
346
+ strokeWidth="1.3"
347
+ strokeLinecap="round"
348
+ strokeLinejoin="round"
349
+ />
350
+ </svg>
351
+ </button>
352
+
353
  <span className="sheet-fx-mark" aria-hidden>
354
  <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
355
  <path
web/src/sheet/ImportDialog.tsx ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // sheet/ImportDialog.tsx β€” W51-T13 (owner instruction 7, ruling R1, contracts C4 and C8).
3
+ //
4
+ // THE IMPORT DOOR. One .xlsx goes in, the server reads it with openpyxl, and this dialog says what
5
+ // is happening while it does: Reading, Cells, Formats, Recalculating, a bar, and then the one line
6
+ // that says whether the import is TRUE rather than merely finished β€” "Matched N of M formula
7
+ // cells", which is R1's differential ("done when every computed cell matches the file's cached
8
+ // value") stated as a number.
9
+ //
10
+ // β›”β›” NOTHING HERE OPENS THE FILE. R1 puts openpyxl on the server, and a client that parsed the
11
+ // same bytes would be a second reader disagreeing with the first about merged cells, shared strings
12
+ // and cached values β€” a disagreement that surfaces as a wrong number on a screen rather than as an
13
+ // error. `file.size` and `file.name` are metadata the browser already had; they are the whole of
14
+ // what this file knows about the workbook.
15
+ //
16
+ // β›” THE POLL HAS FIVE TERMINAL CONDITIONS, NOT THREE. C4 names two (`done`, `refused`); a loop
17
+ // that stopped only on those spins forever against a job that stalls, and the dialog then lies
18
+ // about work that is not happening. The other three are the tick CAP, CANCEL and UNMOUNT, all
19
+ // three arbitrated by ONE run token: every `setState` in the loop is preceded by a check that the
20
+ // run it belongs to is still the current one, so a cancelled poll cannot paint over a fresh one.
21
+ //
22
+ // ⚠ THE SHELL IS `ConfirmDialog`, NOT A SECOND DIALOG SHAPED LIKE IT (contract C8). It brings the
23
+ // centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap, Escape, the
24
+ // backdrop and the return of focus to the opener. This file adds a BODY and nothing else. In
25
+ // particular it installs no Escape handler of its own: `useOverlayLayer` inside the kit already
26
+ // claims the key, and a second claimant would race the first.
27
+ //
28
+ // ⚠ `busy` LOCKS BOTH BUTTONS WHILE THE JOB RUNS, and that is the kit's semantics rather than an
29
+ // oversight. The read happens in a server thread that a client dismissal cannot stop, so a live
30
+ // Cancel would promise a cancellation nobody performs. The tick cap is what bounds the lock.
31
+ // ---------------------------------------------------------------------------
32
+ import { useCallback, useEffect, useRef, useState } from "react";
33
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
34
+ import {
35
+ BYTES_PER_MB,
36
+ IMPORT_MAX_BYTES,
37
+ IMPORT_MAX_MB,
38
+ importWorkbook,
39
+ readImportJob,
40
+ } from "./sheetApi";
41
+ import type { ImportJob, ImportState, Result } from "./sheetApi";
42
+
43
+ export interface ImportDialogProps {
44
+ open: boolean;
45
+ /** Dismissed without importing anything, or closed after the job ended. */
46
+ onCancel: () => void;
47
+ /** The import landed: this is the workbook it made, and the host opens it. */
48
+ onOpened: (workbookId: string) => void;
49
+ }
50
+
51
+ /** 750ms x 240 ticks is three minutes, which is the cap and the sentence below agrees with it. */
52
+ const POLL_MS = 750;
53
+ const POLL_TICKS = 240;
54
+ const POLL_MINUTES = Math.round((POLL_MS * POLL_TICKS) / 60000);
55
+
56
+ /** The word each state wears, sentence case, exactly as the done-when names them. */
57
+ const STATE_LABEL: Record<ImportState, string> = {
58
+ reading: "Reading",
59
+ cells: "Cells",
60
+ formats: "Formats",
61
+ recalc: "Recalculating",
62
+ done: "Done",
63
+ refused: "Stopped",
64
+ };
65
+
66
+ /** ...and the sentence under it, because a single word is a label and not an explanation. */
67
+ const STATE_NOTE: Record<ImportState, string> = {
68
+ reading: "Reading the file.",
69
+ cells: "Reading the cells and their values.",
70
+ formats: "Reading the number formats.",
71
+ recalc: "Recalculating every formula and comparing it to the file.",
72
+ done: "Opening the workbook.",
73
+ refused: "The import stopped.",
74
+ };
75
+
76
+ const NOT_AVAILABLE = "Importing a workbook is not available yet.";
77
+
78
+ const wait = (ms: number) => new Promise<void>((done) => { window.setTimeout(done, ms); });
79
+
80
+ /**
81
+ * β›”β›” THE ORDER OF THESE BRANCHES IS THE WHOLE OF THE CHECK, and it is ordered by WHAT EACH STATUS
82
+ * PROVES rather than by the numbers. A 413 and any NAMED refusal both prove the route is THERE and
83
+ * answered about this file; only an unnamed 4xx is evidence of absence. Read the other way round,
84
+ * the first oversized file would convince this client permanently that import does not exist, with
85
+ * nothing on screen saying what actually happened.
86
+ *
87
+ * ⚠ AND THE FALLBACK IS KEYED ON `>= 400` EXCEPT 403, NEVER ON A CODE LIST. An unbuilt route under
88
+ * a path parameter answers 405, not 404 [[an-unbuilt-route-under-a-path-param-answers-405]], and a
89
+ * 403 is a permission answer from a route that plainly exists.
90
+ */
91
+ /**
92
+ * β›”β›” `unknown` IS NOT THE ONLY UNNAMED CODE, AND THAT COST THIS TICKET ITS DONE-WHEN.
93
+ * The API wraps EVERY HTTP error in its own envelope, so an unbuilt route answers
94
+ * {"error": {"code": "http_405", "message": "Method Not Allowed"}}
95
+ * and `res.code !== "unknown"` reads that as a NAMED refusal. The dialog then showed the reason
96
+ * phrase `Method Not Allowed` to a person who asked to import a spreadsheet, and the
97
+ * not-available-yet sentence below was unreachable. Measured in a live browser, not predicted.
98
+ * ⭐ A code the SERVER'S OWN VOCABULARY defines (`sheet_too_many_cells`, `workbook_too_large`)
99
+ * is a sentence worth showing. `http_<status>` is the transport restating itself.
100
+ */
101
+ const HTTP_ENVELOPE = /^http_\d{3}$/;
102
+
103
+ export function refusalSentence(res: { status: number; code: string; message: string }): string {
104
+ const named = res.code !== "unknown" && !HTTP_ENVELOPE.test(res.code);
105
+ if (res.status === 0) return res.message;
106
+ if (res.status === 413) {
107
+ return named
108
+ ? res.message
109
+ : `That file is over the ${IMPORT_MAX_MB} MB limit the server accepts.`;
110
+ }
111
+ if (named) return res.message;
112
+ if (res.status === 403) return res.message;
113
+ if (res.status >= 400 && res.status !== 403) return NOT_AVAILABLE;
114
+ return res.message;
115
+ }
116
+
117
+ /**
118
+ * The client's own two refusals, said as sentences naming the cap and the count.
119
+ *
120
+ * ⚠ THE COMPARISON AND THE PRINTED NUMBER SHARE ONE DIVISOR, or a file could read "25.0 MB" on
121
+ * screen and still be refused. The test is `>` rather than `>=`, so a file exactly at the cap is
122
+ * offered to the server, which is the side that owns the limit.
123
+ */
124
+ export function fileRefusal(file: File): string {
125
+ if (!/\.xlsx$/i.test(file.name)) {
126
+ return "Loopable reads .xlsx workbooks. Choose a file saved in that format.";
127
+ }
128
+ if (file.size > IMPORT_MAX_BYTES) {
129
+ const mb = (file.size / BYTES_PER_MB).toFixed(1);
130
+ return `This file is ${mb} MB; the limit is ${IMPORT_MAX_MB} MB.`;
131
+ }
132
+ return "";
133
+ }
134
+
135
+ /** How many formula cells the differential is over. Zero means there is nothing to state. */
136
+ export function formulaCellsSeen(job: ImportJob | null): number {
137
+ const report = job?.report;
138
+ return report ? report.matched + report.mismatched.length : 0;
139
+ }
140
+
141
+ type Phase = "idle" | "running" | "ended";
142
+
143
+ export default function ImportDialog({ open, onCancel, onOpened }: ImportDialogProps) {
144
+ const [file, setFile] = useState<File | null>(null);
145
+ const [phase, setPhase] = useState<Phase>("idle");
146
+ const [job, setJob] = useState<ImportJob | null>(null);
147
+ const [sentence, setSentence] = useState("");
148
+ /** Remounts the native input, which is the only way to clear what it is showing. */
149
+ const [pick, setPick] = useState(0);
150
+
151
+ /**
152
+ * β›” THE RUN TOKEN IS WHAT MAKES CANCEL AND UNMOUNT TERMINAL. Bumping it orphans every pending
153
+ * tick of the loop that read the old value, so a poll whose dialog is gone cannot call
154
+ * `setState` on an unmounted component or reopen a stale progress bar over a fresh import.
155
+ */
156
+ const runRef = useRef(0);
157
+ const stop = useCallback(() => { runRef.current += 1; }, []);
158
+ useEffect(() => () => { runRef.current += 1; }, []);
159
+
160
+ const poll = useCallback(async (id: string, run: number) => {
161
+ for (let tick = 0; tick < POLL_TICKS; tick += 1) {
162
+ await wait(POLL_MS);
163
+ if (run !== runRef.current) return;
164
+ const read: Result<ImportJob> = await readImportJob(id);
165
+ if (run !== runRef.current) return;
166
+ if (!read.ok) {
167
+ setPhase("ended");
168
+ setSentence(refusalSentence(read));
169
+ return;
170
+ }
171
+ setJob(read.value);
172
+ if (read.value.state === "refused") {
173
+ setPhase("ended");
174
+ setSentence(read.value.sentence || "The import stopped and the server did not say why.");
175
+ return;
176
+ }
177
+ if (read.value.state === "done") {
178
+ setPhase("ended");
179
+ if (read.value.workbook_id) {
180
+ onOpened(read.value.workbook_id);
181
+ return;
182
+ }
183
+ setSentence("The import finished and the server did not say which workbook it made.");
184
+ return;
185
+ }
186
+ }
187
+ setPhase("ended");
188
+ setSentence(
189
+ `Nothing has come back from the import for ${POLL_MINUTES} minutes. `
190
+ + "Close this and try again.",
191
+ );
192
+ }, [onOpened]);
193
+
194
+ const start = useCallback(async () => {
195
+ if (!file) {
196
+ setSentence("Choose an .xlsx file to import.");
197
+ return;
198
+ }
199
+ const refused = fileRefusal(file);
200
+ if (refused) {
201
+ setSentence(refused);
202
+ return;
203
+ }
204
+ stop();
205
+ const run = runRef.current;
206
+ setSentence("");
207
+ setJob(null);
208
+ setPhase("running");
209
+ const started = await importWorkbook(file);
210
+ if (run !== runRef.current) return;
211
+ if (!started.ok) {
212
+ setPhase("ended");
213
+ setSentence(refusalSentence(started));
214
+ return;
215
+ }
216
+ if (!started.value.job) {
217
+ setPhase("ended");
218
+ setSentence("The server accepted the file and did not say which job is reading it.");
219
+ return;
220
+ }
221
+ await poll(started.value.job, run);
222
+ }, [file, poll, stop]);
223
+
224
+ /** After a refusal the primary starts over rather than silently re-posting the same file. */
225
+ const reset = useCallback(() => {
226
+ stop();
227
+ setJob(null);
228
+ setSentence("");
229
+ setFile(null);
230
+ setPick((n) => n + 1);
231
+ setPhase("idle");
232
+ }, [stop]);
233
+
234
+ const dismiss = useCallback(() => { stop(); onCancel(); }, [onCancel, stop]);
235
+
236
+ const onPrimary = () => {
237
+ if (phase === "running") return;
238
+ if (phase === "ended") { reset(); return; }
239
+ void start();
240
+ };
241
+
242
+ const running = phase === "running";
243
+ const ended = phase === "ended";
244
+ const pct = Math.round((job?.progress ?? 0) * 100);
245
+ const seen = formulaCellsSeen(job);
246
+ const report = job?.report;
247
+
248
+ return (
249
+ <ConfirmDialog
250
+ open={open}
251
+ title="Import a workbook"
252
+ confirmLabel={ended ? "Choose another file" : "Import"}
253
+ cancelLabel={phase === "idle" ? "Cancel" : "Close"}
254
+ tone="primary"
255
+ busy={running}
256
+ onConfirm={onPrimary}
257
+ onCancel={dismiss}
258
+ body={
259
+ <div className="sheet-import">
260
+ <p className="sheet-import-note">
261
+ Loopable reads the values, the formulas, the number formats and the layout. Files up to
262
+ {` ${IMPORT_MAX_MB}`} MB.
263
+ </p>
264
+
265
+ {/* β›” THE NATIVE INPUT, ON PURPOSE. It is keyboard reachable, it carries the operating
266
+ system's own file browser, and `accept` filters the picker without ever opening a
267
+ byte. A custom drop zone would be a second control shape for a job the platform
268
+ already does better. */}
269
+ <input
270
+ key={pick}
271
+ className="sheet-import-file"
272
+ type="file"
273
+ accept=".xlsx"
274
+ aria-label="The .xlsx file to import"
275
+ disabled={running}
276
+ onChange={(event) => {
277
+ const next = event.currentTarget.files?.[0] ?? null;
278
+ setFile(next);
279
+ setSentence(next ? fileRefusal(next) : "");
280
+ }}
281
+ />
282
+
283
+ {job ? (
284
+ <div className="sheet-import-progress">
285
+ <p className="sheet-import-state">{STATE_LABEL[job.state]}</p>
286
+ <div
287
+ className="sheet-import-bar"
288
+ role="progressbar"
289
+ aria-label="Import progress"
290
+ aria-valuemin={0}
291
+ aria-valuemax={100}
292
+ aria-valuenow={pct}
293
+ >
294
+ <span className="sheet-import-fill" style={{ width: `${pct}%` }} />
295
+ </div>
296
+ <p className="sheet-import-note">{STATE_NOTE[job.state]}</p>
297
+ </div>
298
+ ) : null}
299
+
300
+ {/* ⭐ R1'S DIFFERENTIAL, AND IT IS GUARDED ON HAVING SEEN A FORMULA AT ALL. "Matched 0 of
301
+ 0 formula cells" is a measurement nobody took, printed on a screen, which is the same
302
+ rule `sheetApi.ts` states for a recalc time the server never measured. A workbook with
303
+ no formulas shows no line rather than a row of zeroes. */}
304
+ {report && seen > 0 ? (
305
+ <p className="sheet-import-line">
306
+ {`Matched ${report.matched} of ${seen} formula cells.`}
307
+ </p>
308
+ ) : null}
309
+
310
+ {report && report.unsupported.length > 0 ? (
311
+ <div className="sheet-import-unsupported">
312
+ <p className="sheet-import-line">These parts of the file did not come across.</p>
313
+ {report.unsupported.map((item) => (
314
+ <p className="sheet-import-note" key={item}>{item}</p>
315
+ ))}
316
+ </div>
317
+ ) : null}
318
+
319
+ {/* The server's own words, verbatim. A rephrasing here would be this client inventing a
320
+ reason for something only the server watched happen. */}
321
+ {sentence ? <p className="sheet-import-refusal">{sentence}</p> : null}
322
+ </div>
323
+ }
324
+ />
325
+ );
326
+ }
web/src/sheet/Ribbon.tsx CHANGED
@@ -1,21 +1,31 @@
1
- // sheet/Ribbon.tsx β€” the Sheet's formatting ribbon (wave 50, W50-T19, amendment A1).
2
  //
3
  // ⭐⭐ WHAT THIS COMPONENT IS AND IS NOT. It is a `role="toolbar"` of STATELESS controls: every
4
- // button reports one patch and holds nothing. The selection, the cells and the commit all live in
5
- // `SheetGrid.tsx`, which routes a patch through the page's ONE commit door so a format change is
6
- // one history step and one save, exactly like a paste. A ribbon that kept its own idea of the
7
- // current style would drift from the cell the moment an undo landed.
8
  //
9
- // ⚠ THERE ARE NOW TWO `role="toolbar"` REGIONS ON THIS PAGE, AND THEY ARE DIFFERENT TOOLBARS.
10
- // `.sheet-toolbar` (aria-label "Sheet") carries the workbook's own acts: its title and Refresh.
11
- // This one (aria-label "Formatting") carries acts on the SELECTION. Two labelled toolbars is the
12
- // correct answer for a screen reader; one toolbar holding both would announce Refresh as a
13
- // formatting control.
 
 
14
  //
15
- // ⭐ ROVING FOCUS, WHICH NOTHING ELSE IN THIS TREE HAD. `CellActionBar` is a `role="toolbar"` of
16
- // plain buttons with no `onKeyDown`, so a keyboard user tabs through every control in it. Here
17
- // the toolbar is ONE tab stop and the arrows move within it (ArrowLeft / ArrowRight, Home / End),
18
- // which is the WAI-ARIA toolbar pattern and what the PRD's interaction layer names.
 
 
 
 
 
 
 
 
19
  //
20
  // β›” THE ROVING HANDLER IS GATED ON `open === ""`. A colour swatch grid and a format menu are
21
  // their own arrow-key surfaces; leaving the toolbar handler live underneath would move the
@@ -28,11 +38,45 @@
28
  // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order
29
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
30
 
31
- import { useCallback, useEffect, useRef, useState } from "react";
32
  import type { KeyboardEvent, ReactNode } from "react";
33
  import { CELL_FORMAT_KINDS } from "./types";
34
  import type { CellFormatKind, CellStyle, CellStylePatch } from "./types";
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  export interface RibbonProps {
37
  /**
38
  * The style of the cell the selection is ANCHORED on, which is what the toggles report as
@@ -42,19 +86,66 @@ export interface RibbonProps {
42
  style: CellStyle | null;
43
  /** No selection, or a workbook that is saving: every control is inert but still readable. */
44
  disabled?: boolean;
 
 
 
 
45
  onApply: (patch: CellStylePatch) => void;
 
46
  }
47
 
48
- /** The tab order INSIDE the toolbar, in the order the controls are read. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  const ORDER = [
50
- "bold", "italic", "underline",
51
- "color", "fill",
52
- "left", "center", "right",
53
- "format", "border",
54
  ] as const;
55
 
56
  type ControlKey = (typeof ORDER)[number];
57
- type Popover = "" | "color" | "fill" | "format" | "border";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  /**
60
  * The ink a person may choose, as TOKEN NAMES.
@@ -84,6 +175,12 @@ const FILLS: { token: string; label: string }[] = [
84
  { token: "--lp-purple-tint", label: "Purple" },
85
  ];
86
 
 
 
 
 
 
 
87
  const FORMAT_LABEL: Record<CellFormatKind, string> = {
88
  general: "General",
89
  number: "Number",
@@ -100,6 +197,14 @@ const BORDERS: { id: string; label: string; sides: Record<string, boolean> }[] =
100
  { id: "left", label: "Left", sides: { left: true } },
101
  ];
102
 
 
 
 
 
 
 
 
 
103
  function IconAlign({ to }: { to: "left" | "center" | "right" }) {
104
  // Four rules; the short ones move, which is what says left, centre or right without a word.
105
  const short = to === "left" ? "M2.5 8h6M2.5 12h7"
@@ -113,6 +218,39 @@ function IconAlign({ to }: { to: "left" | "center" | "right" }) {
113
  );
114
  }
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  function IconInk() {
117
  return (
118
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
@@ -140,6 +278,27 @@ function IconBorder() {
140
  );
141
  }
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  function IconCaret() {
144
  return (
145
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-caret">
@@ -148,11 +307,40 @@ function IconCaret() {
148
  );
149
  }
150
 
151
- export default function Ribbon({ style, disabled = false, onApply }: RibbonProps) {
152
- const [focus, setFocus] = useState<ControlKey>("bold");
 
 
 
 
 
 
 
 
 
 
 
153
  const [open, setOpen] = useState<Popover>("");
 
154
  const rootRef = useRef<HTMLDivElement | null>(null);
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  const focusControl = useCallback((key: ControlKey) => {
157
  setFocus(key);
158
  rootRef.current
@@ -160,6 +348,15 @@ export default function Ribbon({ style, disabled = false, onApply }: RibbonProps
160
  ?.focus();
161
  }, []);
162
 
 
 
 
 
 
 
 
 
 
163
  // β›” A POPOVER CLOSES ON AN OUTSIDE PRESS, AND ON `mousedown` RATHER THAN `click`. A click
164
  // listener fires after the grid canvas has already taken focus and dropped its selection, so
165
  // the menu would close having applied nothing to a cell that is no longer selected.
@@ -181,27 +378,32 @@ export default function Ribbon({ style, disabled = false, onApply }: RibbonProps
181
  }
182
  // The toolbar's arrows belong to the toolbar only while nothing is open above it.
183
  if (open) return;
184
- const at = ORDER.indexOf(focus);
185
  if (event.key === "ArrowRight") {
186
  event.preventDefault();
187
- focusControl(ORDER[(at + 1) % ORDER.length]);
188
  } else if (event.key === "ArrowLeft") {
189
  event.preventDefault();
190
- focusControl(ORDER[(at - 1 + ORDER.length) % ORDER.length]);
191
  } else if (event.key === "Home") {
192
  event.preventDefault();
193
- focusControl(ORDER[0]);
194
  } else if (event.key === "End") {
195
  event.preventDefault();
196
- focusControl(ORDER[ORDER.length - 1]);
197
  }
198
- }, [focus, focusControl, open]);
199
 
200
  const apply = useCallback((patch: CellStylePatch) => {
201
  setOpen("");
202
  onApply(patch);
203
  }, [onApply]);
204
 
 
 
 
 
 
205
  /** One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part. */
206
  const control = (
207
  key: ControlKey,
@@ -232,6 +434,36 @@ export default function Ribbon({ style, disabled = false, onApply }: RibbonProps
232
  </button>
233
  );
234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  const swatches = (
236
  which: "color" | "fill",
237
  list: { token: string; label: string }[],
@@ -268,156 +500,337 @@ export default function Ribbon({ style, disabled = false, onApply }: RibbonProps
268
  const format = style?.format;
269
  const kind: CellFormatKind = format?.kind ?? "general";
270
  const decimals = format?.decimals ?? (kind === "currency" ? 2 : 0);
 
 
 
 
 
 
 
 
 
 
 
271
 
272
  return (
273
- <div
274
- className="sheet-ribbon"
275
- role="toolbar"
276
- aria-label="Formatting"
277
- ref={rootRef}
278
- onKeyDown={onKeyDown}
279
- >
280
- {control("bold", "Bold", <span className="sheet-ribbon-glyph is-bold">B</span>,
281
- () => apply({ bold: !style?.bold }), style?.bold === true)}
282
- {control("italic", "Italic", <span className="sheet-ribbon-glyph is-italic">I</span>,
283
- () => apply({ italic: !style?.italic }), style?.italic === true)}
284
- {control("underline", "Underline", <span className="sheet-ribbon-glyph is-underline">U</span>,
285
- () => apply({ underline: !style?.underline }), style?.underline === true)}
286
-
287
- <span className="sheet-ribbon-sep" aria-hidden="true" />
288
-
289
- <span className="sheet-ribbon-slot">
290
- {control("color", "Text colour",
291
- <><IconInk /><IconCaret /></>,
292
- () => setOpen(open === "color" ? "" : "color"), !!style?.color, open === "color")}
293
- {open === "color" && swatches("color", INKS)}
294
- </span>
295
- <span className="sheet-ribbon-slot">
296
- {control("fill", "Fill colour",
297
- <><IconFill /><IconCaret /></>,
298
- () => setOpen(open === "fill" ? "" : "fill"), !!style?.fill, open === "fill")}
299
- {open === "fill" && swatches("fill", FILLS)}
300
- </span>
301
-
302
- <span className="sheet-ribbon-sep" aria-hidden="true" />
303
-
304
- {(["left", "center", "right"] as const).map((to) => control(
305
- to,
306
- to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
307
- <IconAlign to={to} />,
308
- () => apply({ align: style?.align === to ? null : to }),
309
- style?.align === to,
310
- ))}
311
-
312
- <span className="sheet-ribbon-sep" aria-hidden="true" />
313
-
314
- <span className="sheet-ribbon-slot">
315
- {control("format", "Number format",
316
- <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
317
- () => setOpen(open === "format" ? "" : "format"), kind !== "general", open === "format")}
318
- {open === "format" && (
319
- <div className="sheet-ribbon-pop" role="menu" aria-label="Number format">
320
- {CELL_FORMAT_KINDS.map((entry) => (
321
- <button
322
- key={entry}
323
- type="button"
324
- role="menuitemradio"
325
- aria-checked={entry === kind}
326
- className={"sheet-ribbon-item" + (entry === kind ? " is-on" : "")}
327
- onMouseDown={(e) => e.preventDefault()}
328
- onClick={() => onApply(
329
- entry === "general"
330
- ? { format: null }
331
- : {
332
- format: {
333
- kind: entry,
334
- decimals: entry === "currency" ? 2 : entry === "date" ? undefined : 0,
335
- thousands: format?.thousands,
336
- },
337
- },
338
- )}
339
- >
340
- {FORMAT_LABEL[entry]}
341
- </button>
342
  ))}
343
- {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are shown only
344
- where they mean something; a date has neither and a percent groups by locale. */}
345
- {(kind === "number" || kind === "currency" || kind === "percent") && (
346
- <div className="sheet-ribbon-row">
347
- <span className="sheet-ribbon-row-label">Decimal places</span>
348
- <button
349
- type="button"
350
- className="sheet-ribbon-step"
351
- aria-label="Fewer decimal places"
352
- onMouseDown={(e) => e.preventDefault()}
353
- onClick={() => onApply({
354
- format: { ...format, kind, decimals: Math.max(0, decimals - 1) },
355
- })}
356
- >
357
- Fewer
358
- </button>
359
- <span className="sheet-ribbon-count">{decimals}</span>
360
- <button
361
- type="button"
362
- className="sheet-ribbon-step"
363
- aria-label="More decimal places"
364
- onMouseDown={(e) => e.preventDefault()}
365
- onClick={() => onApply({
366
- format: { ...format, kind, decimals: Math.min(10, decimals + 1) },
367
- })}
368
- >
369
- More
370
- </button>
371
- </div>
372
- )}
373
- {kind === "number" && (
374
- <button
375
- type="button"
376
- role="menuitemcheckbox"
377
- aria-checked={format?.thousands === true}
378
- className={"sheet-ribbon-item" + (format?.thousands ? " is-on" : "")}
379
- onMouseDown={(e) => e.preventDefault()}
380
- onClick={() => onApply({
381
- format: { ...format, kind, thousands: !format?.thousands },
382
- })}
383
- >
384
- Thousands separator
385
- </button>
386
- )}
387
- </div>
388
- )}
389
- </span>
390
-
391
- <span className="sheet-ribbon-slot">
392
- {control("border", "Borders", <><IconBorder /><IconCaret /></>,
393
- () => setOpen(open === "border" ? "" : "border"),
394
- Object.values(style?.border ?? {}).some(Boolean), open === "border")}
395
- {open === "border" && (
396
- <div className="sheet-ribbon-pop" role="menu" aria-label="Borders">
397
- {BORDERS.map((entry) => (
398
- <button
399
- key={entry.id}
400
- type="button"
401
- role="menuitem"
402
- className="sheet-ribbon-item"
403
- onMouseDown={(e) => e.preventDefault()}
404
- onClick={() => apply({ border: entry.sides })}
405
- >
406
- {entry.label}
407
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
408
  ))}
409
- <button
410
- type="button"
411
- role="menuitem"
412
- className="sheet-ribbon-item"
413
- onMouseDown={(e) => e.preventDefault()}
414
- onClick={() => apply({ border: null })}
415
- >
416
- No border
417
- </button>
418
  </div>
419
- )}
420
- </span>
 
 
 
 
 
 
 
 
 
 
 
421
  </div>
422
  );
423
  }
 
1
+ // sheet/Ribbon.tsx β€” the Sheet's HOME ribbon (wave 50, W50-T19/A1; wave 51, W51-T15, ruling R8).
2
  //
3
  // ⭐⭐ WHAT THIS COMPONENT IS AND IS NOT. It is a `role="toolbar"` of STATELESS controls: every
4
+ // button reports one patch or one named act and holds nothing. The selection, the cells and the
5
+ // commit all live in `SheetGrid.tsx`, which routes a patch through the page's ONE commit door so a
6
+ // format change is one history step and one save, exactly like a paste. A ribbon that kept its own
7
+ // idea of the current style would drift from the cell the moment an undo landed.
8
  //
9
+ // ⭐⭐ W51-T15 β€” TWO EMISSIONS, AND THE SECOND ONE IS A CONTRACT WITH A LATER TICKET.
10
+ // `onApply(CellStylePatch)` is a style the document already understands. `onAction({kind, arg})`
11
+ // is a NAMED ACT, and its `kind` is a closed TypeScript union on purpose: W51-T16 implements the
12
+ // acts, and a union is what stops it inventing a name this file does not emit or handling one that
13
+ // never arrives. Every control in R8's roster is present, labelled and focusable NOW even where
14
+ // its act is still owned by that ticket; a control that exists but is unreachable is the harder
15
+ // defect to find later.
16
  //
17
+ // β›” THERE IS EXACTLY ONE `role="toolbar"` HERE AND NONE IN `SheetGrid.tsx` (W51-T15). It used to
18
+ // be two: this one, plus a second strip labelled "Rows and columns" carrying Insert row, Delete
19
+ // row, Insert column, Delete column, Add rows, Add columns and Freeze panes. R8 puts those
20
+ // acts in the Cells group of the Home row, so the strip is folded in and gone. Two toolbars over
21
+ // one grid was also the thing instruction 8 was complaining about: a second white line.
22
+ //
23
+ // ⭐ ROVING FOCUS, AND IT SURVIVES A COLLAPSE. The whole ribbon is ONE tab stop and the arrows move
24
+ // within it (ArrowLeft / ArrowRight, Home / End), which is the WAI-ARIA toolbar pattern. When the
25
+ // ribbon is COLLAPSED the roving order shrinks to the tab strip and the chevron rather than
26
+ // disappearing, because a collapsed ribbon a keyboard cannot re-open is a trap. The handler and
27
+ // the ref both live on the SHELL, one level above the toolbar row, which is what lets the row
28
+ // itself unmount without taking the keyboard with it.
29
  //
30
  // β›” THE ROVING HANDLER IS GATED ON `open === ""`. A colour swatch grid and a format menu are
31
  // their own arrow-key surfaces; leaving the toolbar handler live underneath would move the
 
38
  // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order
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
 
46
+ /**
47
+ * ⭐⭐ THE ACT VOCABULARY, CLOSED. W51-T16 builds against this union and nothing else; adding a
48
+ * control means adding its name here first, which is exactly the review moment that was missing
49
+ * when the borders button shipped doing nothing (instruction 17).
50
+ */
51
+ export type RibbonActionKind =
52
+ // Clipboard
53
+ | "paste" | "cut" | "copy" | "format-painter"
54
+ // Font
55
+ | "font-size"
56
+ // Alignment
57
+ | "align-top" | "align-middle" | "align-bottom"
58
+ | "wrap-text" | "indent-decrease" | "indent-increase"
59
+ // Number (the two formats the document model does not carry yet)
60
+ | "format-accounting" | "format-custom"
61
+ // Styles
62
+ | "conditional-formatting"
63
+ // Cells
64
+ | "insert-row" | "insert-column" | "delete-row" | "delete-column"
65
+ | "add-rows" | "add-columns"
66
+ | "row-height" | "column-width"
67
+ | "hide-rows" | "hide-columns" | "unhide" | "freeze"
68
+ // Editing
69
+ | "autosum" | "fill-down" | "fill-right"
70
+ | "clear-contents" | "clear-formats" | "clear-all"
71
+ // The workbook's own acts, which R8 puts on the SAME row rather than on a line of their own
72
+ | "refresh" | "import";
73
+
74
+ export interface RibbonAction {
75
+ kind: RibbonActionKind;
76
+ /** A step name (`small`), a count, or nothing. Never a free sentence. */
77
+ arg?: string | number;
78
+ }
79
+
80
  export interface RibbonProps {
81
  /**
82
  * The style of the cell the selection is ANCHORED on, which is what the toggles report as
 
86
  style: CellStyle | null;
87
  /** No selection, or a workbook that is saving: every control is inert but still readable. */
88
  disabled?: boolean;
89
+ /** Whether the sheet currently freezes its leading column, so the Freeze item reads back. */
90
+ frozen?: boolean;
91
+ /** β›” NO FAKE AFFORDANCE. Import is offered only where the page actually has a door for it. */
92
+ canImport?: boolean;
93
  onApply: (patch: CellStylePatch) => void;
94
+ onAction: (action: RibbonAction) => void;
95
  }
96
 
97
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
98
+ // THE ROVING ORDER, DERIVED FROM THE GROUPS RATHER THAN RESTATED BESIDE THEM.
99
+ //
100
+ // β›” A HAND MAINTAINED PARALLEL ARRAY IS HOW ROVING FOCUS DIES SILENTLY: one `data-ribbon` typo and
101
+ // `focusControl`'s query returns null, with every gate still green. `ControlKey` is derived from
102
+ // these arrays, so a control rendered under a name that is not in one of them is a TYPE ERROR.
103
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
104
+
105
+ const STRIP = ["tab-home", "collapse"] as const;
106
+ const CLIPBOARD = ["paste", "cut", "copy", "painter"] as const;
107
+ const FONT = ["bold", "italic", "underline", "border", "fill", "color", "size"] as const;
108
+ const ALIGNMENT = [
109
+ "top", "middle", "bottom", "left", "center", "right", "wrap", "outdent", "indent",
110
+ ] as const;
111
+ const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"] as const;
112
+ const STYLES = ["conditional"] as const;
113
+ const CELLS = ["insert", "delete", "cellformat"] as const;
114
+ const EDITING = ["autosum", "filldown", "fillright", "clear"] as const;
115
+ const UTILITY = ["import", "refresh"] as const;
116
+
117
  const ORDER = [
118
+ ...STRIP, ...CLIPBOARD, ...FONT, ...ALIGNMENT, ...NUMBER, ...STYLES, ...CELLS, ...EDITING,
119
+ ...UTILITY,
 
 
120
  ] as const;
121
 
122
  type ControlKey = (typeof ORDER)[number];
123
+ type Popover =
124
+ | "" | "color" | "fill" | "format" | "border" | "size" | "insert" | "delete" | "cellformat"
125
+ | "clear";
126
+
127
+ /**
128
+ * ⭐ COLLAPSE IS REMEMBERED PER PERSON, and the key is namespaced so nothing else in the app can
129
+ * collide with it. A throwing read (a private window refuses storage) renders EXPANDED, which is
130
+ * the state that shows every control rather than the state that hides them.
131
+ */
132
+ const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed";
133
+
134
+ const readCollapsed = (): boolean => {
135
+ try {
136
+ return window.localStorage.getItem(COLLAPSE_KEY) === "1";
137
+ } catch {
138
+ return false;
139
+ }
140
+ };
141
+
142
+ const writeCollapsed = (next: boolean) => {
143
+ try {
144
+ window.localStorage.setItem(COLLAPSE_KEY, next ? "1" : "0");
145
+ } catch {
146
+ // Storage is refused in a private window. The ribbon still collapses for this session.
147
+ }
148
+ };
149
 
150
  /**
151
  * The ink a person may choose, as TOKEN NAMES.
 
175
  { token: "--lp-purple-tint", label: "Purple" },
176
  ];
177
 
178
+ /**
179
+ * β›” THE FIVE THE DOCUMENT MODEL CARRIES, AND ONLY THOSE. `CELL_FORMAT_KINDS` is mirrored in
180
+ * `platform/core/sheets.py` and a sixth spelling is REFUSED by name on the way in, so R8's
181
+ * Accounting and Custom code are offered as ACTS (`format-accounting`, `format-custom`) rather
182
+ * than smuggled in here as a kind the server would reject.
183
+ */
184
  const FORMAT_LABEL: Record<CellFormatKind, string> = {
185
  general: "General",
186
  number: "Number",
 
197
  { id: "left", label: "Left", sides: { left: true } },
198
  ];
199
 
200
+ /** R8's four step size scale. Inter only, so a step is a SIZE and never a typeface. */
201
+ const SIZE_STEPS: { id: string; label: string }[] = [
202
+ { id: "small", label: "Small" },
203
+ { id: "normal", label: "Normal" },
204
+ { id: "large", label: "Large" },
205
+ { id: "heading", label: "Heading" },
206
+ ];
207
+
208
  function IconAlign({ to }: { to: "left" | "center" | "right" }) {
209
  // Four rules; the short ones move, which is what says left, centre or right without a word.
210
  const short = to === "left" ? "M2.5 8h6M2.5 12h7"
 
218
  );
219
  }
220
 
221
+ /** The vertical three: a cell box, with the text rule sitting where the value would land. */
222
+ function IconVAlign({ to }: { to: "top" | "middle" | "bottom" }) {
223
+ const y = to === "top" ? 5 : to === "middle" ? 8 : 11;
224
+ return (
225
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
226
+ <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="1" />
227
+ <path d={`M5 ${y}h6`} />
228
+ </svg>
229
+ );
230
+ }
231
+
232
+ function IconWrap() {
233
+ return (
234
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
235
+ <path d="M2.5 4.5h11" />
236
+ <path d="M2.5 8h8.5a2 2 0 0 1 0 4H7" />
237
+ <path d="M8.6 10.4L7 12l1.6 1.6" />
238
+ </svg>
239
+ );
240
+ }
241
+
242
+ function IconIndent({ out }: { out: boolean }) {
243
+ const arrow = out ? "M6.6 6.4L4.6 8l2 1.6" : "M4.6 6.4L6.6 8l-2 1.6";
244
+ return (
245
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
246
+ <path d="M2.5 3.5h11" />
247
+ <path d="M8.5 6.5h5M8.5 9.5h5" />
248
+ <path d="M2.5 12.5h11" />
249
+ <path d={arrow} />
250
+ </svg>
251
+ );
252
+ }
253
+
254
  function IconInk() {
255
  return (
256
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
 
278
  );
279
  }
280
 
281
+ /** Two decimal dots and the direction the count moves. Never a glyph, never a dash. */
282
+ function IconDecimals({ more }: { more: boolean }) {
283
+ const arrow = more ? "M9.4 6.2L11.4 8l-2 1.8" : "M11.4 6.2L9.4 8l2 1.8";
284
+ return (
285
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
286
+ <path d="M3 11.6h.01M6 11.6h.01" />
287
+ <path d="M3 5.5v3.4M6 5.5v3.4" />
288
+ <path d={arrow} />
289
+ </svg>
290
+ );
291
+ }
292
+
293
+ function IconRefresh() {
294
+ return (
295
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
296
+ <path d="M13 8a5 5 0 1 1-1.6-3.7" />
297
+ <path d="M13.2 2.6v3.2h-3.2" />
298
+ </svg>
299
+ );
300
+ }
301
+
302
  function IconCaret() {
303
  return (
304
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-caret">
 
307
  );
308
  }
309
 
310
+ /** The collapse chevron. It points UP while the row is showing, because that is where it goes. */
311
+ function IconChevron({ up }: { up: boolean }) {
312
+ return (
313
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
314
+ <path d={up ? "M4.5 9.5L8 6l3.5 3.5" : "M4.5 6.5L8 10l3.5 -3.5"} />
315
+ </svg>
316
+ );
317
+ }
318
+
319
+ export default function Ribbon({
320
+ style, disabled = false, frozen = false, canImport = false, onApply, onAction,
321
+ }: RibbonProps) {
322
+ const [focus, setFocus] = useState<ControlKey>("tab-home");
323
  const [open, setOpen] = useState<Popover>("");
324
+ const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
325
  const rootRef = useRef<HTMLDivElement | null>(null);
326
 
327
+ /**
328
+ * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else; and
329
+ * Import is only in the order on a page that actually has an import door.
330
+ */
331
+ const reachable = useMemo<readonly ControlKey[]>(
332
+ () => (collapsed ? STRIP : ORDER.filter((key) => key !== "import" || canImport)),
333
+ [canImport, collapsed],
334
+ );
335
+
336
+ // β›” FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
337
+ // is about to unmount would leave the roving state pointing at nothing: every arrow press after
338
+ // it would query a `data-ribbon` that is not in the tree, and NO control would carry tabIndex 0,
339
+ // so the toolbar would drop out of the tab order entirely with every gate still green.
340
+ useEffect(() => {
341
+ if (!reachable.includes(focus)) setFocus(reachable[0]);
342
+ }, [focus, reachable]);
343
+
344
  const focusControl = useCallback((key: ControlKey) => {
345
  setFocus(key);
346
  rootRef.current
 
348
  ?.focus();
349
  }, []);
350
 
351
+ const toggleCollapsed = useCallback(() => {
352
+ setCollapsed((was) => {
353
+ const next = !was;
354
+ writeCollapsed(next);
355
+ return next;
356
+ });
357
+ setOpen("");
358
+ }, []);
359
+
360
  // β›” A POPOVER CLOSES ON AN OUTSIDE PRESS, AND ON `mousedown` RATHER THAN `click`. A click
361
  // listener fires after the grid canvas has already taken focus and dropped its selection, so
362
  // the menu would close having applied nothing to a cell that is no longer selected.
 
378
  }
379
  // The toolbar's arrows belong to the toolbar only while nothing is open above it.
380
  if (open) return;
381
+ const at = Math.max(0, reachable.indexOf(focus));
382
  if (event.key === "ArrowRight") {
383
  event.preventDefault();
384
+ focusControl(reachable[(at + 1) % reachable.length]);
385
  } else if (event.key === "ArrowLeft") {
386
  event.preventDefault();
387
+ focusControl(reachable[(at - 1 + reachable.length) % reachable.length]);
388
  } else if (event.key === "Home") {
389
  event.preventDefault();
390
+ focusControl(reachable[0]);
391
  } else if (event.key === "End") {
392
  event.preventDefault();
393
+ focusControl(reachable[reachable.length - 1]);
394
  }
395
+ }, [focus, focusControl, open, reachable]);
396
 
397
  const apply = useCallback((patch: CellStylePatch) => {
398
  setOpen("");
399
  onApply(patch);
400
  }, [onApply]);
401
 
402
+ const act = useCallback((kind: RibbonActionKind, arg?: string | number) => {
403
+ setOpen("");
404
+ onAction({ kind, arg });
405
+ }, [onAction]);
406
+
407
  /** One control. `data-ribbon` is what the roving handler finds; `tabIndex` is the roving part. */
408
  const control = (
409
  key: ControlKey,
 
434
  </button>
435
  );
436
 
437
+ /**
438
+ * ⭐ A GROUP IS NAMED TWICE ON PURPOSE: once for a screen reader (`role="group"` plus its label)
439
+ * and once on the screen, in the caption under its controls. R8 names the seven groups and the
440
+ * owner reads them by name, so a row of unnamed clusters would not be the thing that was asked
441
+ * for. Sentence case, muted, and a scale token, never a literal size (DESIGN.md 2).
442
+ */
443
+ const group = (name: string, body: ReactNode, extra = "") => (
444
+ <div className={"sheet-ribbon-group" + extra} role="group" aria-label={name}>
445
+ <div className="sheet-ribbon-group-controls">{body}</div>
446
+ <span className="sheet-ribbon-group-name">{name}</span>
447
+ </div>
448
+ );
449
+
450
+ /** A plain word inside a control. A ribbon is not an icon quiz. */
451
+ const word = (text: string) => <span className="sheet-ribbon-label">{text}</span>;
452
+
453
+ const item = (label: string, onClick: () => void, on = false, role = "menuitem") => (
454
+ <button
455
+ key={label}
456
+ type="button"
457
+ role={role}
458
+ aria-checked={role === "menuitem" ? undefined : on}
459
+ className={"sheet-ribbon-item" + (on ? " is-on" : "")}
460
+ onMouseDown={(e) => e.preventDefault()}
461
+ onClick={onClick}
462
+ >
463
+ {label}
464
+ </button>
465
+ );
466
+
467
  const swatches = (
468
  which: "color" | "fill",
469
  list: { token: string; label: string }[],
 
500
  const format = style?.format;
501
  const kind: CellFormatKind = format?.kind ?? "general";
502
  const decimals = format?.decimals ?? (kind === "currency" ? 2 : 0);
503
+ /** Stepping decimals on a date or on an unformatted cell means the cell becomes a number. */
504
+ const numeric: CellFormatKind =
505
+ kind === "currency" || kind === "percent" ? kind : "number";
506
+
507
+ const stepDecimals = (delta: number) => onApply({
508
+ format: {
509
+ ...format,
510
+ kind: numeric,
511
+ decimals: Math.min(10, Math.max(0, decimals + delta)),
512
+ },
513
+ });
514
 
515
  return (
516
+ <div className="sheet-ribbon-shell" ref={rootRef} onKeyDown={onKeyDown}>
517
+ {/* ⭐ THE TAB STRIP. One tab today, and it is still a tab strip: it is where the collapse
518
+ chevron belongs and where a second tab would join without moving anything. */}
519
+ <div className="sheet-ribbon-tabs">
520
+ <div className="sheet-ribbon-tablist" role="tablist" aria-label="Ribbon tabs">
521
+ <button
522
+ type="button"
523
+ role="tab"
524
+ data-ribbon="tab-home"
525
+ className="sheet-ribbon-tab is-on"
526
+ aria-selected="true"
527
+ tabIndex={focus === "tab-home" ? 0 : -1}
528
+ onFocus={() => setFocus("tab-home")}
529
+ onMouseDown={(e) => e.preventDefault()}
530
+ onClick={() => { if (collapsed) toggleCollapsed(); }}
531
+ >
532
+ Home
533
+ </button>
534
+ </div>
535
+ <button
536
+ type="button"
537
+ data-ribbon="collapse"
538
+ className="sheet-ribbon-chevron"
539
+ aria-label={collapsed ? "Show the ribbon" : "Collapse the ribbon"}
540
+ title={collapsed ? "Show the ribbon" : "Collapse the ribbon"}
541
+ aria-expanded={!collapsed}
542
+ tabIndex={focus === "collapse" ? 0 : -1}
543
+ onFocus={() => setFocus("collapse")}
544
+ onMouseDown={(e) => e.preventDefault()}
545
+ onClick={toggleCollapsed}
546
+ >
547
+ <IconChevron up={!collapsed} />
548
+ </button>
549
+ </div>
550
+
551
+ {!collapsed && (
552
+ <div className="sheet-ribbon sheet-ribbon-home" role="toolbar" aria-label="Formatting">
553
+ {/* β›” `min-width: 0` ON THE SCROLLER IS LOAD BEARING. A flex child will not scroll
554
+ without it, and Refresh must stay OUT of the scrolling area or it walks off the
555
+ right edge at a narrow window, which is the complaint instruction 8 already made. */}
556
+ <div className="sheet-ribbon-scroll">
557
+
558
+ {group("Clipboard", (
559
+ <>
560
+ {control("paste", "Paste", word("Paste"), () => act("paste"))}
561
+ {control("cut", "Cut", word("Cut"), () => act("cut"))}
562
+ {control("copy", "Copy", word("Copy"), () => act("copy"))}
563
+ {control("painter", "Format painter", word("Format painter"),
564
+ () => act("format-painter"))}
565
+ </>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566
  ))}
567
+
568
+ {group("Font", (
569
+ <>
570
+ {control("bold", "Bold", <span className="sheet-ribbon-glyph is-bold">B</span>,
571
+ () => apply({ bold: !style?.bold }), style?.bold === true)}
572
+ {control("italic", "Italic",
573
+ <span className="sheet-ribbon-glyph is-italic">I</span>,
574
+ () => apply({ italic: !style?.italic }), style?.italic === true)}
575
+ {control("underline", "Underline",
576
+ <span className="sheet-ribbon-glyph is-underline">U</span>,
577
+ () => apply({ underline: !style?.underline }), style?.underline === true)}
578
+
579
+ <span className="sheet-ribbon-slot">
580
+ {control("border", "Borders", <><IconBorder /><IconCaret /></>,
581
+ () => setOpen(open === "border" ? "" : "border"),
582
+ Object.values(style?.border ?? {}).some(Boolean), open === "border")}
583
+ {open === "border" && (
584
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Borders">
585
+ {BORDERS.map((entry) => item(entry.label, () => apply({ border: entry.sides })))}
586
+ {item("No border", () => apply({ border: null }))}
587
+ </div>
588
+ )}
589
+ </span>
590
+
591
+ <span className="sheet-ribbon-slot">
592
+ {control("fill", "Fill colour",
593
+ <><IconFill /><IconCaret /></>,
594
+ () => setOpen(open === "fill" ? "" : "fill"), !!style?.fill, open === "fill")}
595
+ {open === "fill" && swatches("fill", FILLS)}
596
+ </span>
597
+ <span className="sheet-ribbon-slot">
598
+ {control("color", "Text colour",
599
+ <><IconInk /><IconCaret /></>,
600
+ () => setOpen(open === "color" ? "" : "color"), !!style?.color,
601
+ open === "color")}
602
+ {open === "color" && swatches("color", INKS)}
603
+ </span>
604
+
605
+ <span className="sheet-ribbon-slot">
606
+ {control("size", "Font size", <>{word("Size")}<IconCaret /></>,
607
+ () => setOpen(open === "size" ? "" : "size"), false, open === "size")}
608
+ {open === "size" && (
609
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Font size">
610
+ {SIZE_STEPS.map((step) => item(step.label, () => act("font-size", step.id)))}
611
+ </div>
612
+ )}
613
+ </span>
614
+ </>
615
+ ))}
616
+
617
+ {group("Alignment", (
618
+ <>
619
+ {control("top", "Align top", <IconVAlign to="top" />, () => act("align-top"))}
620
+ {control("middle", "Align middle", <IconVAlign to="middle" />,
621
+ () => act("align-middle"))}
622
+ {control("bottom", "Align bottom", <IconVAlign to="bottom" />,
623
+ () => act("align-bottom"))}
624
+ {(["left", "center", "right"] as const).map((to) => control(
625
+ to,
626
+ to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
627
+ <IconAlign to={to} />,
628
+ () => apply({ align: style?.align === to ? null : to }),
629
+ style?.align === to,
630
+ ))}
631
+ {control("wrap", "Wrap text", <IconWrap />, () => act("wrap-text"))}
632
+ {control("outdent", "Decrease indent", <IconIndent out />,
633
+ () => act("indent-decrease"))}
634
+ {control("indent", "Increase indent", <IconIndent out={false} />,
635
+ () => act("indent-increase"))}
636
+ </>
637
+ ))}
638
+
639
+ {group("Number", (
640
+ <>
641
+ <span className="sheet-ribbon-slot">
642
+ {control("format", "Number format",
643
+ <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
644
+ () => setOpen(open === "format" ? "" : "format"), kind !== "general",
645
+ open === "format")}
646
+ {open === "format" && (
647
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Number format">
648
+ {CELL_FORMAT_KINDS.map((entry) => (
649
+ <button
650
+ key={entry}
651
+ type="button"
652
+ role="menuitemradio"
653
+ aria-checked={entry === kind}
654
+ className={"sheet-ribbon-item" + (entry === kind ? " is-on" : "")}
655
+ onMouseDown={(e) => e.preventDefault()}
656
+ onClick={() => onApply(
657
+ entry === "general"
658
+ ? { format: null }
659
+ : {
660
+ format: {
661
+ kind: entry,
662
+ decimals: entry === "currency" ? 2 : entry === "date" ? undefined : 0,
663
+ thousands: format?.thousands,
664
+ },
665
+ },
666
+ )}
667
+ >
668
+ {FORMAT_LABEL[entry]}
669
+ </button>
670
+ ))}
671
+ {/* ⚠ THE TWO R8 NAMES THE DOCUMENT MODEL DOES NOT CARRY YET. They are acts,
672
+ not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so
673
+ writing `accounting` here would refuse the whole cell. */}
674
+ {item("Accounting", () => act("format-accounting"))}
675
+ {item("Custom code", () => act("format-custom"))}
676
+ {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are
677
+ shown only where they mean something; a date has neither and a percent
678
+ groups by locale. */}
679
+ {(kind === "number" || kind === "currency" || kind === "percent") && (
680
+ <div className="sheet-ribbon-row">
681
+ <span className="sheet-ribbon-row-label">Decimal places</span>
682
+ <button
683
+ type="button"
684
+ className="sheet-ribbon-step"
685
+ aria-label="Fewer decimal places"
686
+ onMouseDown={(e) => e.preventDefault()}
687
+ onClick={() => stepDecimals(-1)}
688
+ >
689
+ Fewer
690
+ </button>
691
+ <span className="sheet-ribbon-count">{decimals}</span>
692
+ <button
693
+ type="button"
694
+ className="sheet-ribbon-step"
695
+ aria-label="More decimal places"
696
+ onMouseDown={(e) => e.preventDefault()}
697
+ onClick={() => stepDecimals(1)}
698
+ >
699
+ More
700
+ </button>
701
+ </div>
702
+ )}
703
+ {kind === "number" && (
704
+ <button
705
+ type="button"
706
+ role="menuitemcheckbox"
707
+ aria-checked={format?.thousands === true}
708
+ className={"sheet-ribbon-item" + (format?.thousands ? " is-on" : "")}
709
+ onMouseDown={(e) => e.preventDefault()}
710
+ onClick={() => onApply({
711
+ format: { ...format, kind, thousands: !format?.thousands },
712
+ })}
713
+ >
714
+ Thousands separator
715
+ </button>
716
+ )}
717
+ </div>
718
+ )}
719
+ </span>
720
+
721
+ {control("currency", "Currency",
722
+ <span className="sheet-ribbon-glyph">$</span>,
723
+ () => apply({ format: { kind: "currency", decimals: 2 } }),
724
+ kind === "currency")}
725
+ {control("percent", "Percent",
726
+ <span className="sheet-ribbon-glyph">%</span>,
727
+ () => apply({ format: { kind: "percent", decimals: 0 } }),
728
+ kind === "percent")}
729
+ {control("comma", "Comma",
730
+ <span className="sheet-ribbon-glyph">,</span>,
731
+ () => apply({ format: { kind: "number", decimals: 2, thousands: true } }),
732
+ kind === "number" && format?.thousands === true)}
733
+ {control("decless", "Decrease decimals", <IconDecimals more={false} />,
734
+ () => stepDecimals(-1))}
735
+ {control("decmore", "Increase decimals", <IconDecimals more />,
736
+ () => stepDecimals(1))}
737
+ </>
738
+ ))}
739
+
740
+ {group("Styles", (
741
+ <>
742
+ {control("conditional", "Conditional formatting", word("Conditional formatting"),
743
+ () => act("conditional-formatting"))}
744
+ </>
745
+ ))}
746
+
747
+ {/* ⭐⭐ THE CELLS GROUP IS WHERE THE OLD "Rows and columns" STRIP WENT. Every act it
748
+ carried is still here and still reaches the same page callback; what is gone is a
749
+ second toolbar of its own. */}
750
+ {group("Cells", (
751
+ <>
752
+ <span className="sheet-ribbon-slot">
753
+ {control("insert", "Insert", <>{word("Insert")}<IconCaret /></>,
754
+ () => setOpen(open === "insert" ? "" : "insert"), false, open === "insert")}
755
+ {open === "insert" && (
756
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Insert">
757
+ {item("Insert row above", () => act("insert-row"))}
758
+ {item("Insert column left", () => act("insert-column"))}
759
+ {item("Add rows", () => act("add-rows"))}
760
+ {item("Add columns", () => act("add-columns"))}
761
+ </div>
762
+ )}
763
+ </span>
764
+ <span className="sheet-ribbon-slot">
765
+ {control("delete", "Delete", <>{word("Delete")}<IconCaret /></>,
766
+ () => setOpen(open === "delete" ? "" : "delete"), false, open === "delete")}
767
+ {open === "delete" && (
768
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Delete">
769
+ {item("Delete row", () => act("delete-row"))}
770
+ {item("Delete column", () => act("delete-column"))}
771
+ </div>
772
+ )}
773
+ </span>
774
+ <span className="sheet-ribbon-slot">
775
+ {control("cellformat", "Format", <>{word("Format")}<IconCaret /></>,
776
+ () => setOpen(open === "cellformat" ? "" : "cellformat"), false,
777
+ open === "cellformat")}
778
+ {open === "cellformat" && (
779
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Format">
780
+ {item("Row height", () => act("row-height"))}
781
+ {item("Column width", () => act("column-width"))}
782
+ {item("Hide rows", () => act("hide-rows"))}
783
+ {item("Hide columns", () => act("hide-columns"))}
784
+ {item("Unhide", () => act("unhide"))}
785
+ {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze panes panel offering rows and
786
+ columns rather than toggling one column. The label had to move with the
787
+ behaviour: a control that says "Freeze first column" and opens a
788
+ two-axis panel is the kind of small lie an owner finds in the first
789
+ minute. `aria-checked` still reports whether ANYTHING is frozen, which
790
+ is the useful state for a person scanning the menu.
791
+ ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells
792
+ tuple, so the two move in ONE commit or the rename reds a leg in a
793
+ ticket that never touched this file. */}
794
+ {item("Freeze panes", () => act("freeze"), frozen,
795
+ "menuitemcheckbox")}
796
+ </div>
797
+ )}
798
+ </span>
799
+ </>
800
+ ))}
801
+
802
+ {group("Editing", (
803
+ <>
804
+ {control("autosum", "AutoSum", word("AutoSum"), () => act("autosum"))}
805
+ {control("filldown", "Fill down", word("Fill down"), () => act("fill-down"))}
806
+ {control("fillright", "Fill right", word("Fill right"), () => act("fill-right"))}
807
+ <span className="sheet-ribbon-slot">
808
+ {control("clear", "Clear", <>{word("Clear")}<IconCaret /></>,
809
+ () => setOpen(open === "clear" ? "" : "clear"), false, open === "clear")}
810
+ {open === "clear" && (
811
+ <div className="sheet-ribbon-pop" role="menu" aria-label="Clear">
812
+ {item("Clear contents", () => act("clear-contents"))}
813
+ {item("Clear formats", () => act("clear-formats"))}
814
+ {item("Clear all", () => act("clear-all"))}
815
+ </div>
816
+ )}
817
+ </span>
818
+ </>
819
  ))}
 
 
 
 
 
 
 
 
 
820
  </div>
821
+
822
+ {/* ⭐ INSTRUCTION 8, LITERALLY: Refresh is on the same row as Bold, Italic and
823
+ Underline, and it is not on a white line of its own. It sits outside the scroller so
824
+ a narrow window never carries it off the right edge. */}
825
+ {group("Workbook", (
826
+ <>
827
+ {canImport && control("import", "Import", word("Import"), () => act("import"))}
828
+ {control("refresh", "Refresh", <><IconRefresh />{word("Refresh")}</>,
829
+ () => act("refresh"))}
830
+ </>
831
+ ), " sheet-ribbon-group--utility")}
832
+ </div>
833
+ )}
834
  </div>
835
  );
836
  }
web/src/sheet/RulesDialog.tsx ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------------------------
2
+ // sheet/RulesDialog.tsx β€” W51-T18, the conditional formatting editor and the validation list
3
+ // editor (contract C2, contract C8, rulings R1 and R8).
4
+ //
5
+ // ⭐⭐ TWO DIALOGS IN ONE FILE, AND THAT IS A FENCE DECISION SAID OUT LOUD. This ticket's `files`
6
+ // list names `RulesDialog.tsx` and no second component file, and the validation editor is the
7
+ // same shape as the rules editor wearing one control instead of a list: a base-kit dialog with a
8
+ // body, a refusal line and one commit door. Putting it here keeps `SheetGrid.tsx` from growing a
9
+ // third inline panel; the alternative was widening the ticket's own fence, which a worker may not
10
+ // do. `ValidationDialog` is exported beside `RulesDialog` and neither knows about the other.
11
+ //
12
+ // β›”β›” CONTRACT C8, IN FULL. Both use `ui/ConfirmDialog::ConfirmDialog` as their SHELL: centred at
13
+ // min(420px, 100vw - 32px), Cancel first and focused, Tab trapped, Escape and backdrop cancel,
14
+ // focus returned to the opener. Nothing here writes a second Escape listener; `ConfirmDialog`
15
+ // reaches the ONE arbiter through `useOverlayLayer`, and a `document.addEventListener` added in
16
+ // this file would race it and win or lose on registration order.
17
+ //
18
+ // ⚠ THE SHELL GENUINELY CARRIES A LIST EDITOR, so no second dialog shape was built. Its `body` is
19
+ // a `ReactNode` and its panel scrolls, which is what a hundred rules need; what it does not offer
20
+ // is a wider panel, so each rule is a stacked CARD rather than a wide row. That is the same
21
+ // anatomy the field rail uses for a stacked editor and it joins that rhythm rather than inventing
22
+ // a new one (DESIGN.md 4).
23
+ //
24
+ // ⚠ DESIGN CONTRACT: sentence case, no ALL CAPS chrome, scale tokens only and no literal
25
+ // font-size, colour tokens never hues, inline SVG on `currentColor` and no emoji, 150 ms ease-out
26
+ // on opacity and transform, and no em dash or en dash in any string that reaches a screen.
27
+ // ---------------------------------------------------------------------------------------------
28
+
29
+ import { useCallback, useId, useState } from "react";
30
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
31
+ import {
32
+ RULE_FILLS, RULE_INKS, RULE_OPS, RULE_OP_LABEL,
33
+ addRule, blankRule, moveRule, removeRule, ruleArity, rulesRefusal, updateRule,
34
+ } from "./rules";
35
+ import { listText, parseList } from "./validation";
36
+ import { MAX_SHEET_RULES, MAX_VALIDATION_LIST } from "./types";
37
+ import type { SheetRule, SheetRuleOp } from "./types";
38
+
39
+ export interface RulesDialogProps {
40
+ open: boolean;
41
+ /** The rules the tab carries today. The dialog edits a DRAFT and commits it once. */
42
+ rules: readonly SheetRule[];
43
+ /** The selection's range, which is what a new rule opens with. `A1` when nothing is selected. */
44
+ range: string;
45
+ onCancel: () => void;
46
+ onSave: (rules: SheetRule[]) => void;
47
+ }
48
+
49
+ /**
50
+ * ⚠ THE HOOKS LIVE BELOW THE `open` GATE, exactly as `ConfirmDialog` splits its own. The draft
51
+ * has to START from the tab's rules every time the dialog opens, and a component that stays
52
+ * mounted while closed would keep yesterday's draft and silently offer it back.
53
+ */
54
+ export function RulesDialog({ open, rules, range, onCancel, onSave }: RulesDialogProps) {
55
+ if (!open) return null;
56
+ return <RulesSurface rules={rules} range={range} onCancel={onCancel} onSave={onSave} />;
57
+ }
58
+
59
+ /** The chevron a move button wears. Inline SVG on `currentColor`, never a glyph and never an
60
+ * emoji (DESIGN.md 4). One shape, rotated by CSS, so the pair cannot drift apart. */
61
+ function IconChevron() {
62
+ return (
63
+ <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" className="sheet-rules-icon">
64
+ <path d="M4 10l4-4 4 4" fill="none" stroke="currentColor" strokeWidth="1.6"
65
+ strokeLinecap="round" strokeLinejoin="round" />
66
+ </svg>
67
+ );
68
+ }
69
+
70
+ /** The cross a delete button wears. Same vocabulary as the shortcuts panel's close. */
71
+ function IconRemove() {
72
+ return (
73
+ <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" className="sheet-rules-icon">
74
+ <path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" strokeWidth="1.6"
75
+ strokeLinecap="round" />
76
+ </svg>
77
+ );
78
+ }
79
+
80
+ function RulesSurface({
81
+ rules, range, onCancel, onSave,
82
+ }: Omit<RulesDialogProps, "open">) {
83
+ const [draft, setDraft] = useState<SheetRule[]>(() => (rules ?? []).map((r) => ({ ...r })));
84
+ /** The cap's own refusal, which is raised by an ACT rather than by the draft's shape. */
85
+ const [notice, setNotice] = useState("");
86
+
87
+ const add = useCallback(() => {
88
+ setDraft((current) => {
89
+ const out = addRule(current, blankRule(range));
90
+ setNotice(out.refusal ?? "");
91
+ return out.rules;
92
+ });
93
+ }, [range]);
94
+
95
+ const patch = useCallback((id: string, next: Partial<SheetRule>) => {
96
+ setNotice("");
97
+ setDraft((current) => updateRule(current, id, next));
98
+ }, []);
99
+
100
+ // β›” THE DRAFT'S OWN REFUSAL IS COMPUTED, NEVER STORED. A rule that cannot match is refused at
101
+ // save time from the list itself, so editing a bad rule clears its own complaint rather than
102
+ // leaving a stale sentence on the screen.
103
+ const refusal = notice || rulesRefusal(draft) || "";
104
+
105
+ return (
106
+ <ConfirmDialog
107
+ open
108
+ title="Conditional formatting"
109
+ tone="primary"
110
+ cancelLabel="Cancel"
111
+ confirmLabel="Save rules"
112
+ onCancel={onCancel}
113
+ onConfirm={() => {
114
+ const why = rulesRefusal(draft);
115
+ if (why) {
116
+ setNotice(why);
117
+ return;
118
+ }
119
+ onSave(draft);
120
+ }}
121
+ body={(
122
+ <div className="sheet-rules">
123
+ {/* ⭐⭐ THE ORDER RULE, SAID ON THE SURFACE THAT OWNS IT. Two rules matching one cell is
124
+ ordinary, and a person who cannot see which one wins will reorder at random until
125
+ the sheet looks right. `rules.ts::ruleStyleAt` stops at the first match and takes
126
+ its whole style; this sentence is that behaviour in words. */}
127
+ <p className="sheet-rules-note">
128
+ The first rule that matches a cell paints it, and it paints the whole cell. Move a rule
129
+ up to let it win.
130
+ </p>
131
+
132
+ {draft.length === 0 ? (
133
+ <p className="sheet-rules-empty">No rules yet.</p>
134
+ ) : (
135
+ <ol className="sheet-rules-list">
136
+ {draft.map((rule, index) => (
137
+ <RuleCard
138
+ key={rule.id}
139
+ rule={rule}
140
+ index={index}
141
+ count={draft.length}
142
+ onPatch={patch}
143
+ onMove={(delta) => {
144
+ setNotice("");
145
+ setDraft((current) => moveRule(current, rule.id, delta));
146
+ }}
147
+ onRemove={() => {
148
+ setNotice("");
149
+ setDraft((current) => removeRule(current, rule.id));
150
+ }}
151
+ />
152
+ ))}
153
+ </ol>
154
+ )}
155
+
156
+ <div className="sheet-rules-foot">
157
+ <button type="button" className="sheet-rules-add" onClick={add}>
158
+ Add a rule
159
+ </button>
160
+ <span className="sheet-rules-count">
161
+ {draft.length} of {MAX_SHEET_RULES}
162
+ </span>
163
+ </div>
164
+
165
+ {refusal ? (
166
+ <p className="sheet-rules-refusal" role="alert">{refusal}</p>
167
+ ) : null}
168
+ </div>
169
+ )}
170
+ />
171
+ );
172
+ }
173
+
174
+ interface RuleCardProps {
175
+ rule: SheetRule;
176
+ index: number;
177
+ count: number;
178
+ onPatch: (id: string, next: Partial<SheetRule>) => void;
179
+ onMove: (delta: number) => void;
180
+ onRemove: () => void;
181
+ }
182
+
183
+ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardProps) {
184
+ const ids = useId();
185
+ const arity = ruleArity(rule.op);
186
+ return (
187
+ <li className="sheet-rules-card">
188
+ <div className="sheet-rules-row">
189
+ <span className="sheet-rules-order" aria-hidden="true">{index + 1}</span>
190
+ <label className="sheet-rules-field">
191
+ <span className="sheet-rules-label" id={`${ids}-range`}>Range</span>
192
+ <input
193
+ className="sheet-rules-input"
194
+ type="text"
195
+ value={rule.range}
196
+ aria-labelledby={`${ids}-range`}
197
+ placeholder="B2:D40"
198
+ onChange={(e) => onPatch(rule.id, { range: e.target.value })}
199
+ />
200
+ </label>
201
+ <div className="sheet-rules-moves">
202
+ <button
203
+ type="button"
204
+ className="sheet-rules-move"
205
+ aria-label={`Move rule ${index + 1} up`}
206
+ title="Move up"
207
+ disabled={index === 0}
208
+ onClick={() => onMove(-1)}
209
+ >
210
+ <IconChevron />
211
+ </button>
212
+ <button
213
+ type="button"
214
+ className="sheet-rules-move is-down"
215
+ aria-label={`Move rule ${index + 1} down`}
216
+ title="Move down"
217
+ disabled={index === count - 1}
218
+ onClick={() => onMove(1)}
219
+ >
220
+ <IconChevron />
221
+ </button>
222
+ <button
223
+ type="button"
224
+ className="sheet-rules-remove"
225
+ aria-label={`Delete rule ${index + 1}`}
226
+ title="Delete this rule"
227
+ onClick={onRemove}
228
+ >
229
+ <IconRemove />
230
+ </button>
231
+ </div>
232
+ </div>
233
+
234
+ <div className="sheet-rules-row">
235
+ <label className="sheet-rules-field">
236
+ <span className="sheet-rules-label" id={`${ids}-op`}>Condition</span>
237
+ <select
238
+ className="sheet-rules-select"
239
+ value={rule.op}
240
+ aria-labelledby={`${ids}-op`}
241
+ onChange={(e) => onPatch(rule.id, { op: e.target.value as SheetRuleOp })}
242
+ >
243
+ {RULE_OPS.map((op) => (
244
+ <option key={op} value={op}>{RULE_OP_LABEL[op]}</option>
245
+ ))}
246
+ </select>
247
+ </label>
248
+ {arity >= 1 ? (
249
+ <label className="sheet-rules-field">
250
+ <span className="sheet-rules-label" id={`${ids}-value`}>
251
+ {arity === 2 ? "From" : "Value"}
252
+ </span>
253
+ <input
254
+ className="sheet-rules-input"
255
+ type="text"
256
+ value={String(rule.value ?? "")}
257
+ aria-labelledby={`${ids}-value`}
258
+ onChange={(e) => onPatch(rule.id, { value: e.target.value })}
259
+ />
260
+ </label>
261
+ ) : null}
262
+ {arity === 2 ? (
263
+ <label className="sheet-rules-field">
264
+ <span className="sheet-rules-label" id={`${ids}-value2`}>To</span>
265
+ <input
266
+ className="sheet-rules-input"
267
+ type="text"
268
+ value={String(rule.value2 ?? "")}
269
+ aria-labelledby={`${ids}-value2`}
270
+ onChange={(e) => onPatch(rule.id, { value2: e.target.value })}
271
+ />
272
+ </label>
273
+ ) : null}
274
+ </div>
275
+
276
+ {/* β›” THE PALETTE IS TOKEN NAMES (`rules.ts::RULE_FILLS` / `RULE_INKS`), the ribbon's own,
277
+ so a palette change repaints every rule ever written. `var(--lp-*)` in the swatch is a
278
+ token reference and never a hue (DESIGN.md 3). */}
279
+ <div className="sheet-rules-row sheet-rules-paint">
280
+ <span className="sheet-rules-label">Paint</span>
281
+ <div className="sheet-rules-swatches" role="group" aria-label="Fill colour">
282
+ {RULE_FILLS.map((entry) => (
283
+ <button
284
+ key={entry.token}
285
+ type="button"
286
+ className={"sheet-rules-swatch" + (rule.style?.fill === entry.token ? " is-on" : "")}
287
+ style={{ background: `var(${entry.token})` }}
288
+ aria-label={`${entry.label} fill`}
289
+ aria-pressed={rule.style?.fill === entry.token}
290
+ title={`${entry.label} fill`}
291
+ onClick={() => onPatch(rule.id, {
292
+ style: {
293
+ ...rule.style,
294
+ fill: rule.style?.fill === entry.token ? undefined : entry.token,
295
+ },
296
+ })}
297
+ />
298
+ ))}
299
+ </div>
300
+ <div className="sheet-rules-swatches" role="group" aria-label="Text colour">
301
+ {RULE_INKS.map((entry) => (
302
+ <button
303
+ key={entry.token}
304
+ type="button"
305
+ className={"sheet-rules-swatch is-ink"
306
+ + (rule.style?.color === entry.token ? " is-on" : "")}
307
+ style={{ color: `var(${entry.token})` }}
308
+ aria-label={`${entry.label} text`}
309
+ aria-pressed={rule.style?.color === entry.token}
310
+ title={`${entry.label} text`}
311
+ onClick={() => onPatch(rule.id, {
312
+ style: {
313
+ ...rule.style,
314
+ color: rule.style?.color === entry.token ? undefined : entry.token,
315
+ },
316
+ })}
317
+ >
318
+ A
319
+ </button>
320
+ ))}
321
+ </div>
322
+ <button
323
+ type="button"
324
+ className={"sheet-rules-bold" + (rule.style?.bold ? " is-on" : "")}
325
+ aria-pressed={rule.style?.bold === true}
326
+ aria-label="Bold"
327
+ title="Bold"
328
+ onClick={() => onPatch(rule.id, {
329
+ style: { ...rule.style, bold: rule.style?.bold ? undefined : true },
330
+ })}
331
+ >
332
+ B
333
+ </button>
334
+ </div>
335
+ </li>
336
+ );
337
+ }
338
+
339
+ // ── the validation list editor ────────────────────────────────────────────────────────────────
340
+
341
+ export interface ValidationDialogProps {
342
+ open: boolean;
343
+ /** How many cells the list is about to be set on, so the title can say what it will change. */
344
+ count: number;
345
+ /** The list the anchor cell carries today, or an empty array. */
346
+ list: readonly string[];
347
+ onCancel: () => void;
348
+ onSave: (list: string[]) => void;
349
+ }
350
+
351
+ /** The same `open` split, for the same reason: the draft starts from the cell every time. */
352
+ export function ValidationDialog({ open, count, list, onCancel, onSave }: ValidationDialogProps) {
353
+ if (!open) return null;
354
+ return <ValidationSurface count={count} list={list} onCancel={onCancel} onSave={onSave} />;
355
+ }
356
+
357
+ function ValidationSurface({ count, list, onCancel, onSave }: Omit<ValidationDialogProps, "open">) {
358
+ const [text, setText] = useState(() => listText(list));
359
+ const [notice, setNotice] = useState("");
360
+ const boxId = useId();
361
+ const parsed = parseList(text);
362
+
363
+ return (
364
+ <ConfirmDialog
365
+ open
366
+ title="Values this cell accepts"
367
+ tone="primary"
368
+ cancelLabel="Cancel"
369
+ confirmLabel="Save list"
370
+ onCancel={onCancel}
371
+ onConfirm={() => {
372
+ const out = parseList(text);
373
+ if (out.refusal) {
374
+ setNotice(out.refusal);
375
+ return;
376
+ }
377
+ onSave(out.list);
378
+ }}
379
+ body={(
380
+ <div className="sheet-validation">
381
+ <label className="sheet-validation-label" htmlFor={boxId}>
382
+ One value per line. {count === 1 ? "This cell" : `These ${count} cells`} will offer them
383
+ as a dropdown and refuse anything else.
384
+ </label>
385
+ <textarea
386
+ id={boxId}
387
+ className="sheet-validation-box"
388
+ rows={8}
389
+ spellCheck={false}
390
+ autoFocus
391
+ value={text}
392
+ placeholder={"Royal\nFisch"}
393
+ onChange={(e) => { setNotice(""); setText(e.target.value); }}
394
+ />
395
+ <p className="sheet-validation-count">
396
+ {parsed.refusal ? "" : `${parsed.list.length} of ${MAX_VALIDATION_LIST} values.`}
397
+ {parsed.list.length === 0 && !parsed.refusal
398
+ ? " Saving an empty list removes the dropdown."
399
+ : ""}
400
+ </p>
401
+ {notice || parsed.refusal ? (
402
+ <p className="sheet-validation-refusal" role="alert">{notice || parsed.refusal}</p>
403
+ ) : null}
404
+ </div>
405
+ )}
406
+ />
407
+ );
408
+ }
web/src/sheet/SheetGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/sheet/SheetPage.tsx CHANGED
@@ -35,21 +35,48 @@
35
  // is placed where a page-level act belongs.
36
  // ---------------------------------------------------------------------------
37
 
38
- import { useCallback, useEffect, useRef, useState } from "react";
 
39
  import "../styles/wave49/sheet.css";
40
  import "../styles/wave50/sheet.css";
 
 
 
 
 
 
 
 
 
41
  import { SHEET_VIEW_KIND } from "./index";
42
  import BindingEditor from "./BindingEditor";
43
  import DrillModal from "./DrillModal";
44
  import FormulaBar from "./FormulaBar";
45
- import SheetGrid from "./SheetGrid";
 
46
  import SheetRail from "./SheetRail";
47
  import type { RailStrata } from "./SheetRail";
48
  import {
49
- createWorkbook, deleteWorkbook, readIndex, readWorkbook, refreshWorkbook, writeIndex,
50
- writeWorkbook,
51
  } from "./sheetApi";
 
 
 
 
 
 
52
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
 
 
 
 
 
 
 
 
 
 
53
  import {
54
  addTab, applyStructure, bandBoundLabel, boundCellsInBand, cellAt, convertToLiteral,
55
  drillAffordance, emptyHistory, growSheet, moveTab, pushHistory, redoHistory, removeTab,
@@ -58,7 +85,43 @@ import {
58
  } from "./sheetState";
59
  import type { SheetHistory, StructureOp } from "./sheetState";
60
  import { emptyIndex } from "./types";
61
- import type { Cell, IndexRepair, SheetTab, Workbook, WorkbookIndex } from "./types";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  /**
64
  * The main area while a workbook is opening: the DATA MODULE'S OWN SPINNER, markup for markup.
@@ -68,6 +131,16 @@ import type { Cell, IndexRepair, SheetTab, Workbook, WorkbookIndex } from "./typ
68
  * one product. `lp-spin--lg` is the 20px mark, which is the one sized for a surface with nothing
69
  * else on it; the 14px default reads as dust on an empty panel.
70
  */
 
 
 
 
 
 
 
 
 
 
71
  function SheetLoading() {
72
  return (
73
  <div className="cg-loading">
@@ -120,11 +193,80 @@ function repairSentence(repairs: readonly IndexRepair[] | undefined): string {
120
  + "read as a folder or a filing, so they were left out.";
121
  }
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  export default function SheetPage() {
124
  const [book, setBook] = useState<Workbook | null>(null);
125
  const [tabId, setTabId] = useState<string>("");
126
  const [busy, setBusy] = useState(false);
127
  const [notice, setNotice] = useState("");
 
 
 
 
 
 
 
 
128
  /**
129
  * β›” THE THIRD STATE (W50-T17). See the header: `book === null` cannot distinguish "opening"
130
  * from "could not open", and a spinner shown for the second one never stops.
@@ -132,8 +274,15 @@ export default function SheetPage() {
132
  const [loading, setLoading] = useState(true);
133
  /** A LATER workbook switch. The main area waits; the rail keeps the list it is showing. */
134
  const [opening, setOpening] = useState(false);
135
- /** The rail's own document: workbook rows, folders, placements and stars. */
136
- const [index, setIndex] = useState<WorkbookIndex>(emptyIndex);
 
 
 
 
 
 
 
137
  /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */
138
  const [drillAt, setDrillAt] = useState("");
139
  /** The address whose binding is being edited, or "" for none (W49-T06). */
@@ -186,6 +335,36 @@ export default function SheetPage() {
186
  /** Bumped by every local edit, so a save knows whether the tree moved under it. */
187
  const editSeqRef = useRef(0);
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  /** Write the ref and the state together. Nothing in this file calls `setBook` on its own. */
190
  const applyLocal = useCallback((next: Workbook) => {
191
  bookRef.current = next;
@@ -194,6 +373,118 @@ export default function SheetPage() {
194
 
195
  useEffect(() => { tabIdRef.current = tabId; }, [tabId]);
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  // ⭐ THE FIRST WORKBOOK IS OPENED, OR CREATED IF THERE IS NONE. An empty rail row that does
198
  // nothing until someone finds a create button is the shape this module is trying not to be.
199
  //
@@ -216,7 +507,10 @@ export default function SheetPage() {
216
  }
217
  setIndex(got.value);
218
  const first = got.value.workbooks[0];
219
- const opened = first ? await readWorkbook(first.id) : await createWorkbook("Workbook");
 
 
 
220
  if (!live) return;
221
  if (!opened.ok) {
222
  setNotice(opened.message);
@@ -225,7 +519,15 @@ export default function SheetPage() {
225
  }
226
  bookRef.current = opened.value;
227
  setBook(opened.value);
228
- setTabId(opened.value.sheets[0]?.id ?? "");
 
 
 
 
 
 
 
 
229
  if (!first) {
230
  // A workbook made to fill an empty module still has to appear in the rail, and the
231
  // index was read BEFORE it existed.
@@ -263,6 +565,7 @@ export default function SheetPage() {
263
  if (!book) return;
264
  setBusy(true);
265
  setNotice("");
 
266
  const got = await refreshWorkbook(book.id);
267
  setBusy(false);
268
  if (!got.ok) {
@@ -273,8 +576,18 @@ export default function SheetPage() {
273
  // rather than left pointing at cells that no longer hold the values it recorded.
274
  historyRef.current = emptyHistory();
275
  editSeqRef.current += 1;
276
- applyLocal(got.value);
277
- }, [applyLocal, book]);
 
 
 
 
 
 
 
 
 
 
278
 
279
  // ⭐ R20 IS DECIDED HERE, NOT INSIDE THE EDITOR. `editIntent` says whether typing over this cell
280
  // is an ordinary edit or a CONVERSION that needs confirming, and the conversion path is the one
@@ -285,7 +598,110 @@ export default function SheetPage() {
285
  }, []);
286
 
287
  /**
288
- * Send the workbook the ref currently holds, behind whatever save is already in flight.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  *
290
  * ⚠ THE SERVER'S ANSWER IS ADOPTED ONLY WHEN NOTHING MOVED WHILE IT WAS AWAY. If more
291
  * keystrokes landed during the round trip, taking `saved.value` wholesale would paint the
@@ -293,39 +709,158 @@ export default function SheetPage() {
293
  * staying in the ref. In that case only `rev` and `updated_at` are taken, which is the one
294
  * thing the client could not have known. [[a-rebuilt-value-drops-its-new-field]]
295
  */
296
- const queueSave = useCallback(() => {
297
- saveChainRef.current = saveChainRef.current.then(async () => {
298
- const current = bookRef.current;
299
- if (!current) return;
300
- const seq = editSeqRef.current;
301
- const saved = await writeWorkbook(current.id, {
302
- name: current.name, sheets: current.sheets, rev: current.rev,
303
- });
304
- if (!saved.ok) {
305
- // β›” A STALE REV IS NOT A DEAD SESSION. Leaving the local `rev` behind would make every
306
- // later save stale too, so editing would be over until someone reloaded the page. The
307
- // workbook is re-read instead, and the reader is told the edit did not land.
308
- if (saved.code === "workbook_revision_stale") {
309
- const fresh = await readWorkbook(current.id);
310
- if (fresh.ok) {
311
- historyRef.current = emptyHistory();
312
- editSeqRef.current += 1;
313
- applyLocal(fresh.value);
314
- }
315
- setNotice("This workbook changed somewhere else, so that edit was not saved. "
316
- + "The sheet has been reloaded with the other change.");
317
- return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  }
319
- setNotice(saved.message);
 
 
 
 
320
  return;
321
  }
322
- if (editSeqRef.current === seq) {
323
- applyLocal(saved.value);
324
- } else if (bookRef.current) {
325
- applyLocal({ ...bookRef.current, rev: saved.value.rev, updated_at: saved.value.updated_at });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  }
 
327
  });
328
- }, [applyLocal]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
 
330
  /**
331
  * ⭐ THE ONE COMMIT DOOR. Every edit the grid can make arrives here: a typed cell, a paste, a
@@ -342,9 +877,14 @@ export default function SheetPage() {
342
  historyRef.current = pushHistory(historyRef.current, base.sheets);
343
  editSeqRef.current += 1;
344
  setNotice("");
 
 
 
 
 
345
  applyLocal(withCells(base, target, edits));
346
  queueSave();
347
- }, [applyLocal, queueSave]);
348
 
349
  // ═══════════════════════════════════════════════════════════════════════════════════════════
350
  // ⭐⭐ W50-T20 β€” STRUCTURE, THROUGH THE SAME DOOR AS A KEYSTROKE.
@@ -366,6 +906,12 @@ export default function SheetPage() {
366
  historyRef.current = pushHistory(historyRef.current, base.sheets);
367
  editSeqRef.current += 1;
368
  setNotice("");
 
 
 
 
 
 
369
  applyLocal({ ...base, sheets });
370
  queueSave();
371
  }, [applyLocal, queueSave]);
@@ -423,6 +969,9 @@ export default function SheetPage() {
423
  if (!base) return;
424
  const made = addTab(base);
425
  commitSheets(made.sheets);
 
 
 
426
  setTabId(made.id);
427
  }, [commitSheets]);
428
 
@@ -489,6 +1038,10 @@ export default function SheetPage() {
489
  historyRef.current = step.history;
490
  editSeqRef.current += 1;
491
  setNotice("");
 
 
 
 
492
  applyLocal({ ...base, sheets: step.sheets });
493
  queueSave();
494
  }, [applyLocal, queueSave]);
@@ -501,6 +1054,8 @@ export default function SheetPage() {
501
  historyRef.current = step.history;
502
  editSeqRef.current += 1;
503
  setNotice("");
 
 
504
  applyLocal({ ...base, sheets: step.sheets });
505
  queueSave();
506
  }, [applyLocal, queueSave]);
@@ -568,28 +1123,43 @@ export default function SheetPage() {
568
  if (got.ok) setIndex(got.value);
569
  }, []);
570
 
571
- const adoptWorkbook = useCallback((next: Workbook) => {
 
 
 
 
 
 
 
572
  // A different workbook is a different tree, so the undo stack is dropped rather than left
573
  // pointing at cells that no longer hold the values it recorded.
574
  historyRef.current = emptyHistory();
575
  editSeqRef.current += 1;
 
 
 
 
576
  applyLocal(next);
577
  setTabId(next.sheets[0]?.id ?? "");
578
- }, [applyLocal]);
579
 
580
  const openWorkbook = useCallback(async (id: string) => {
581
  if (id === bookRef.current?.id) return;
582
  setOpening(true);
583
  setNotice("");
584
- const got = await readWorkbook(id);
 
 
585
  if (!got.ok) {
586
  setNotice(got.message);
587
  setOpening(false);
588
  return;
589
  }
590
- adoptWorkbook(got.value);
 
 
591
  setOpening(false);
592
- }, [adoptWorkbook]);
593
 
594
  /** R2's create door: made and OPENED in one act, with no name step in between. */
595
  const createAndOpen = useCallback(async () => {
@@ -601,7 +1171,7 @@ export default function SheetPage() {
601
  setOpening(false);
602
  return;
603
  }
604
- adoptWorkbook(made.value);
605
  await refreshIndex();
606
  setOpening(false);
607
  }, [adoptWorkbook, refreshIndex]);
@@ -634,7 +1204,7 @@ export default function SheetPage() {
634
  setOpening(false);
635
  return;
636
  }
637
- adoptWorkbook(filled.value);
638
  await refreshIndex();
639
  setOpening(false);
640
  }, [adoptWorkbook, refreshIndex]);
@@ -648,8 +1218,15 @@ export default function SheetPage() {
648
  setNotice("");
649
  if (bookRef.current && bookRef.current.id === id) {
650
  applyLocal({ ...bookRef.current, name });
 
 
 
 
 
 
 
651
  queueSave();
652
- await saveChainRef.current;
653
  await refreshIndex();
654
  return;
655
  }
@@ -666,7 +1243,7 @@ export default function SheetPage() {
666
  return;
667
  }
668
  await refreshIndex();
669
- }, [applyLocal, queueSave, refreshIndex]);
670
 
671
  const removeWorkbook = useCallback(async (id: string) => {
672
  setNotice("");
@@ -689,6 +1266,9 @@ export default function SheetPage() {
689
  await openWorkbook(next.id);
690
  }, [openWorkbook]);
691
 
 
 
 
692
  /**
693
  * The ONE door for every folder, placement and star change.
694
  *
@@ -705,7 +1285,19 @@ export default function SheetPage() {
705
  itemFolders: next.itemFolders,
706
  starred: next.starred,
707
  }));
708
- const saved = await writeIndex(next);
 
 
 
 
 
 
 
 
 
 
 
 
709
  if (!saved.ok) {
710
  const rows = await readIndex();
711
  if (rows.ok) setIndex(rows.value);
@@ -715,6 +1307,183 @@ export default function SheetPage() {
715
  setIndex(saved.value);
716
  const sentence = repairSentence(saved.value.repairs);
717
  if (sentence) setNotice(sentence);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718
  }, []);
719
 
720
  const tab = book?.sheets.find((t) => t.id === tabId) ?? book?.sheets[0] ?? null;
@@ -737,9 +1506,36 @@ export default function SheetPage() {
737
  onRenameWorkbook={renameWorkbook}
738
  onDuplicateWorkbook={duplicateWorkbook}
739
  onDeleteWorkbook={removeWorkbook}
 
740
  onStrataChange={saveStrata}
 
 
741
  />
742
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743
  {/* β›”β›” THE LOADING BODY IS ITS OWN BRANCH AND CARRIES NO SENTENCE. The owner named the
744
  defect: "the 'opening your workbook' loading screen must be the Data module's loading
745
  animation". A line of prose where the rest of the app shows a spinner is the thing
@@ -751,40 +1547,34 @@ export default function SheetPage() {
751
  </div>
752
  ) : (
753
  <div className="sheet-body">
754
- <div className="sheet-toolbar" role="toolbar" aria-label="Sheet">
755
- <h1 className="sheet-title">{book?.name ?? "Sheet"}</h1>
756
- <div className="sheet-toolbar-right">
757
- {book?.refreshed_at && (
758
- <span className="sheet-stamp">Refreshed {book.refreshed_at.slice(0, 16)}</span>
759
- )}
760
- <button
761
- type="button"
762
- className="sheet-refresh"
763
- onClick={onRefresh}
764
- disabled={busy || !book}
765
- >
766
- {busy ? "Refreshing" : "Refresh"}
767
- </button>
768
- </div>
769
- </div>
770
 
 
 
 
 
 
 
 
 
771
  {notice && <p className="sheet-notice">{notice}</p>}
772
 
773
- {/* β›”β›” THE BAR SITS ABOVE THE GRID AND MUST NOT STEAL ITS HEIGHT. `.sheet-body` is a flex
774
- COLUMN and `.sheet-grid-wrap` is its `flex: 1 1 auto` child; a new sibling that did not
775
- declare `flex: 0 0 auto` would be shrunk by a tall grid, and the reverse mistake is
776
- worse: glide's infinite scroller renders NO CANVAS AT ALL at a measured height of zero,
777
- so a bar that ate the remaining space would DELETE the grid rather than clip it. See
778
- `styles/wave49/sheet.css`'s own note on that failure, and `.sheet-fx`'s rule. */}
779
- {book && tab && (
780
- <FormulaBar
781
- addr={barAddr}
782
- cell={cellAt(tab, barAddr)}
783
- disabled={busy}
784
- onAddrChange={setBarAddr}
785
- onCommit={commitCells}
786
- />
787
- )}
788
 
789
  {/* ⭐ THREE OUTCOMES, IN THE ORDER THEY CAN HAPPEN. A workbook is switching, so the
790
  spinner again; a workbook is open, so the grid; nothing opened and `loading` is over,
@@ -813,6 +1603,25 @@ export default function SheetPage() {
813
  onGrow={onGrow}
814
  onFreeze={onFreeze}
815
  onColumnWidth={onColumnWidth}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816
  />
817
  ) : (
818
  <div className="sheet-placeholder">
@@ -842,7 +1651,7 @@ export default function SheetPage() {
842
  type="button"
843
  className={"sheet-ribbon-btn" + (t.id === (tab?.id ?? "") ? " is-on" : "")}
844
  aria-pressed={t.id === (tab?.id ?? "")}
845
- onClick={() => setTabId(t.id)}
846
  onDoubleClick={() => setTabRename({ id: t.id, name: t.name })}
847
  // ⚠ THE ELEMENT IS CAPTURED BEFORE THE UPDATER RUNS. Reading `e.currentTarget`
848
  // inside a state updater is how this app lost an anchor before
@@ -850,7 +1659,7 @@ export default function SheetPage() {
850
  onContextMenu={(e) => {
851
  e.preventDefault();
852
  const el = e.currentTarget;
853
- setTabId(t.id);
854
  setTabMenu({ id: t.id, el });
855
  }}
856
  title="Click to open. Double click to rename. Right click for more."
@@ -954,26 +1763,29 @@ export default function SheetPage() {
954
  </div>
955
  )}
956
 
957
- {tabDelete && (
958
- <div className="sheet-drill-error" role="dialog" aria-label="Delete this sheet">
959
- <p className="sheet-binding-title">Delete {tabDelete.name}?</p>
960
- <p className="sheet-placeholder-note">
961
- {tabDelete.cells === 1
962
- ? "This sheet holds 1 value, and deleting it removes that value."
963
- : `This sheet holds ${tabDelete.cells} values, and deleting it removes them.`}
964
- {" "}
965
- Any formula on another sheet that points here stops resolving.
966
- </p>
967
- <div className="sheet-binding-actions">
968
- <button type="button" className="sheet-refresh" onClick={() => setTabDelete(null)}>
969
- Cancel
970
- </button>
971
- <button type="button" className="sheet-refresh" onClick={confirmRemoveTab}>
972
- Delete
973
- </button>
974
- </div>
975
- </div>
976
- )}
 
 
 
977
 
978
  {/* β›” R18's SECOND HALF, AND THE TICKET NAMES IT: a delete that would drop a BOUND cell asks
979
  first. A bound cell is the one kind that cannot be typed back in from memory, because
@@ -996,7 +1808,19 @@ export default function SheetPage() {
996
  )}
997
 
998
  {book && editAt && (
 
 
 
 
 
 
 
 
 
 
 
999
  <BindingEditor
 
1000
  workbookId={book.id}
1001
  addr={editAt}
1002
  databases={databases}
 
35
  // is placed where a page-level act belongs.
36
  // ---------------------------------------------------------------------------
37
 
38
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
39
+ import type { ReactNode } from "react";
40
  import "../styles/wave49/sheet.css";
41
  import "../styles/wave50/sheet.css";
42
+ // β›”β›” W51-T09 β€” THE LAUNCHER'S OWN STYLESHEET, AND IT IS NOT OPTIONAL. `.cg-chat-toggle` and
43
+ // `.cg-chat-dock` live in `customer-grid/chatDock.css`, which until this ticket ONLY
44
+ // `CustomerGrid.tsx` imported. On a direct load of `#/sheet` that chunk is never fetched, so the
45
+ // rail's new Ask button would have rendered in native UA chrome: the "1.78px outset black border
46
+ // over rgb(240,240,240)" that `styles/wave46/rail-select.css` documents as the owner's "big square
47
+ // outline". Nothing catches that β€” not `tsc`, not a text-presence gate, not the parity harness,
48
+ // which measures five OTHER classes. Importing the sheet is the fix; re-declaring the class in a
49
+ // lane sheet would fight the cascade the first time somebody visits Data before the Sheet.
50
+ import "../customer-grid/chatDock.css";
51
  import { SHEET_VIEW_KIND } from "./index";
52
  import BindingEditor from "./BindingEditor";
53
  import DrillModal from "./DrillModal";
54
  import FormulaBar from "./FormulaBar";
55
+ import SheetGridBase from "./SheetGrid";
56
+ import type { SheetGridProps } from "./SheetGrid";
57
  import SheetRail from "./SheetRail";
58
  import type { RailStrata } from "./SheetRail";
59
  import {
60
+ createWorkbook, deleteWorkbook, patchTabCells, readIndex, readTab, readTabMeta, readWorkbook,
61
+ refreshWorkbook, writeIndex, writeWorkbook,
62
  } from "./sheetApi";
63
+ import type { SheetIndex } from "./sheetApi";
64
+ // β›”β›” W51-T10 / R6 β€” THE ONE CONFIRM DIALOG (contract C8). The sheet-delete prompt below used to
65
+ // be a hand-rolled `.sheet-drill-error` panel: no focus trap, no Escape, no backdrop, and its two
66
+ // buttons wore the same quiet `.sheet-refresh` chrome, so the destructive one was indistinguishable
67
+ // from Cancel. It is the same promise the workbook delete makes, so it is the same shape.
68
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
69
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
70
+ // β›” THE `.tsx` IS LOAD-BEARING. A sibling `customer-grid/gridChat.ts` exists, `./GridChat`
71
+ // resolves to IT under bundler resolution, and `tsc` then reports TS1261 plus "has no default
72
+ // export" β€” an error about the wrong file. `allowImportingTsExtensions` is on for exactly this.
73
+ import GridChat from "../customer-grid/GridChat.tsx";
74
+ import { schemaSentence } from "../customer-grid/gridChat";
75
+ import type { GridChatAnswer, GridChatField } from "../customer-grid/gridChat";
76
+ import { fetchTableWindow, fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
77
+ import type { SurfaceScope } from "../customer-grid/apiBridge";
78
+ import { CUSTOMER_TOPIC, PRODUCT_TOPIC } from "../customer-grid/types";
79
+ import type { TopicConfig } from "../customer-grid/types";
80
  import {
81
  addTab, applyStructure, bandBoundLabel, boundCellsInBand, cellAt, convertToLiteral,
82
  drillAffordance, emptyHistory, growSheet, moveTab, pushHistory, redoHistory, removeTab,
 
85
  } from "./sheetState";
86
  import type { SheetHistory, StructureOp } from "./sheetState";
87
  import { emptyIndex } from "./types";
88
+ import type { Cell, IndexRepair, SheetTab, Workbook } from "./types";
89
+
90
+ /**
91
+ * ⭐⭐ W51-T08 / CONTRACT C1 β€” THE FOUR SEAM PROPS, TYPED HERE BECAUSE `SheetGrid.tsx` IS LANE E'S.
92
+ *
93
+ * C1 says the ribbon lives inside `SheetGrid` and is fed from this page: the formula bar arrives
94
+ * as a NODE it slots under the ribbon, and Refresh, Ctrl+S and Import arrive as handlers. Lane E
95
+ * declares those members on `SheetGridProps`; this lane may not edit that file, so the call site
96
+ * would be an unknown-attribute error until E lands.
97
+ *
98
+ * β›” THIS IS AN ASSIGNMENT, NOT A CAST, AND THAT IS THE WHOLE POINT. A parameter is contravariant,
99
+ * so a function taking `SheetGridProps` is assignable to one taking `SheetGridProps & Seams` with
100
+ * no `as` anywhere. Nothing is silenced: every OTHER prop is still checked against E's real type,
101
+ * a missing `onCommit` is still an error, and a `formulaBar` of the wrong TYPE is still an error.
102
+ * `as any` on the element would have thrown all of that away to buy the same three props.
103
+ *
104
+ * ⭐ AND IT SURVIVES THE COMBINE UNTOUCHED. Once E declares the three members, the intersection is
105
+ * a no-op and the call typechecks against the REAL props; if E declares one with a DIFFERENT
106
+ * signature the intersection makes that a `tsc` error at the merge rather than a silent mismatch,
107
+ * which is the failure this shape is worth having for. Collapsing it back is two lines whenever
108
+ * someone wants to: rename the import to `SheetGrid` and delete this block.
109
+ *
110
+ * ⚠ THE LOCAL IS NAMED `SheetGrid` ON PURPOSE. The JSX stays `<SheetGrid …>`, so `verify_wiring`'s
111
+ * W50-T17 row and every other reader keeps matching without being edited around a shim.
112
+ */
113
+ type SheetGridSeams = {
114
+ /** C1: rendered between the ribbon and the canvas. This page still renders it above the grid
115
+ * as well, until W51-T14 deletes that interim render on the merged tree. */
116
+ formulaBar?: ReactNode;
117
+ /** C1: Ctrl+S inside the grid, wired to this page's own save queue. */
118
+ onSaveNow?: () => void;
119
+ /** C1: the ribbon's Import door. W51-T13 builds what it opens. */
120
+ onOpenImport?: () => void;
121
+ };
122
+
123
+ const SheetGrid: (props: SheetGridProps & SheetGridSeams) => ReturnType<typeof SheetGridBase> =
124
+ SheetGridBase;
125
 
126
  /**
127
  * The main area while a workbook is opening: the DATA MODULE'S OWN SPINNER, markup for markup.
 
131
  * one product. `lp-spin--lg` is the 20px mark, which is the one sized for a surface with nothing
132
  * else on it; the 14px default reads as dust on an empty panel.
133
  */
134
+ /**
135
+ * W51-T09 / R12 β€” the topic databases a cell binding may name, taken from the SHARED constants.
136
+ *
137
+ * β›” NOT A HAND-WRITTEN MAP. `customer_data -> "customer"` is already declared once, in
138
+ * `customer-grid/types.ts`, and `BindingEditor.tsx` reads the same pair through its own `scopeOf`.
139
+ * A third spelling here is a third thing to keep in step, and the day a topic is renamed the
140
+ * chat would quietly read the wrong workspace rather than fail.
141
+ */
142
+ const CHAT_TOPICS: TopicConfig[] = [CUSTOMER_TOPIC, PRODUCT_TOPIC];
143
+
144
  function SheetLoading() {
145
  return (
146
  <div className="cg-loading">
 
193
  + "read as a folder or a filing, so they were left out.";
194
  }
195
 
196
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
197
+ // ⭐⭐ W51-T11 / RULING R4 β€” THE SAVE MODEL: A RANGE PER COMMIT, ONE TAB AT A TIME.
198
+ //
199
+ // R4, verbatim: *"the client saves a cell-range PATCH per commit with `rev`, opens one tab at a
200
+ // time; recalc runs only on Refresh or a formula commit and its time is shown."*
201
+ //
202
+ // β›”β›” THE ONE THING THAT COULD HAVE DESTROYED DATA, AND IT IS THE REASON `tabLoadedRef` EXISTS.
203
+ // Opening with `?tabs=meta` means the in-memory workbook holds tabs with EMPTY `cells` maps for
204
+ // every tab nobody has looked at. Today's whole-workbook PUT sends `current.sheets` verbatim, so
205
+ // a single fallback save after a lazy open would have written those empty maps over every unread
206
+ // tab and deleted them, with every gate green and nothing thrown. So the PUT is fenced: it may
207
+ // only run once every tab is in memory, and `ensureTabs` is what gets it there.
208
+ //
209
+ // β›” AND THE PUT FALLBACK IS THE LIVE PATH ON THIS BRANCH, not a theoretical branch. None of
210
+ // contract C3's three routes are served yet, so on this tree the probe fails on the first save,
211
+ // the status line reads "Saving the whole workbook", and everything above is what makes that
212
+ // safe rather than destructive.
213
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
214
+
215
+ /**
216
+ * How long a burst of keystrokes is allowed to gather before it is sent.
217
+ *
218
+ * ⚠ THE TICKET'S `how:` LINE SAYS THE DIRTY SET "DRAINS ON A DEBOUNCE" AND THERE WAS NO DEBOUNCE.
219
+ * `queueSave` used to send the entire workbook synchronously on every commit, undo, redo, binding
220
+ * save and structure op, serialised only by promise chaining. Ten characters typed into ten cells
221
+ * were ten whole-workbook PUTs. This is the timer that was assumed to exist.
222
+ *
223
+ * ⭐ 600 ms IS CHOSEN AGAINST THE TYPING RHYTHM, not picked round. A commit in this grid is an
224
+ * Enter or a Tab, so the gap between two commits is a person moving to the next cell and typing
225
+ * it; shorter than about half a second and a steady typist still pays a request per cell, much
226
+ * longer and a save feels detached from the edit that caused it. Ctrl+S bypasses it entirely.
227
+ */
228
+ const SAVE_DEBOUNCE_MS = 600;
229
+
230
+ /** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */
231
+ const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`;
232
+
233
+ /**
234
+ * Does this tab carry anything an undo could destroy?
235
+ *
236
+ * ⭐ THIS IS THE TEST BEHIND THE `historyRef` DECISION BELOW, and it is why the decision is not
237
+ * simply "always drop the stack".
238
+ */
239
+ const tabHoldsCells = (tab: SheetTab | null | undefined): boolean =>
240
+ Object.keys(tab?.cells ?? {}).length > 0;
241
+
242
+ /**
243
+ * The revision to send with a cell PATCH.
244
+ *
245
+ * ⚠ C3 SAYS `rev` AND DOES NOT SAY WHOSE. The contract's 409 is `sheet_revision_stale`, which
246
+ * reads as a per-SHEET revision, but `SheetTab` (lane E's type) declares no `rev` and today's
247
+ * server stamps one only on the workbook. So the tab's own is used the moment lane D starts
248
+ * stamping one, and the workbook's is used until then. Booked as a handover, not guessed at
249
+ * silently: if lane D lands a per-tab revision this keeps working, and if it keys the guard on
250
+ * the workbook's this keeps working too.
251
+ */
252
+ const tabRevOf = (tab: SheetTab, book: Workbook): number => {
253
+ const own = (tab as { rev?: unknown }).rev;
254
+ return typeof own === "number" ? own : book.rev;
255
+ };
256
+
257
  export default function SheetPage() {
258
  const [book, setBook] = useState<Workbook | null>(null);
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.
 
274
  const [loading, setLoading] = useState(true);
275
  /** A LATER workbook switch. The main area waits; the rail keeps the list it is showing. */
276
  const [opening, setOpening] = useState(false);
277
+ /**
278
+ * The rail's own document: workbook rows, folders, placements and stars.
279
+ *
280
+ * ⚠ `SheetIndex` (W51-T10) rather than `WorkbookIndex`, and the difference is two OPTIONAL
281
+ * members the server does not send yet: contract C5's `sharedWithMe` and the index's own `rev`.
282
+ * `sheet/types.ts` is another lane's file this wave, so the widening lives in `sheetApi.ts`;
283
+ * `emptyIndex()` stays assignable because both members are optional.
284
+ */
285
+ const [index, setIndex] = useState<SheetIndex>(emptyIndex);
286
  /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */
287
  const [drillAt, setDrillAt] = useState("");
288
  /** The address whose binding is being edited, or "" for none (W49-T06). */
 
335
  /** Bumped by every local edit, so a save knows whether the tree moved under it. */
336
  const editSeqRef = useRef(0);
337
 
338
+ // ── W51-T11's five refs ────────────────────────────────────────────────────────────────────
339
+
340
+ /**
341
+ * THE DIRTY SET: tab id -> the addresses whose cells changed since the last drain.
342
+ *
343
+ * ⭐ ADDRESSES, NOT CELLS. The VALUE is read out of the workbook at send time, so two edits to
344
+ * the same address inside one debounce window send one cell and not two, and the cell that is
345
+ * sent is the one on screen rather than the one that was on screen when the timer started.
346
+ */
347
+ const dirtyRef = useRef<Map<string, Set<string>>>(new Map());
348
+ /** Set by anything a cell PATCH cannot express: a row, a column, a tab, a workbook name. */
349
+ const structureDirtyRef = useRef(false);
350
+ /**
351
+ * The probe's answer, remembered for the session. C3: *"The client probes PATCH once per
352
+ * session and falls back to PUT on 404, saying so in the status line."*
353
+ *
354
+ * β›” `"put"` IS ONE WAY. Once a save has fallen back, it does not probe again on the next
355
+ * keystroke: a route that is not deployed does not appear mid session, and re-probing would
356
+ * spend a failed request per commit for the whole session.
357
+ */
358
+ const patchModeRef = useRef<"unknown" | "patch" | "put">("unknown");
359
+ /** The same answer for the per-tab READ, learned the same way and kept for the same reason. */
360
+ const tabRouteRef = useRef<"unknown" | "yes" | "no">("unknown");
361
+ /** Which tabs have had their cells read. Keyed `workbookId:tabId`, so a switch cannot reuse. */
362
+ const tabLoadedRef = useRef<Set<string>>(new Set());
363
+ /** The pending debounce, or null when nothing is waiting. */
364
+ const saveTimerRef = useRef<number | null>(null);
365
+ /** The current drain, so the unmount flush can call it without re-arming its own effect. */
366
+ const drainRef = useRef<() => void>(() => {});
367
+
368
  /** Write the ref and the state together. Nothing in this file calls `setBook` on its own. */
369
  const applyLocal = useCallback((next: Workbook) => {
370
  bookRef.current = next;
 
373
 
374
  useEffect(() => { tabIdRef.current = tabId; }, [tabId]);
375
 
376
+ const markDirty = useCallback((tabId2: string, addr: string) => {
377
+ const held = dirtyRef.current.get(tabId2) ?? new Set<string>();
378
+ held.add(addr);
379
+ dirtyRef.current.set(tabId2, held);
380
+ }, []);
381
+
382
+ /** Everything in this workbook is in memory: a full read, a refresh, or a workbook just made. */
383
+ const markAllLoaded = useCallback((wb: Workbook) => {
384
+ for (const t of wb.sheets) tabLoadedRef.current.add(tabKeyOf(wb.id, t.id));
385
+ }, []);
386
+
387
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
388
+ // β›”β›” THE `historyRef` DECISION, WHICH THE TICKET ASKS TO BE STATED IN A COMMENT.
389
+ //
390
+ // `pushHistory` snapshots the WHOLE `sheets` array, so every recorded step describes a tree in
391
+ // which an unloaded tab has NO CELLS. Merge that tab's real cells in afterwards and the stack
392
+ // is now lying about it: one Ctrl+Z would restore the empty version, and because undo SAVES,
393
+ // the emptiness would then be written. That is silent data loss caused by a keystroke that is
394
+ // supposed to be the safe one.
395
+ //
396
+ // ⭐ SO: A LAZY LOAD DROPS THE UNDO STACK, BUT ONLY WHEN THE TAB IT LOADED HOLDS SOMETHING.
397
+ // Loading an empty tab changes nothing an undo could get wrong, and dropping the stack on every
398
+ // tab switch would punish the ordinary case for the rare one. What the narrow rule still gives
399
+ // up is a tab's GEOMETRY (its `cols`, `rows` and dragged column widths): an undo can put those
400
+ // back to the defaults the placeholder carried. That is recoverable by dragging, it is not
401
+ // data, and it is written down here rather than hidden. Booked as a follow-up.
402
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
403
+
404
+ const mergeTab = useCallback((workbookId: string, next: SheetTab) => {
405
+ const live = bookRef.current;
406
+ if (!live || live.id !== workbookId) return;
407
+ tabLoadedRef.current.add(tabKeyOf(workbookId, next.id));
408
+ if (tabHoldsCells(next)) historyRef.current = emptyHistory();
409
+ editSeqRef.current += 1;
410
+ applyLocal({
411
+ ...live,
412
+ sheets: live.sheets.map((t) => (t.id === next.id ? { ...t, ...next } : t)),
413
+ });
414
+ }, [applyLocal]);
415
+
416
+ /**
417
+ * ⭐⭐ MAKE SURE THE NAMED TABS ARE IN MEMORY, AND ANSWER WHETHER THEY NOW ARE.
418
+ *
419
+ * This is the lazy fetch, its cache and its repair path in one door, because all three have to
420
+ * agree about what "loaded" means. A tab already in `tabLoadedRef` is never fetched twice.
421
+ *
422
+ * β›” THE REPAIR IS WHAT MAKES THIS SAFE ON A SERVER THAT SERVES NEITHER NEW ROUTE. If the
423
+ * per-tab read answers `status >= 400` and not 403, the route is absent, so the WHOLE workbook
424
+ * is read in one go and every tab that is not already loaded takes its cells from that read.
425
+ * Loaded tabs keep the local copy, because it may hold edits that have not been saved yet, and
426
+ * the workbook's own `rev` is left alone so the next PUT still asserts the revision this client
427
+ * has been editing against.
428
+ *
429
+ * β›” AND IT IS KEYED ON `status >= 400 && status !== 403`, NEVER ON 404. The tab route sits
430
+ * under the `/sheets/{workbook_id}` path parameter, so an unbuilt route there answers 405 and a
431
+ * `=== 404` test would leave this stuck. [[an-unbuilt-route-under-a-path-param-answers-405]]
432
+ */
433
+ const ensureTabs = useCallback(async (workbookId: string, keys: string[]): Promise<boolean> => {
434
+ const wanted = keys.filter((k) => k && !tabLoadedRef.current.has(tabKeyOf(workbookId, k)));
435
+ if (wanted.length === 0) return true;
436
+ if (tabRouteRef.current !== "no") {
437
+ let served = true;
438
+ for (const key of wanted) {
439
+ const got = await readTab(workbookId, key);
440
+ if (got.ok && got.value) {
441
+ tabRouteRef.current = "yes";
442
+ mergeTab(workbookId, got.value);
443
+ continue;
444
+ }
445
+ const absent = !got.ok && got.status >= 400 && got.status !== 403;
446
+ if (!absent || tabRouteRef.current === "yes") {
447
+ // β›” A TAB THAT WILL NOT LOAD IS NOT AN EMPTY TAB. Painting it as one reads exactly
448
+ // like the cells having been deleted, so the reason is said instead.
449
+ setNotice(got.ok ? "That sheet could not be read, so it is not shown."
450
+ : got.message);
451
+ return false;
452
+ }
453
+ tabRouteRef.current = "no";
454
+ served = false;
455
+ break;
456
+ }
457
+ if (served) return true;
458
+ }
459
+ const fresh = await readWorkbook(workbookId);
460
+ if (!fresh.ok) {
461
+ setNotice(fresh.message);
462
+ return false;
463
+ }
464
+ const live = bookRef.current;
465
+ if (!live || live.id !== workbookId) return false;
466
+ let dropHistory = false;
467
+ const sheets = live.sheets.map((s) => {
468
+ if (tabLoadedRef.current.has(tabKeyOf(workbookId, s.id))) return s;
469
+ const full = fresh.value.sheets.find((f) => f.id === s.id);
470
+ if (!full) return s;
471
+ if (tabHoldsCells(full)) dropHistory = true;
472
+ return { ...s, ...full };
473
+ });
474
+ if (dropHistory) historyRef.current = emptyHistory();
475
+ editSeqRef.current += 1;
476
+ applyLocal({ ...live, sheets });
477
+ markAllLoaded({ ...live, sheets });
478
+ return true;
479
+ }, [applyLocal, markAllLoaded, mergeTab]);
480
+
481
+ /** The tab bar's own door: switch, then fetch the cells if this is the first visit. */
482
+ const openTab = useCallback((id: string) => {
483
+ setTabId(id);
484
+ const current = bookRef.current;
485
+ if (current) void ensureTabs(current.id, [id]);
486
+ }, [ensureTabs]);
487
+
488
  // ⭐ THE FIRST WORKBOOK IS OPENED, OR CREATED IF THERE IS NONE. An empty rail row that does
489
  // nothing until someone finds a create button is the shape this module is trying not to be.
490
  //
 
507
  }
508
  setIndex(got.value);
509
  const first = got.value.workbooks[0];
510
+ // ⭐⭐ W51-T11 / R4 β€” OPENING IS `?tabs=meta` AND THEN THE ACTIVE TAB, in that order and
511
+ // never the whole document. A workbook at R4's cap is 100,000 cells a tab; fetching every
512
+ // tab to show one is the load this split exists to stop paying.
513
+ const opened = first ? await readTabMeta(first.id) : await createWorkbook("Workbook");
514
  if (!live) return;
515
  if (!opened.ok) {
516
  setNotice(opened.message);
 
519
  }
520
  bookRef.current = opened.value;
521
  setBook(opened.value);
522
+ const firstTab = opened.value.sheets[0]?.id ?? "";
523
+ setTabId(firstTab);
524
+ // β›” A WORKBOOK THIS PAGE JUST CREATED IS EMPTY AND WHOLLY IN HAND, so it is marked loaded
525
+ // outright; a workbook read as META carries no cells for any tab, so only the one being
526
+ // opened is fetched. Getting this backwards is what a whole-workbook PUT would then write
527
+ // over the tabs nobody looked at.
528
+ if (!first) markAllLoaded(opened.value);
529
+ else if (firstTab) await ensureTabs(opened.value.id, [firstTab]);
530
+ if (!live) return;
531
  if (!first) {
532
  // A workbook made to fill an empty module still has to appear in the rail, and the
533
  // index was read BEFORE it existed.
 
565
  if (!book) return;
566
  setBusy(true);
567
  setNotice("");
568
+ setStatus("");
569
  const got = await refreshWorkbook(book.id);
570
  setBusy(false);
571
  if (!got.ok) {
 
576
  // rather than left pointing at cells that no longer hold the values it recorded.
577
  historyRef.current = emptyHistory();
578
  editSeqRef.current += 1;
579
+ // A refresh answers with the WHOLE workbook, so every tab is now in memory and the dirty set
580
+ // describes cells that no longer exist in the form it recorded them.
581
+ dirtyRef.current = new Map();
582
+ markAllLoaded(got.value.workbook);
583
+ applyLocal(got.value.workbook);
584
+ // ⭐ R4: *"recalc runs only on Refresh or a formula commit and its time is shown."* Shown to
585
+ // ONE decimal, in seconds, and only when the server actually measured it: rendering a 0.0 for
586
+ // a server that sent no number would be an unverifiable aggregate on a screen.
587
+ if (got.value.recalcMs !== null) {
588
+ setStatus(`Recalculated in ${(got.value.recalcMs / 1000).toFixed(1)} s`);
589
+ }
590
+ }, [applyLocal, book, markAllLoaded]);
591
 
592
  // ⭐ R20 IS DECIDED HERE, NOT INSIDE THE EDITOR. `editIntent` says whether typing over this cell
593
  // is an ordinary edit or a CONVERSION that needs confirming, and the conversion path is the one
 
598
  }, []);
599
 
600
  /**
601
+ * A 409 on one tab: re-read THAT TAB and say so, naming it.
602
+ *
603
+ * ⭐ THIS IS THE WHOLE-WORKBOOK STALE-REV BRANCH, NARROWED TO ONE SHEET. The old sentence said
604
+ * "This workbook changed somewhere else", which was true when a save was the whole document; a
605
+ * per-tab save that reloads one sheet has to name the sheet, or a reader looking at a tab that
606
+ * did not move is told their edit was lost with no way to tell which edit.
607
+ */
608
+ const reloadTab = useCallback(async (workbookId: string, tabKey: string) => {
609
+ const before = bookRef.current;
610
+ const name = before?.sheets.find((t) => t.id === tabKey)?.name || "That sheet";
611
+ const got = await readTab(workbookId, tabKey);
612
+ const live = bookRef.current;
613
+ if (got.ok && got.value && live && live.id === workbookId) {
614
+ // The reloaded tab is not the tree the stack was taken against, so the stack goes.
615
+ historyRef.current = emptyHistory();
616
+ editSeqRef.current += 1;
617
+ tabLoadedRef.current.add(tabKeyOf(workbookId, tabKey));
618
+ const next = got.value;
619
+ applyLocal({
620
+ ...live,
621
+ sheets: live.sheets.map((t) => (t.id === tabKey ? { ...t, ...next } : t)),
622
+ });
623
+ }
624
+ setNotice(`${name} changed somewhere else, so that edit was not saved. `
625
+ + `${name} has been reloaded with the other change.`);
626
+ }, [applyLocal]);
627
+
628
+ /**
629
+ * ⭐⭐ THE CELL PATCH: only the addresses that changed, with the revision they changed against.
630
+ *
631
+ * β›” THE BRANCHES ARE ORDERED, AND THE ORDER IS THE CONTRACT. A 409 and a 413 are both `status
632
+ * >= 400`, and both PROVE the route is there, so each is answered by name BEFORE the
633
+ * route-absence test underneath them. Reversing them would make the first concurrent edit look
634
+ * like an undeployed server and drop the client into whole-workbook saves for the session.
635
+ *
636
+ * β›” AND THE DIRTY SET IS RE-ARMED ONLY WHERE A RETRY MEANS SOMETHING:
637
+ * 409 the tab was reloaded and the local edit is gone by design, so there is nothing to
638
+ * re-send and the sentence already says the edit did not land.
639
+ * 413 the document is over a cap. Re-arming would re-send the same oversized payload on
640
+ * every later debounce, forever, which is a retry loop wearing a refusal.
641
+ * absent route the whole workbook PUT runs in the SAME drain and carries these cells, so
642
+ * re-arming would send them a second time.
643
+ * unreachable (status 0) and anything below 400 a retry is meaningful, so they go back in.
644
+ */
645
+ const sendDirtyCells = useCallback(
646
+ async (): Promise<"sent" | "route_absent" | "stopped"> => {
647
+ const pending = dirtyRef.current;
648
+ dirtyRef.current = new Map();
649
+ for (const [tabKey, addrs] of Array.from(pending.entries())) {
650
+ // β›” THE WORKBOOK AND ITS REVISION ARE RE-READ INSIDE THE LOOP. A PATCH bumps the
651
+ // revision, so a second tab sending the one captured before the loop would be refused as
652
+ // stale by a conflict this client caused itself.
653
+ const current = bookRef.current;
654
+ if (!current) return "stopped";
655
+ const sheet = current.sheets.find((t) => t.id === tabKey);
656
+ if (!sheet) continue;
657
+ const cells: Record<string, Cell | null> = {};
658
+ for (const addr of Array.from(addrs)) cells[addr] = sheet.cells?.[addr] ?? null;
659
+ const sent = await patchTabCells(current.id, tabKey, {
660
+ cells, rev: tabRevOf(sheet, current),
661
+ });
662
+ if (sent.ok) {
663
+ patchModeRef.current = "patch";
664
+ const live = bookRef.current;
665
+ if (live && sent.value.rev) applyLocal({ ...live, rev: sent.value.rev });
666
+ const refused = sent.value.refused ?? [];
667
+ if (refused.length > 0) {
668
+ const head = refused[0];
669
+ setNotice(refused.length === 1
670
+ ? (head.sentence || `${head.addr} was not saved.`)
671
+ : `${head.sentence || `${head.addr} was not saved.`} `
672
+ + `${refused.length - 1} other cells were refused for the same kind of reason.`);
673
+ }
674
+ continue;
675
+ }
676
+ if (sent.status === 409 || sent.code === "sheet_revision_stale") {
677
+ await reloadTab(current.id, tabKey);
678
+ return "stopped";
679
+ }
680
+ if (sent.status === 413) {
681
+ // ⭐ THE SERVER'S OWN SENTENCE, VERBATIM. C3 says it names the count and the cap, and
682
+ // it is the server that knows which cap was hit, cells or bytes. Rewriting it here
683
+ // would be this client guessing at a number it never measured.
684
+ setNotice(sent.message);
685
+ return "stopped";
686
+ }
687
+ if (sent.status >= 400 && sent.status !== 403 && patchModeRef.current !== "patch") {
688
+ // β›” THE PROBE'S ANSWER, AND IT IS TAKEN ONCE. Not `=== 404`: this route sits under the
689
+ // `/sheets/{workbook_id}` path parameter, so an unbuilt route there answers 405.
690
+ patchModeRef.current = "put";
691
+ setStatus("Saving the whole workbook");
692
+ return "route_absent";
693
+ }
694
+ for (const addr of Array.from(addrs)) markDirty(tabKey, addr);
695
+ setNotice(sent.message);
696
+ return "stopped";
697
+ }
698
+ return "sent";
699
+ },
700
+ [applyLocal, markDirty, reloadTab],
701
+ );
702
+
703
+ /**
704
+ * Send the workbook the ref currently holds. Structure changes and the PATCH fallback only.
705
  *
706
  * ⚠ THE SERVER'S ANSWER IS ADOPTED ONLY WHEN NOTHING MOVED WHILE IT WAS AWAY. If more
707
  * keystrokes landed during the round trip, taking `saved.value` wholesale would paint the
 
709
  * staying in the ref. In that case only `rev` and `updated_at` are taken, which is the one
710
  * thing the client could not have known. [[a-rebuilt-value-drops-its-new-field]]
711
  */
712
+ const sendWholeWorkbook = useCallback(async () => {
713
+ const opening = bookRef.current;
714
+ if (!opening) return;
715
+ // β›”β›” THE FENCE. This PUT writes `sheets` verbatim, and after a `?tabs=meta` open the tabs
716
+ // nobody has visited hold an EMPTY cell map. Sending that would delete them, silently, with
717
+ // every gate green. So every tab is read in first, and a workbook that cannot be completed
718
+ // is not written at all.
719
+ const whole = await ensureTabs(opening.id, opening.sheets.map((t) => t.id));
720
+ const current = bookRef.current;
721
+ if (!current) return;
722
+ if (!whole) {
723
+ // β›”β›” THE FLAG GOES BACK ON, AND THIS IS THE SAME RE-ARM DISCIPLINE THE DIRTY SET GETS.
724
+ // `drainSave` clears `structureDirtyRef` before the await, so a return from here without
725
+ // restoring it would leave the next drain believing there is no structure change pending:
726
+ // it would take the CELL PATCH instead, sending addresses whose positions have already
727
+ // moved, against a server still holding the row that was inserted. The insert would never
728
+ // be sent and the cells that were would describe a grid the server does not have.
729
+ structureDirtyRef.current = true;
730
+ setNotice("Some sheets in this workbook could not be read, so nothing was saved. "
731
+ + "Reload the page and try again.");
732
+ return;
733
+ }
734
+ // The PUT carries every cell, so anything the dirty set was still holding is covered by it.
735
+ dirtyRef.current = new Map();
736
+ const seq = editSeqRef.current;
737
+ const saved = await writeWorkbook(current.id, {
738
+ name: current.name, sheets: current.sheets, rev: current.rev,
739
+ });
740
+ if (!saved.ok) {
741
+ // β›” A STALE REV IS NOT A DEAD SESSION. Leaving the local `rev` behind would make every
742
+ // later save stale too, so editing would be over until someone reloaded the page. The
743
+ // workbook is re-read instead, and the reader is told the edit did not land.
744
+ if (saved.code === "workbook_revision_stale") {
745
+ const fresh = await readWorkbook(current.id);
746
+ if (fresh.ok) {
747
+ historyRef.current = emptyHistory();
748
+ editSeqRef.current += 1;
749
+ markAllLoaded(fresh.value);
750
+ applyLocal(fresh.value);
751
  }
752
+ // ⚠ AND HERE THE FLAG STAYS OFF, deliberately. The re-read REPLACED the tree the
753
+ // structure change was made in, so there is nothing left to re-send; the sentence above
754
+ // is what tells the reader their change did not land.
755
+ setNotice("This workbook changed somewhere else, so that edit was not saved. "
756
+ + "The sheet has been reloaded with the other change.");
757
  return;
758
  }
759
+ // A refusal that is not a revision conflict leaves the local tree intact, so the pending
760
+ // structure change is still pending and the next drain must still carry it.
761
+ structureDirtyRef.current = true;
762
+ setNotice(saved.message);
763
+ return;
764
+ }
765
+ if (editSeqRef.current === seq) {
766
+ markAllLoaded(saved.value);
767
+ applyLocal(saved.value);
768
+ } else if (bookRef.current) {
769
+ applyLocal({ ...bookRef.current, rev: saved.value.rev, updated_at: saved.value.updated_at });
770
+ }
771
+ }, [applyLocal, ensureTabs, markAllLoaded]);
772
+
773
+ /**
774
+ * ⭐ ONE DRAIN, BEHIND WHATEVER SAVE IS ALREADY IN FLIGHT.
775
+ *
776
+ * β›” THE CHAIN IS WHAT MAKES A REVISION GUARD WORK AT ALL: two writes in flight carrying the
777
+ * same `rev` means the second is refused, so they are queued rather than raced. The debounce
778
+ * decides WHEN a drain is appended; the chain decides that only one runs at a time.
779
+ */
780
+ const drainSave = useCallback(() => {
781
+ saveChainRef.current = saveChainRef.current.then(async () => {
782
+ if (!bookRef.current) return;
783
+ const structural = structureDirtyRef.current;
784
+ structureDirtyRef.current = false;
785
+ if (!structural && patchModeRef.current !== "put") {
786
+ if (dirtyRef.current.size === 0) return;
787
+ const outcome = await sendDirtyCells();
788
+ // β›” ONLY AN ABSENT ROUTE FALLS THROUGH TO THE PUT, and it falls through in THIS drain so
789
+ // the edit that discovered it still lands. A 409, a 413 and an unreachable server have
790
+ // each been answered already; re-sending the whole document after one of them would
791
+ // either overwrite the change that caused the conflict or push the same refused payload.
792
+ if (outcome !== "route_absent") return;
793
  }
794
+ await sendWholeWorkbook();
795
  });
796
+ }, [sendDirtyCells, sendWholeWorkbook]);
797
+
798
+ useEffect(() => { drainRef.current = drainSave; }, [drainSave]);
799
+
800
+ /**
801
+ * β›” AN UNMOUNT WITH A TIMER STILL PENDING IS AN EDIT THE PERSON WATCHED THEMSELVES MAKE AND
802
+ * WILL NEVER SEE AGAIN. Navigating away inside the debounce window has to drain, not discard.
803
+ */
804
+ useEffect(() => () => {
805
+ if (saveTimerRef.current !== null) {
806
+ window.clearTimeout(saveTimerRef.current);
807
+ saveTimerRef.current = null;
808
+ drainRef.current();
809
+ }
810
+ }, []);
811
+
812
+ /** Drain now, cancelling any pending debounce, and answer when the write has finished. */
813
+ const flushSave = useCallback((): Promise<void> => {
814
+ if (saveTimerRef.current !== null) {
815
+ window.clearTimeout(saveTimerRef.current);
816
+ saveTimerRef.current = null;
817
+ }
818
+ drainSave();
819
+ return saveChainRef.current;
820
+ }, [drainSave]);
821
+
822
+ /**
823
+ * ⭐⭐ THE DEBOUNCE THE TICKET ASSUMED ALREADY EXISTED. Every commit, undo, redo, binding save
824
+ * and structure op calls this; the drain runs once the typing stops.
825
+ *
826
+ * ⚠ THE NAME IS PINNED. `verify_wiring.py`'s W51-T08 leg matches `const onSaveNow = useCallback
827
+ * (() => { queueSave();`, so this door keeps its name and Ctrl+S keeps calling it, whatever the
828
+ * body now does.
829
+ */
830
+ const queueSave = useCallback(() => {
831
+ if (saveTimerRef.current !== null) window.clearTimeout(saveTimerRef.current);
832
+ saveTimerRef.current = window.setTimeout(() => {
833
+ saveTimerRef.current = null;
834
+ drainSave();
835
+ }, SAVE_DEBOUNCE_MS);
836
+ }, [drainSave]);
837
+
838
+ /**
839
+ * ⭐ W51-T08 / C1 β€” CTRL+S. The grid owns the keystroke; the save belongs to the page, because
840
+ * `queueSave` is what serialises a save behind whichever one is already in flight.
841
+ *
842
+ * ⭐ W51-T11 / R4 β€” AND IT IS THE DIRTY SET'S SECOND DOOR. Saving is already automatic on a
843
+ * debounce, so what Ctrl+S adds is IMMEDIACY: the pending timer is cancelled and the drain runs
844
+ * now. Pressing it twice costs one extra round trip and cannot reorder anything.
845
+ */
846
+ const onSaveNow = useCallback(() => {
847
+ queueSave();
848
+ void flushSave();
849
+ }, [queueSave, flushSave]);
850
+
851
+ /**
852
+ * ⭐ W51-T08 / C1 β€” THE IMPORT DOOR, DECLARED WHERE IT WILL LIVE AND INERT UNTIL W51-T13.
853
+ *
854
+ * β›” IT IS A REAL FUNCTION AND NOT `undefined` ON PURPOSE. C1 asks the seam to be passed now so
855
+ * the wiring is one edit at T13 rather than a prop that has to be threaded through E's component
856
+ * afterwards; a prop pinned as `undefined` would prove nothing. It opens nothing today, which is
857
+ * the honest state: there is no dialog to open, and inventing a message about a feature nobody
858
+ * can see would be copy that outlives its own reason.
859
+ */
860
+ const onOpenImport = useCallback(() => {
861
+ // W51-T13 mounts the import dialog on this handler. Deliberately inert until then.
862
+ return;
863
+ }, []);
864
 
865
  /**
866
  * ⭐ THE ONE COMMIT DOOR. Every edit the grid can make arrives here: a typed cell, a paste, a
 
877
  historyRef.current = pushHistory(historyRef.current, base.sheets);
878
  editSeqRef.current += 1;
879
  setNotice("");
880
+ // ⭐⭐ W51-T11 / R4 β€” THE DIRTY SET, AND `edits` IS ALREADY EXACTLY IT. The changed addresses
881
+ // arrive as this function's own parameter, so the PATCH body is in hand at the one place
882
+ // every cell write in this module passes through: a typed cell, a paste, a fill, a range
883
+ // delete and the R20 conversion. Nothing else has to be diffed against anything.
884
+ for (const addr of Object.keys(edits)) markDirty(target, addr);
885
  applyLocal(withCells(base, target, edits));
886
  queueSave();
887
+ }, [applyLocal, markDirty, queueSave]);
888
 
889
  // ═══════════════════════════════════════════════════════════════════════════════════════════
890
  // ⭐⭐ W50-T20 β€” STRUCTURE, THROUGH THE SAME DOOR AS A KEYSTROKE.
 
906
  historyRef.current = pushHistory(historyRef.current, base.sheets);
907
  editSeqRef.current += 1;
908
  setNotice("");
909
+ // β›”β›” W51-T11 / C3 β€” STRUCTURE STAYS ON PUT, AND THIS FLAG IS THE WHOLE DIVISION. An inserted
910
+ // row moves every cell below it, a deleted column moves every cell to its right, and a
911
+ // renamed tab changes what every formula on every OTHER sheet resolves against. A cell PATCH
912
+ // can express none of that: it names addresses, and the addresses themselves have moved.
913
+ // C3 is explicit that *"`PUT` stays for structure and stays capped"*.
914
+ structureDirtyRef.current = true;
915
  applyLocal({ ...base, sheets });
916
  queueSave();
917
  }, [applyLocal, queueSave]);
 
969
  if (!base) return;
970
  const made = addTab(base);
971
  commitSheets(made.sheets);
972
+ // A tab this page just made has no cells anywhere but here, so it is loaded by construction
973
+ // and must never be fetched: a lazy read of it would 404 or answer an empty tab.
974
+ tabLoadedRef.current.add(tabKeyOf(base.id, made.id));
975
  setTabId(made.id);
976
  }, [commitSheets]);
977
 
 
1038
  historyRef.current = step.history;
1039
  editSeqRef.current += 1;
1040
  setNotice("");
1041
+ // β›” AN UNDO RESTORES A WHOLE `sheets` ARRAY, so it is a structure write and takes the PUT.
1042
+ // A cell PATCH would have to diff two trees to find what moved, and a step that put a
1043
+ // deleted row back would have no address list at all.
1044
+ structureDirtyRef.current = true;
1045
  applyLocal({ ...base, sheets: step.sheets });
1046
  queueSave();
1047
  }, [applyLocal, queueSave]);
 
1054
  historyRef.current = step.history;
1055
  editSeqRef.current += 1;
1056
  setNotice("");
1057
+ /* A redo is an undo in the other direction, and takes the same door for the same reason. */
1058
+ structureDirtyRef.current = true;
1059
  applyLocal({ ...base, sheets: step.sheets });
1060
  queueSave();
1061
  }, [applyLocal, queueSave]);
 
1123
  if (got.ok) setIndex(got.value);
1124
  }, []);
1125
 
1126
+ /**
1127
+ * @param held `"all"` when the workbook arrived complete (a full read, a create, a duplicate);
1128
+ * `"meta"` when only its tab LIST arrived and the cells have still to be fetched.
1129
+ *
1130
+ * β›” GETTING THIS ARGUMENT WRONG IS THE DATA-LOSS BUG. Calling it `"all"` over a meta read
1131
+ * tells the PUT fallback that empty tabs are the truth, and the next save writes that.
1132
+ */
1133
+ const adoptWorkbook = useCallback((next: Workbook, held: "all" | "meta") => {
1134
  // A different workbook is a different tree, so the undo stack is dropped rather than left
1135
  // pointing at cells that no longer hold the values it recorded.
1136
  historyRef.current = emptyHistory();
1137
  editSeqRef.current += 1;
1138
+ // The dirty set names addresses in the workbook being left. It does not travel.
1139
+ dirtyRef.current = new Map();
1140
+ structureDirtyRef.current = false;
1141
+ if (held === "all") markAllLoaded(next);
1142
  applyLocal(next);
1143
  setTabId(next.sheets[0]?.id ?? "");
1144
+ }, [applyLocal, markAllLoaded]);
1145
 
1146
  const openWorkbook = useCallback(async (id: string) => {
1147
  if (id === bookRef.current?.id) return;
1148
  setOpening(true);
1149
  setNotice("");
1150
+ // ⭐ R4: one tab at a time here too. The meta read carries the tab list and the revision; the
1151
+ // tab being opened is the only one whose cells are fetched.
1152
+ const got = await readTabMeta(id);
1153
  if (!got.ok) {
1154
  setNotice(got.message);
1155
  setOpening(false);
1156
  return;
1157
  }
1158
+ adoptWorkbook(got.value, "meta");
1159
+ const firstTab = got.value.sheets[0]?.id ?? "";
1160
+ if (firstTab) await ensureTabs(got.value.id, [firstTab]);
1161
  setOpening(false);
1162
+ }, [adoptWorkbook, ensureTabs]);
1163
 
1164
  /** R2's create door: made and OPENED in one act, with no name step in between. */
1165
  const createAndOpen = useCallback(async () => {
 
1171
  setOpening(false);
1172
  return;
1173
  }
1174
+ adoptWorkbook(made.value, "all");
1175
  await refreshIndex();
1176
  setOpening(false);
1177
  }, [adoptWorkbook, refreshIndex]);
 
1204
  setOpening(false);
1205
  return;
1206
  }
1207
+ adoptWorkbook(filled.value, "all");
1208
  await refreshIndex();
1209
  setOpening(false);
1210
  }, [adoptWorkbook, refreshIndex]);
 
1218
  setNotice("");
1219
  if (bookRef.current && bookRef.current.id === id) {
1220
  applyLocal({ ...bookRef.current, name });
1221
+ // β›”β›” A NAME IS NOT A CELL, SO IT TAKES THE PUT, AND IT IS FLUSHED RATHER THAN DEBOUNCED.
1222
+ // `await saveChainRef.current` used to be enough because `queueSave` appended the write
1223
+ // synchronously. With a debounce in front of it that await returns IMMEDIATELY, on a chain
1224
+ // whose last link resolved before this rename existed, and `refreshIndex` would then read
1225
+ // the rail back with the OLD name. `flushSave` cancels the timer, appends the write and
1226
+ // hands back the chain that actually carries it.
1227
+ structureDirtyRef.current = true;
1228
  queueSave();
1229
+ await flushSave();
1230
  await refreshIndex();
1231
  return;
1232
  }
 
1243
  return;
1244
  }
1245
  await refreshIndex();
1246
+ }, [applyLocal, flushSave, queueSave, refreshIndex]);
1247
 
1248
  const removeWorkbook = useCallback(async (id: string) => {
1249
  setNotice("");
 
1266
  await openWorkbook(next.id);
1267
  }, [openWorkbook]);
1268
 
1269
+ /** The index revision to send with the next strata PUT, or `undefined` before W51-T25. */
1270
+ const indexRev = index.rev;
1271
+
1272
  /**
1273
  * The ONE door for every folder, placement and star change.
1274
  *
 
1285
  itemFolders: next.itemFolders,
1286
  starred: next.starred,
1287
  }));
1288
+ /**
1289
+ * ⭐⭐ W51-T10 β€” THE REVISION RIDES ALONG WHEN THERE IS ONE, AND IS OMITTED WHEN THERE IS NOT.
1290
+ *
1291
+ * The index PUT is wholesale and carries no `rev` today (D-639), so two people filing at once
1292
+ * overwrite each other in silence. W51-T25 stamps one; this is the ONE place a star, a move,
1293
+ * a rename and a folder change all pass through, so forwarding it here covers every strata
1294
+ * write at once. β›” `rev: undefined` is NOT the same as no key: it would serialise as an
1295
+ * absent field on some paths and as a null on others, and the server's guard would then have
1296
+ * to read two spellings of "I did not send one".
1297
+ */
1298
+ const saved = await writeIndex(
1299
+ indexRev === undefined ? next : { ...next, rev: indexRev },
1300
+ );
1301
  if (!saved.ok) {
1302
  const rows = await readIndex();
1303
  if (rows.ok) setIndex(rows.value);
 
1307
  setIndex(saved.value);
1308
  const sentence = repairSentence(saved.value.repairs);
1309
  if (sentence) setNotice(sentence);
1310
+ }, [indexRev]);
1311
+
1312
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
1313
+ // ⭐⭐ W51-T09 (owner instruction 2, ruling R12) β€” "ASK ABOUT THIS DATA", AND WHAT IT IS ABOUT
1314
+ //
1315
+ // R12, verbatim: *"'Ask about this data' in the Sheet opens the assistant dock with the
1316
+ // WORKBOOK'S BOUND DATABASES as its subject, through Data's read path; reading raw cells is not
1317
+ // this wave."* So the panel is `customer-grid/GridChat.tsx` ITSELF β€” the same component the Data
1318
+ // module docks, not a Sheet-shaped copy of it β€” and everything below is the host half that
1319
+ // component's contract C6 requires.
1320
+ //
1321
+ // β›” THE STATE LIVES ON THE PAGE, NOT IN THE RAIL. The launcher and the panel are two halves of
1322
+ // one thing; a rail holding its own copy would let the button say "close" over a dock that was
1323
+ // never open. `CustomerGrid` owns it the same way for the Data rail.
1324
+ //
1325
+ // β›” AND THE NUMBERS ON SCREEN ARE READ, NEVER DERIVED FROM THE CELLS. `GridChat`'s composer foot
1326
+ // prints "N records, M fields", so a count invented from the workbook would put an unverifiable
1327
+ // aggregate on a screen. Both come through the doors the Data module itself uses.
1328
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
1329
+
1330
+ /** Is the assistant dock open. */
1331
+ const [chatOpen, setChatOpen] = useState(false);
1332
+ const toggleChat = useCallback(() => setChatOpen((open) => !open), []);
1333
+ const closeChat = useCallback(() => setChatOpen(false), []);
1334
+ /** What the bound databases hold. Empty until the reads answer, exactly as a Data grid is. */
1335
+ const [chatSchema, setChatSchema] = useState<GridChatField[]>([]);
1336
+ const [chatRows, setChatRows] = useState(0);
1337
+
1338
+ /**
1339
+ * R12's subject, half one: the DISTINCT databases this workbook's cells are bound to.
1340
+ *
1341
+ * ⚠ `binding` FIRST, `source` SECOND, and both are read for a reason. `binding` is what the
1342
+ * person chose in the binding editor and exists the moment they choose it; `source` is what the
1343
+ * server's resolver stamped back and exists only after a cell has resolved once. Reading only
1344
+ * the second would leave a freshly bound workbook claiming it reads nothing.
1345
+ */
1346
+ const boundDatabases = useMemo(() => {
1347
+ const seen: string[] = [];
1348
+ for (const sheet of book?.sheets ?? []) {
1349
+ for (const cell of Object.values(sheet.cells ?? {})) {
1350
+ const bound = (cell?.binding as { database?: unknown } | undefined)?.database;
1351
+ const key = String(bound ?? cell?.source?.database ?? "").trim();
1352
+ if (key && !seen.includes(key)) seen.push(key);
1353
+ }
1354
+ }
1355
+ return seen;
1356
+ }, [book]);
1357
+
1358
+ /** Those databases in the person's own words, from the nav list this page already holds. */
1359
+ const boundLabels = useMemo(
1360
+ () => boundDatabases.map((key) => databases.find((d) => d.key === key)?.label || key),
1361
+ [boundDatabases, databases],
1362
+ );
1363
+
1364
+ /**
1365
+ * R12's subject, half two: the WORKBOOK, named, and what it reads. This is `databaseLabel`, and
1366
+ * `GridChat` puts it in its header, its placeholder ("Ask about ...") and every refusal it
1367
+ * writes, so it has to read as a phrase rather than as a key.
1368
+ */
1369
+ const chatSubject = useMemo(() => {
1370
+ const name = (book?.name ?? "").trim() || "This workbook";
1371
+ return boundLabels.length
1372
+ ? `${name}, reading ${boundLabels.join(", ")}`
1373
+ : `${name}, which reads no database yet`;
1374
+ }, [book, boundLabels]);
1375
+
1376
+ /**
1377
+ * R12's "through Data's read path", literally: `fetchWorkspace` is the door `BindingEditor`
1378
+ * already opens for these same databases, so the chat can never name a column a cell could not
1379
+ * bind to, and `fetchTopicRows` / `fetchTableWindow` are the two row doors the Data module reads
1380
+ * through. Both are shared caches, so a person who has already opened Data pays nothing here.
1381
+ *
1382
+ * ⚠ ON OPEN, NOT ON PAINT. A workbook can be bound to several databases and this is several
1383
+ * round trips; running it for every visitor who never opens the dock would be a page load spent
1384
+ * on a panel nobody asked for.
1385
+ *
1386
+ * β›” AND IT IS SLOW ENOUGH TO BE WORTH WRITING DOWN. Measured on a local qa-b box, one binding
1387
+ * to `customer_data`: `/workspace?scope=customer` took 21.4s and `/customers` a further 16.8s,
1388
+ * so the composer foot reads "0 records" for about 38 seconds before it reads
1389
+ * "0 records, 39 fields". Both numbers are then TRUE (that tenant really holds no customer
1390
+ * rows), and the panel is usable throughout, but the scope line is a count that arrives late
1391
+ * with nothing on screen saying so. `GridChatProps` has no loading state to say it with, and
1392
+ * adding one means editing lane A's file; booked rather than smuggled in.
1393
+ */
1394
+ useEffect(() => {
1395
+ if (!chatOpen) return undefined;
1396
+ let live = true;
1397
+ (async () => {
1398
+ const fields: GridChatField[] = [];
1399
+ let rows = 0;
1400
+ for (const key of boundDatabases) {
1401
+ const topic = CHAT_TOPICS.find((t) => t.key === key);
1402
+ const scope: SurfaceScope | null = topic
1403
+ ? (topic.scope as SurfaceScope)
1404
+ : (key.startsWith("ut_") ? (key as SurfaceScope) : null);
1405
+ if (!scope) continue;
1406
+ const ws = await fetchWorkspace(scope, { allowCached: true });
1407
+ if (!live) return;
1408
+ for (const f of ws?.fields ?? []) {
1409
+ if (!fields.some((seen) => seen.key === f.key)) {
1410
+ fields.push({ key: f.key, label: f.label, type: String(f.type) });
1411
+ }
1412
+ }
1413
+ // β›” THE SERVER'S OWN COUNT WHEN IT STATES ONE. `counts.matched` is the count statement a
1414
+ // windowed table answers with; `rows.length` is only correct for a payload that carried
1415
+ // the whole table, which is why it is the fallback and not the first read.
1416
+ const payload = topic
1417
+ ? await fetchTopicRows(topic)
1418
+ : await fetchTableWindow(key, { offset: 0, limit: 1 });
1419
+ if (!live) return;
1420
+ rows += payload ? payload.counts?.matched ?? payload.rows.length : 0;
1421
+ }
1422
+ if (!live) return;
1423
+ setChatSchema(fields);
1424
+ setChatRows(rows);
1425
+ })().catch(() => {
1426
+ // A read that fails leaves the foot on its last honest numbers rather than a wrong pair, and
1427
+ // the catch is what stops a failed fetch surfacing as an unhandled rejection in the console.
1428
+ });
1429
+ return () => { live = false; };
1430
+ }, [chatOpen, boundDatabases]);
1431
+
1432
+ /**
1433
+ * (a) ANSWER A QUESTION, and it spends no model call.
1434
+ *
1435
+ * β›” D-339's RULE IS THE WHOLE SHAPE OF THIS: an agent that cannot read the data answers from
1436
+ * words alone and invents a number. This host can see WHAT the bound databases hold and nothing
1437
+ * else this wave, so it says exactly that and marks everything else `unanswerable` rather than
1438
+ * writing prose that sounds like an answer. `schemaSentence` is `GridChat`'s own sentence
1439
+ * builder, so the wording matches the Data module's for the same question.
1440
+ */
1441
+ const describeSubject = useCallback(async (question: string): Promise<GridChatAnswer> => {
1442
+ const asked = question.toLowerCase();
1443
+ if (!boundDatabases.length) {
1444
+ return {
1445
+ text: "No cell in this workbook is bound to a database yet, so there is nothing here for "
1446
+ + "me to read. Bind a cell from the formula bar and ask again.",
1447
+ unanswerable: true,
1448
+ };
1449
+ }
1450
+ const named = chatSchema.find((f) => asked.includes(f.label.toLowerCase())
1451
+ || asked.includes(f.key.toLowerCase()));
1452
+ const where = boundLabels.join(", ");
1453
+ if (named) {
1454
+ return {
1455
+ text: `${named.label} is a ${named.type} column in ${where}. I can say what this `
1456
+ + "workbook's databases hold; counting or comparing their records from a sheet is not "
1457
+ + "something this build does yet.",
1458
+ unanswerable: true,
1459
+ };
1460
+ }
1461
+ return {
1462
+ text: `${schemaSentence(chatSchema, where)} I can say what this workbook's databases hold; `
1463
+ + "reading the values in its cells is not something this build does yet.",
1464
+ unanswerable: true,
1465
+ };
1466
+ }, [boundDatabases, boundLabels, chatSchema]);
1467
+
1468
+ /**
1469
+ * (b), (b-undo) and (d) β€” THE THREE DOORS THIS HOST DELIBERATELY DOES NOT OPEN.
1470
+ *
1471
+ * β›” NAMED, NOT ANONYMOUS, AND THAT IS THE POINT. `GridChat`'s ten props are all required, so
1472
+ * each of these has to be SOMETHING; a bare `() => {}` at the call site is indistinguishable
1473
+ * from a wiring somebody forgot, and the next reader has no way to tell a deliberate refusal
1474
+ * from a bug. The name is the difference.
1475
+ */
1476
+ const noSavedViewToApply = useCallback(() => {
1477
+ // A Sheet has ONE view kind and no saved view (wave-49 R2), so there is no sort, group or
1478
+ // colour for the chat to change. Wave-49 R2: a control that cannot be honoured is absent.
1479
+ }, []);
1480
+ const noSavedViewToUndo = useCallback(() => {
1481
+ // Nothing was applied, so there is nothing to put back.
1482
+ }, []);
1483
+ const noCellWritesThisWave = useCallback(async () => {
1484
+ // R12 withholds cell writes this wave, which is why `canEdit` is false at the call site: the
1485
+ // power is not OFFERED rather than offered and then refused. This can only be reached from a
1486
+ // confirm control the panel never renders while `canEdit` is false.
1487
  }, []);
1488
 
1489
  const tab = book?.sheets.find((t) => t.id === tabId) ?? book?.sheets[0] ?? null;
 
1506
  onRenameWorkbook={renameWorkbook}
1507
  onDuplicateWorkbook={duplicateWorkbook}
1508
  onDeleteWorkbook={removeWorkbook}
1509
+ sharedWithMe={index.sharedWithMe}
1510
  onStrataChange={saveStrata}
1511
+ chatOpen={chatOpen}
1512
+ onToggleChat={toggleChat}
1513
  />
1514
 
1515
+ {/* ⭐⭐ W51-T09 (R12) β€” THE DOCK, SEATED BETWEEN THE RAIL AND THE BODY, which is where the
1516
+ Data module seats its own ("docked to the RIGHT of the secondary navigation"). It is
1517
+ mounted in the same change as its launcher, deliberately: a panel whose only entry point
1518
+ is a prop nobody flips is mounted-but-never-offered, which is the defect this repo has
1519
+ shipped more often than any other. `verify_wiring.py` asserts both halves.
1520
+ ⚠ `.sheet-chat-dock` rather than `.cg-chat-dock` alone: that class is a bare flex seat
1521
+ written for `.cg-shell`, a row this page is not inside. See `styles/wave51/sheet-chrome.css`. */}
1522
+ {chatOpen && (
1523
+ <div className="sheet-chat-dock">
1524
+ <GridChat
1525
+ open={chatOpen}
1526
+ onClose={closeChat}
1527
+ databaseLabel={chatSubject}
1528
+ schema={chatSchema}
1529
+ rowCount={chatRows}
1530
+ canEdit={false}
1531
+ onDescribe={describeSubject}
1532
+ onApplyView={noSavedViewToApply}
1533
+ onUndoView={noSavedViewToUndo}
1534
+ onWriteCells={noCellWritesThisWave}
1535
+ />
1536
+ </div>
1537
+ )}
1538
+
1539
  {/* β›”β›” THE LOADING BODY IS ITS OWN BRANCH AND CARRIES NO SENTENCE. The owner named the
1540
  defect: "the 'opening your workbook' loading screen must be the Data module's loading
1541
  animation". A line of prose where the rest of the app shows a spinner is the thing
 
1547
  </div>
1548
  ) : (
1549
  <div className="sheet-body">
1550
+ {/* ⭐⭐ W51-T08 (owner instructions 8 and 10) β€” THE PAGE TOOLBAR IS GONE, TITLE AND ALL.
1551
+ The owner's ask is that the Sheet carries no page title and that exactly ONE ribbon
1552
+ sits above exactly ONE formula bar above the canvas. A `.sheet-toolbar` row holding an
1553
+ `<h1>` and a second Refresh button is a THIRD band of chrome above the ribbon, and the
1554
+ workbook's name is already the selected row in the rail beside it, so the heading was
1555
+ naming the page to a reader who had just clicked it.
 
 
 
 
 
 
 
 
 
 
1556
 
1557
+ ⭐ REFRESH DID NOT DISAPPEAR, IT MOVED. R8 puts it on the ribbon's own row, so it is
1558
+ handed down as `onRefresh` (C1) rather than drawn here. Wave-49 R12's reasoning still
1559
+ holds and is why it is a ROW-level control rather than a cell one: a sheet is a
1560
+ snapshot, so the one act that changes every number on screen is a page-level act.
1561
+
1562
+ ⚠ `.sheet-notice` DELIBERATELY STAYS. It is a transient sentence about a refusal, not
1563
+ chrome, and instructions 8 and 10 name a title and a duplicated bar. Deleting it would
1564
+ take the only place a save conflict or a failed refresh is ever said out loud. */}
1565
  {notice && <p className="sheet-notice">{notice}</p>}
1566
 
1567
+ {/* ⭐ W51-T11 β€” THE MACHINE'S OWN LINE, beside the refusal line and never instead of it.
1568
+ It carries two sentences and only ever one at a time: "Saving the whole workbook",
1569
+ which is what the client says when contract C3's cell PATCH is not served and it has
1570
+ fallen back to writing the whole document, and "Recalculated in N.N s" after a
1571
+ Refresh that reported its own time (R4). Both are states of the machine rather than
1572
+ refusals, which is why neither may take `.sheet-notice`'s slot away from a sentence
1573
+ saying an edit did not land.
1574
+ ⚠ IT WEARS `.sheet-notice` BECAUSE THAT CLASS IS STYLED AND BOTH SHEET STYLESHEETS
1575
+ ARE OUTSIDE THIS TICKET'S FENCE. `.sheet-status` is carried alongside it as the hook
1576
+ a later ticket can style without hunting for the element. */}
1577
+ {status && <p className="sheet-notice sheet-status">{status}</p>}
 
 
 
 
1578
 
1579
  {/* ⭐ THREE OUTCOMES, IN THE ORDER THEY CAN HAPPEN. A workbook is switching, so the
1580
  spinner again; a workbook is open, so the grid; nothing opened and `loading` is over,
 
1603
  onGrow={onGrow}
1604
  onFreeze={onFreeze}
1605
  onColumnWidth={onColumnWidth}
1606
+ // ⭐⭐ W51-T08 / CONTRACT C1 β€” THE FOUR SEAM PROPS THE RIBBON IS FED THROUGH.
1607
+ //
1608
+ // ⚠ THEY SIT AFTER `onCommit` AND THAT IS LOAD BEARING, not tidiness. `verify_wiring`'s
1609
+ // W50-T17 row matches `<SheetGrid` forward to `onCommit={commitCells}` and REFUSES an
1610
+ // intervening `/>`; the slot below closes a self-closing element, so putting it
1611
+ // earlier in this list would red a row this ticket does not own.
1612
+ //
1613
+ // β›” `formulaBar` IS A NODE, NOT A FLAG. The bar carries the page's own commit door and
1614
+ // its address state, so building it here and handing E a rendered node is what keeps
1615
+ // ONE formula bar in the app; a boolean would have made E build a second one.
1616
+ formulaBar={<FormulaBar
1617
+ addr={barAddr}
1618
+ cell={cellAt(tab, barAddr)}
1619
+ disabled={busy}
1620
+ onAddrChange={setBarAddr}
1621
+ onCommit={commitCells}
1622
+ />}
1623
+ onSaveNow={onSaveNow}
1624
+ onOpenImport={onOpenImport}
1625
  />
1626
  ) : (
1627
  <div className="sheet-placeholder">
 
1651
  type="button"
1652
  className={"sheet-ribbon-btn" + (t.id === (tab?.id ?? "") ? " is-on" : "")}
1653
  aria-pressed={t.id === (tab?.id ?? "")}
1654
+ onClick={() => openTab(t.id)}
1655
  onDoubleClick={() => setTabRename({ id: t.id, name: t.name })}
1656
  // ⚠ THE ELEMENT IS CAPTURED BEFORE THE UPDATER RUNS. Reading `e.currentTarget`
1657
  // inside a state updater is how this app lost an anchor before
 
1659
  onContextMenu={(e) => {
1660
  e.preventDefault();
1661
  const el = e.currentTarget;
1662
+ openTab(t.id);
1663
  setTabMenu({ id: t.id, el });
1664
  }}
1665
  title="Click to open. Double click to rename. Right click for more."
 
1763
  </div>
1764
  )}
1765
 
1766
+ {/* β›”β›” W51-T10 / R6 β€” THE SAME DIALOG THE RAIL'S WORKBOOK DELETE OPENS. R6: one
1767
+ `ConfirmDialog` for every destructive act, workbook and tab deletes named in as many
1768
+ words. The panel this replaced was a positioned div with neither a focus trap nor an
1769
+ Escape key, and its Delete button wore the same `.sheet-refresh` chrome as its Cancel.
1770
+ ⚠ WHEN IT OPENS IS UNCHANGED, AND DELIBERATELY SO. `onRemoveTab` still asks only when
1771
+ the sheet HOLDS something (wave-50 R18: what a bound cell loses is a QUERY, not a number
1772
+ somebody can type back in); an empty sheet still goes on one click. R6 governs the SHAPE
1773
+ of the promise, not which acts earn one, and adding friction to an empty sheet is a
1774
+ product decision this ticket was not given. */}
1775
+ <ConfirmDialog
1776
+ open={Boolean(tabDelete)}
1777
+ title={`Delete ${tabDelete?.name ?? ""}?`}
1778
+ body={
1779
+ (tabDelete?.cells === 1
1780
+ ? "This sheet holds 1 value, and deleting it removes that value."
1781
+ : `This sheet holds ${tabDelete?.cells ?? 0} values, and deleting it removes them.`)
1782
+ + " Any formula on another sheet that points here stops resolving."
1783
+ }
1784
+ confirmLabel="Delete"
1785
+ tone="destructive"
1786
+ onConfirm={confirmRemoveTab}
1787
+ onCancel={() => setTabDelete(null)}
1788
+ />
1789
 
1790
  {/* β›” R18's SECOND HALF, AND THE TICKET NAMES IT: a delete that would drop a BOUND cell asks
1791
  first. A bound cell is the one kind that cannot be typed back in from memory, because
 
1808
  )}
1809
 
1810
  {book && editAt && (
1811
+ /*
1812
+ * β›”β›” `key={editAt}` REMOUNTS THE PANEL, AND WITHOUT IT THE SECOND CELL SHOWS THE FIRST
1813
+ * CELL'S PERIOD. `BindingEditor` seeds its period, lock and drag state from `initial`
1814
+ * through `useState(() => ...)`, which runs ONCE per mount; reconciling D9 -> E10 keeps
1815
+ * the old state and the panel then describes a cell it is not editing.
1816
+ *
1817
+ * ⚠ W51-T12 is what made this reachable. While the panel was a `position: fixed` sheet
1818
+ * over the canvas there was no way to click a second bound cell without closing it first,
1819
+ * so the missing key cost nothing. The panel is a COLUMN now and the grid beside it stays
1820
+ * clickable, which turns 'edit another cell' into an ordinary gesture.
1821
+ */
1822
  <BindingEditor
1823
+ key={editAt}
1824
  workbookId={book.id}
1825
  addr={editAt}
1826
  databases={databases}
web/src/sheet/SheetRail.tsx CHANGED
@@ -38,6 +38,11 @@
38
  import { useMemo, useState } from "react";
39
  import type { DragEvent as ReactDragEvent } from "react";
40
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
 
 
 
 
 
41
  import { ROOT_FOLDER_ID } from "./types";
42
  import type { SheetFolder, WorkbookRow } from "./types";
43
 
@@ -51,6 +56,15 @@ export interface RailStrata {
51
  export interface SheetRailProps {
52
  loading: boolean;
53
  rows: readonly WorkbookRow[];
 
 
 
 
 
 
 
 
 
54
  folders: readonly SheetFolder[];
55
  itemFolders: Record<string, string>;
56
  starred: readonly string[];
@@ -62,14 +76,30 @@ export interface SheetRailProps {
62
  onDeleteWorkbook: (id: string) => void;
63
  /** Every folder, placement and star change goes through this ONE door. */
64
  onStrataChange: (next: RailStrata) => void;
 
 
 
 
 
 
 
 
 
 
65
  }
66
 
 
 
 
 
 
 
 
 
 
67
  /** How many rows the rail draws while it is loading. Matches `Shell.tsx::RAIL_SKELETON_ROWS`. */
68
  const SKELETON_ROWS = 6;
69
 
70
- const FOLDER_PATH =
71
- "M2.4 12.6V4.2a.6.6 0 0 1 .6-.6h3.2l1.5 1.7h5.3a.6.6 0 0 1 .6.6v6.7a.6.6 0 0 1-.6.6H3a.6.6 "
72
- + "0 0 1-.6-.6z";
73
  const STAR_PATH =
74
  "M8 2.9l1.63 3.3 3.64.53-2.63 2.57.62 3.63L8 11.24 4.74 12.93l.62-3.63L2.73 6.73l3.64-.53z";
75
 
@@ -96,27 +126,71 @@ function RailSkeleton() {
96
  );
97
  }
98
 
99
- /** The mark one workbook row wears: a page ruled into cells. 16x16, `currentColor`. */
 
 
 
 
 
 
 
 
 
100
  function SheetViewIcon() {
101
  return (
102
  <svg className="sheet-view-icon" viewBox="0 0 16 16" aria-hidden="true">
103
- <rect x="2.2" y="2.6" width="11.6" height="10.8" rx="1.3" />
104
- <path d="M2.2 6.2h11.6M2.2 9.8h11.6M6.4 2.6v10.8M10.2 2.6v10.8" />
 
105
  </svg>
106
  );
107
  }
108
 
109
- function FolderMark() {
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  return (
111
- <svg className="cg-folder-mark" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
112
- <path
113
- d={FOLDER_PATH}
114
- fill="none"
115
- stroke="currentColor"
116
- strokeWidth={1.35}
117
- strokeLinecap="round"
118
- strokeLinejoin="round"
119
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  </svg>
121
  );
122
  }
@@ -171,6 +245,7 @@ const cleanName = (raw: string) => raw.trim().replace(/\s+/g, " ").slice(0, 80);
171
  export default function SheetRail({
172
  loading,
173
  rows,
 
174
  folders,
175
  itemFolders,
176
  starred,
@@ -181,7 +256,25 @@ export default function SheetRail({
181
  onDuplicateWorkbook,
182
  onDeleteWorkbook,
183
  onStrataChange,
 
 
184
  }: SheetRailProps) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  /** The folder whose contents are on screen, or null for the top level. */
186
  const [at, setAt] = useState<string | null>(null);
187
  /** Windows-style history for the path row's back and forward buttons. */
@@ -195,6 +288,31 @@ export default function SheetRail({
195
  const [folderName, setFolderName] = useState("");
196
  const [dragged, setDragged] = useState<Dragged | null>(null);
197
  const [dropOn, setDropOn] = useState<string | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  const byId = useMemo(() => {
200
  const map: Record<string, SheetFolder> = {};
@@ -251,6 +369,8 @@ export default function SheetRail({
251
 
252
  const levelFolders = folders.filter((f) => (f.parent ?? null) === at && matches(f.name));
253
  const levelRows = rows.filter((r) => placedIn(r.id) === at && matches(r.name));
 
 
254
 
255
  const isStarred = (id: string) => starred.includes(id);
256
 
@@ -329,6 +449,44 @@ export default function SheetRail({
329
  onStrataChange(next);
330
  };
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  const createFolder = () => {
333
  const clean = cleanName(folderName);
334
  if (!clean) return;
@@ -341,7 +499,65 @@ export default function SheetRail({
341
  };
342
 
343
  return (
344
- <nav className="cg-views sheet-rail-views" aria-label="Sheet workbooks">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  {loading ? (
346
  <RailSkeleton />
347
  ) : (
@@ -400,8 +616,14 @@ export default function SheetRail({
400
  </nav>
401
 
402
  {/* ⚠ `cg-data-create` WRAPS `cg-create-new`, which is the nesting the Data rail uses:
403
- the outer class is the host's slot and the inner one is the control. Flattening
404
- them loses the 8px the outer wrapper contributes and the two rails drift apart. */}
 
 
 
 
 
 
405
  <div className="cg-data-create">
406
  <div className="cg-create-new">
407
  <button
@@ -433,10 +655,18 @@ export default function SheetRail({
433
  </div>
434
 
435
  {/* THE LEVEL. `cg-fold-root` is the Data rail's own drop target for "file it here",
436
- and dropping on it moves the dragged row into the folder currently open. */}
 
 
 
 
 
 
 
 
437
  <div
438
  className={
439
- "cg-views-scroll cg-fold-root sheet-rail-level"
440
  + (dropOn === "__level__" ? " is-drop" : "")
441
  }
442
  {...dropProps(at, "__level__")}
@@ -465,7 +695,7 @@ export default function SheetRail({
465
  aria-label={`Open folder ${folder.name}`}
466
  onClick={() => goTo(folder.id)}
467
  >
468
- <FolderMark />
469
  <span className="cg-fold-name">{folder.name}</span>
470
  </button>
471
  <button
@@ -534,6 +764,40 @@ export default function SheetRail({
534
  {needle ? "No workbook here matches what you typed." : "Nothing filed here yet."}
535
  </p>
536
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  </div>
538
  </>
539
  )}
@@ -569,19 +833,36 @@ export default function SheetRail({
569
  {/* β›” A WORKBOOK IS MADE AND OPENED IN ONE ACT, with no name step. The page shows
570
  the new workbook the moment the server answers, which is the done-when clause,
571
  and renaming it is one item down in its own `…` menu. */}
 
 
 
 
 
572
  <button
573
  type="button"
574
  role="menuitem"
575
  onClick={() => { setCreateAt(null); onCreateWorkbook(); }}
576
  >
577
- Workbook
578
  </button>
579
  <button
580
  type="button"
581
  role="menuitem"
582
  onClick={() => { setFolderName(""); setNamingFolder(true); }}
583
  >
584
- Folder
 
 
 
 
 
 
 
 
 
 
 
 
585
  </button>
586
  </>
587
  )}
@@ -623,57 +904,184 @@ export default function SheetRail({
623
  </form>
624
  ) : (
625
  <>
626
- {/* ⭐ DUPLICATE IS COMPOSED FROM DOORS THAT ALREADY EXIST (read, create, write) and
627
- needs no route of its own. It is here rather than absent because the Sheet CAN
628
- honour it, which is the test R2 sets. */}
629
- {menu.kind === "workbook" ? (
630
- <button
631
- type="button"
632
- role="menuitem"
633
- onClick={() => { const id = menu.id; closeMenu(); onDuplicateWorkbook(id); }}
634
- >
635
- Duplicate
636
- </button>
637
- ) : null}
638
  <button
639
  type="button"
640
  role="menuitem"
641
  onClick={() => {
642
  const current = menu.kind === "folder"
643
  ? byId[menu.id]?.name ?? ""
644
- : rows.find((r) => r.id === menu.id)?.name ?? "";
645
  setFolderName(current);
646
  setRenaming(menu.id);
647
  }}
648
  >
649
- Rename
650
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
651
  {menu.kind === "workbook" ? (
652
  <button
653
  type="button"
654
  role="menuitem"
655
  onClick={() => { const id = menu.id; closeMenu(); toggleStar(id); }}
656
  >
657
- {isStarred(menu.id) ? "Unstar" : "Star"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  </button>
659
  ) : null}
 
 
 
 
660
  <button
661
  type="button"
662
  role="menuitem"
663
  className="is-danger"
664
  onClick={() => {
665
  const target = menu;
 
 
 
666
  closeMenu();
667
- if (target.kind === "folder") deleteFolder(target.id);
668
- else onDeleteWorkbook(target.id);
669
  }}
670
  >
671
- Delete…
672
  </button>
673
  </>
674
  )}
675
  </AnchoredOverlay>
676
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
677
  </nav>
678
  );
679
  }
 
38
  import { useMemo, useState } from "react";
39
  import type { DragEvent as ReactDragEvent } from "react";
40
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
41
+ import { FolderMark, MenuLabel } from "../customer-grid/icons";
42
+ import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
43
+ import { StarIcon } from "../ui/icons";
44
+ import { ConfirmDialog } from "../ui/ConfirmDialog";
45
+ import ImportDialog from "./ImportDialog";
46
  import { ROOT_FOLDER_ID } from "./types";
47
  import type { SheetFolder, WorkbookRow } from "./types";
48
 
 
56
  export interface SheetRailProps {
57
  loading: boolean;
58
  rows: readonly WorkbookRow[];
59
+ /**
60
+ * W51-T10 (contract C5) β€” the workbooks OTHER people have shared with this account.
61
+ *
62
+ * β›” OPTIONAL, AND ABSENT IS THE ORDINARY CASE TODAY. `GET /sheets/index` grows this list in
63
+ * W51-T25; until it does the server sends nothing, and a section with a heading and no rows
64
+ * would tell a person that sharing exists and has given them nothing. So the whole section is
65
+ * rendered only when the list has something in it.
66
+ */
67
+ sharedWithMe?: readonly WorkbookRow[];
68
  folders: readonly SheetFolder[];
69
  itemFolders: Record<string, string>;
70
  starred: readonly string[];
 
76
  onDeleteWorkbook: (id: string) => void;
77
  /** Every folder, placement and star change goes through this ONE door. */
78
  onStrataChange: (next: RailStrata) => void;
79
+ /**
80
+ * W51-T09 (owner instruction 2, ruling R12) β€” whether the page's assistant dock is open, and
81
+ * the one door that flips it.
82
+ *
83
+ * β›” THE PAGE OWNS THE STATE, NOT THIS RAIL, exactly as `CustomerGrid` owns it for the Data
84
+ * rail. The launcher and the panel are two halves of one thing; a rail holding its own copy
85
+ * would let the button say "close" over a dock that was never open.
86
+ */
87
+ chatOpen: boolean;
88
+ onToggleChat: () => void;
89
  }
90
 
91
+ /**
92
+ * ⭐⭐ THE FOLD KEY IS THE DATA RAIL'S OWN, AND THAT IS THE TICKET RATHER THAN A COINCIDENCE.
93
+ * `ViewSidebar.tsx:1463` reads and writes this same string, the name is after neither module, and
94
+ * that file's own comment says the two rails "are one idea (a navigation bar folds)". The
95
+ * done-when asks for "the same shut state Data uses", so ONE stored state serves both rails and a
96
+ * person who folds the navigation in Data finds it folded here.
97
+ */
98
+ const RAIL_FOLD_KEY = "aios-views-rail";
99
+
100
  /** How many rows the rail draws while it is loading. Matches `Shell.tsx::RAIL_SKELETON_ROWS`. */
101
  const SKELETON_ROWS = 6;
102
 
 
 
 
103
  const STAR_PATH =
104
  "M8 2.9l1.63 3.3 3.64.53-2.63 2.57.62 3.63L8 11.24 4.74 12.93l.62-3.63L2.73 6.73l3.64-.53z";
105
 
 
126
  );
127
  }
128
 
129
+ /**
130
+ * The mark one workbook row wears: a page ruled into cells. 16x16, painted by
131
+ * `.sheet-view-icon` (wave49/sheet.css), which sets the fill, the stroke and the muted tone on the
132
+ * element itself, so the paths carry no attributes of their own.
133
+ *
134
+ * ⭐ W51-T10 β€” THE GEOMETRY IS `SHEET_SHAPE`'s NOW, not a third hand-drawn sheet. The rail's row
135
+ * mark, the create menu's Workbook mark and the shell's nav mark were three drawings of one idea
136
+ * with three sets of coordinates; two of them now read the same constant and the third is the one
137
+ * it was traced from.
138
+ */
139
  function SheetViewIcon() {
140
  return (
141
  <svg className="sheet-view-icon" viewBox="0 0 16 16" aria-hidden="true">
142
+ {SHEET_SHAPE.map((s) => (
143
+ <path key={s.d} d={s.d} />
144
+ ))}
145
  </svg>
146
  );
147
  }
148
 
149
+ /**
150
+ * β›”β›” THESE TWO ARE LOCAL BECAUSE THE COMPONENTS THEY MIRROR CANNOT BE IMPORTED, AND THAT IS A
151
+ * FENCE RATHER THAN A PREFERENCE. `ViewSidebar.tsx::ShareMark` and `Shell.tsx::SheetIcon` are both
152
+ * private to files this lane may not edit this wave, so exporting either one is off the table.
153
+ * What travels instead is the GEOMETRY: `SHARE_SHAPE` and `SHEET_SHAPE` in `iconShapes.ts`, the
154
+ * vocabulary's own home, drawn here at the menu's stroke conventions. This is exactly the
155
+ * precedent `ViewSidebar::ShareMark` set for the same shape, and it keeps the icon LANGUAGE single
156
+ * while touching no other lane's file.
157
+ *
158
+ * ⚠ NOT PAINTED BY A CLASS. A menu row's mark takes its colour from `.cg-view-menu button:hover
159
+ * .cg-mi-ic` and from `.is-danger`; an svg carrying its own `color` rule would out-rank that
160
+ * inheritance and the row's hover state would leave one glyph behind.
161
+ */
162
+ function ShareMark({ size = 16 }: { size?: number }) {
163
  return (
164
+ <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden="true">
165
+ {SHARE_SHAPE.map((s) => (
166
+ <path
167
+ key={s.d}
168
+ d={s.d}
169
+ fill={s.fill ? "currentColor" : "none"}
170
+ stroke={s.fill ? "none" : "currentColor"}
171
+ strokeWidth={1.35}
172
+ strokeLinecap="round"
173
+ strokeLinejoin="round"
174
+ />
175
+ ))}
176
+ </svg>
177
+ );
178
+ }
179
+
180
+ function SheetMark({ size = 16 }: { size?: number }) {
181
+ return (
182
+ <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden="true">
183
+ {SHEET_SHAPE.map((s) => (
184
+ <path
185
+ key={s.d}
186
+ d={s.d}
187
+ fill="none"
188
+ stroke="currentColor"
189
+ strokeWidth={1.35}
190
+ strokeLinecap="round"
191
+ strokeLinejoin="round"
192
+ />
193
+ ))}
194
  </svg>
195
  );
196
  }
 
245
  export default function SheetRail({
246
  loading,
247
  rows,
248
+ sharedWithMe = [],
249
  folders,
250
  itemFolders,
251
  starred,
 
256
  onDuplicateWorkbook,
257
  onDeleteWorkbook,
258
  onStrataChange,
259
+ chatOpen,
260
+ onToggleChat,
261
  }: SheetRailProps) {
262
+ /**
263
+ * W51-T09 β€” IS THE RAIL FOLDED. Read from storage on the first render only, exactly as
264
+ * `ViewSidebar.tsx:1463` does, so the fold survives a reload and a walk between the two modules.
265
+ *
266
+ * β›” THE `try` IS NOT DECORATION. `localStorage` THROWS on a browser with storage blocked, and an
267
+ * unguarded read here would take the whole rail down with it. Blocked storage must still fold
268
+ * for the session, which is what a `false` start plus an ignored write gives.
269
+ */
270
+ const [railShut, setRailShut] = useState<boolean>(() => {
271
+ try { return localStorage.getItem(RAIL_FOLD_KEY) === "1"; } catch { return false; }
272
+ });
273
+ const toggleRail = () => setRailShut((v) => {
274
+ const next = !v;
275
+ try { localStorage.setItem(RAIL_FOLD_KEY, next ? "1" : "0"); } catch { /* session only */ }
276
+ return next;
277
+ });
278
  /** The folder whose contents are on screen, or null for the top level. */
279
  const [at, setAt] = useState<string | null>(null);
280
  /** Windows-style history for the path row's back and forward buttons. */
 
288
  const [folderName, setFolderName] = useState("");
289
  const [dragged, setDragged] = useState<Dragged | null>(null);
290
  const [dropOn, setDropOn] = useState<string | null>(null);
291
+ /**
292
+ * W51-T10 / R13 β€” "Move to folder", the picker the menu item opens.
293
+ *
294
+ * β›” THE MENU CLOSES AND A SECOND OVERLAY OPENS ON THE SAME ANCHOR. That is the Data rail's own
295
+ * shape (`ViewSidebar.tsx`'s `moveFor`), and it is the shape because a picker nested INSIDE the
296
+ * menu overlay would be an outside click as far as the menu's own dismiss handler is concerned:
297
+ * choosing a folder would close the thing being clicked. One overlay at a time, anchored to the
298
+ * `…` button both times, so the picker opens where the menu was.
299
+ */
300
+ const [moveFor, setMoveFor] = useState<{ id: string; anchor: HTMLElement } | null>(null);
301
+ /**
302
+ * W51-T10 / R6 β€” the pending destructive act, or null. ONE ConfirmDialog for the workbook and
303
+ * the folder both, because R6 is about there being one shape for the promise, not one per noun.
304
+ */
305
+ const [confirmDelete, setConfirmDelete] =
306
+ useState<{ kind: "workbook" | "folder"; id: string; name: string } | null>(null);
307
+ /**
308
+ * W51-T13 (owner instruction 7, contract C4) β€” is the import dialog on screen.
309
+ *
310
+ * β›” THE DIALOG IS MOUNTED CONDITIONALLY, AND THAT IS THE RESET. It holds the chosen file, the
311
+ * poll's run token, the job and its report; a component kept mounted behind an `open={false}`
312
+ * would hand the next import the previous one's progress bar, and the previous poll would still
313
+ * be ticking behind it. Unmounting is one of the poll's five terminal conditions.
314
+ */
315
+ const [importing, setImporting] = useState(false);
316
 
317
  const byId = useMemo(() => {
318
  const map: Record<string, SheetFolder> = {};
 
369
 
370
  const levelFolders = folders.filter((f) => (f.parent ?? null) === at && matches(f.name));
371
  const levelRows = rows.filter((r) => placedIn(r.id) === at && matches(r.name));
372
+ /** The shared list obeys the find box like every other row, so one search covers the rail. */
373
+ const sharedRows = sharedWithMe.filter((r) => matches(r.name));
374
 
375
  const isStarred = (id: string) => starred.includes(id);
376
 
 
449
  onStrataChange(next);
450
  };
451
 
452
+ /**
453
+ * W51-T10 / R13 β€” file one workbook into a folder, or back to the top level.
454
+ *
455
+ * ⚠ THE SAME DOOR THE DRAG USES, and deliberately so: `fileInto` already knows that an absent
456
+ * placement and the root sentinel mean the same thing, and that the PUT carries all three strata
457
+ * because a placement is only legal while its folder exists (D-639). A second write path here
458
+ * would be a second chance to send half an index.
459
+ */
460
+ const moveWorkbook = (id: string, target: string | null) => {
461
+ fileInto({ kind: "workbook", id }, target);
462
+ setMoveFor(null);
463
+ };
464
+
465
+ /**
466
+ * W51-T10 / R16 β€” Share. The dispatch is the one channel the other three share controls use,
467
+ * spelled here as the literal exactly as `ColumnMenu.tsx`, `MapView.tsx` and `ViewSidebar.tsx`
468
+ * spell it: the emitter and the dialog live in trees that must not import each other.
469
+ *
470
+ * β›” IT ONLY OPENS ANYTHING BECAUSE `"workbook"` IS IN `SHARE_KINDS`. `parseShareRequest`
471
+ * fail-closes on a kind that tuple does not carry and returns null, so before this ticket a
472
+ * workbook dispatch was DROPPED IN SILENCE: no dialog, no error, nothing in the console.
473
+ */
474
+ const shareWorkbook = (id: string, name: string) => {
475
+ window.dispatchEvent(
476
+ new CustomEvent("aios:share-open", { detail: { kind: "workbook", id, label: name } }),
477
+ );
478
+ };
479
+
480
+ const nameOfWorkbook = (id: string) => rows.find((r) => r.id === id)?.name ?? "";
481
+
482
+ const runDelete = () => {
483
+ const pending = confirmDelete;
484
+ setConfirmDelete(null);
485
+ if (!pending) return;
486
+ if (pending.kind === "folder") deleteFolder(pending.id);
487
+ else onDeleteWorkbook(pending.id);
488
+ };
489
+
490
  const createFolder = () => {
491
  const clean = cleanName(folderName);
492
  if (!clean) return;
 
499
  };
500
 
501
  return (
502
+ <nav
503
+ className={"cg-views" + (railShut ? " is-collapsed" : "")}
504
+ aria-label="Sheet workbooks"
505
+ >
506
+ <div className="cg-views-top">
507
+ {/* β›”β›” THIS WRAPPER IS FIRST, AND THE POSITION IS THE WHOLE CONTROL. `index.css:450` is
508
+ `.cg-views.is-collapsed > :not(.cg-views-top) { display: none }`, so folding the rail
509
+ hides EVERY child except this one. Measured in the live DOM before this ticket: the
510
+ Sheet rail had no `.cg-views-top` at all, and collapsing it by hand took it to 48px
511
+ with all four of its children hidden and nothing left on screen. A minimize button
512
+ anywhere else compiles, styles and photographs perfectly, then HIDES ITSELF on the
513
+ first click with no way to unfold the rail again.
514
+ ⚠ NOTHING BELOW IT IS RESTRUCTURED. The two rails differ completely under this row
515
+ (the Data rail's `cg-data-tree` against this rail's path, create, find and level) and
516
+ that is correct: the fold is shared, the contents are not. */}
517
+ <button
518
+ type="button"
519
+ className="cg-rail-toggle"
520
+ aria-label={railShut ? "Expand views" : "Minimize views"}
521
+ aria-expanded={!railShut}
522
+ title={railShut ? "Expand views" : "Minimize views"}
523
+ onClick={toggleRail}
524
+ >
525
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
526
+ <path
527
+ d="M2.5 4.4h11M2.5 8h11M2.5 11.6h11"
528
+ stroke="currentColor"
529
+ strokeWidth="1.35"
530
+ strokeLinecap="round"
531
+ />
532
+ </svg>
533
+ </button>
534
+ {/* β›”β›” THE `!railShut` GUARD IS OWNER INSTRUCTION 5 OF WAVE 40, NOT A TIDY-UP: *"when the
535
+ Database navigation is minimized it must disappear from the secondary navigation
536
+ too."* A RENDER guard rather than a CSS hide, for the reason `ViewSidebar.tsx` records
537
+ at its own copy: the collapse rule above deliberately SPARES this row's children, so a
538
+ CSS answer would mean carving an exception into the rule written to protect them.
539
+ ⚠ The minimize toggle beside it stays unguarded on purpose. Folding the rail closes
540
+ the last door onto the dock, so the control that unfolds it must survive the fold. */}
541
+ {!railShut && (
542
+ <button
543
+ type="button"
544
+ className={"cg-chat-toggle" + (chatOpen ? " is-on" : "")}
545
+ aria-label={chatOpen ? "Close the chat about this data"
546
+ : "Ask about this data"}
547
+ aria-expanded={chatOpen}
548
+ title={chatOpen ? "Close the chat about this data" : "Ask about this data"}
549
+ onClick={onToggleChat}
550
+ >
551
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
552
+ <path d="M13.4 9.2c0 1.5-1.3 2.7-2.9 2.7H6.9l-3 2.1v-2.3a2.8 2.8 0 0 1-1.3-2.3V5.1c0-1.5 1.3-2.7 2.9-2.7h5c1.6 0 2.9 1.2 2.9 2.7z"
553
+ stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" />
554
+ <path d="M5.9 7.2h4.2" stroke="currentColor" strokeWidth="1.3"
555
+ strokeLinecap="round" />
556
+ </svg>
557
+ </button>
558
+ )}
559
+ </div>
560
+
561
  {loading ? (
562
  <RailSkeleton />
563
  ) : (
 
616
  </nav>
617
 
618
  {/* ⚠ `cg-data-create` WRAPS `cg-create-new`, which is the nesting the Data rail uses:
619
+ the outer class is the host's slot and the inner one is the control.
620
+ β›” W51-T09 CORRECTS WHAT THIS COMMENT USED TO CLAIM. It said flattening the pair
621
+ "loses the 8px the outer wrapper contributes"; measured, the 8px is `.cg-create-new`'s
622
+ OWN `margin-top` (index.css:504) and the wrapper contributes nothing on this page at
623
+ all. What the wrapper does contribute is a BOX TYPE, and that was the real difference:
624
+ in the Data rail `.cg-create-new` is a flex item of `.cg-data-database-views` and
625
+ computed `min-height: auto`, while here it was a block child and computed `0px`. The
626
+ slot is a flex column in `styles/wave50/sheet.css` for exactly that reason. */}
627
  <div className="cg-data-create">
628
  <div className="cg-create-new">
629
  <button
 
655
  </div>
656
 
657
  {/* THE LEVEL. `cg-fold-root` is the Data rail's own drop target for "file it here",
658
+ and dropping on it moves the dragged row into the folder currently open.
659
+ β›”β›” W51-T09 β€” IT IS A BLOCK NOW, AND THAT IS A MEASURED FIX RATHER THAN A TIDY-UP.
660
+ `.sheet-rail-level` made this a flex COLUMN with a 2px gap. `min-height: auto`
661
+ resolves to the keyword `auto` for a flex ITEM and to `0px` for anything else, so
662
+ every `.cg-view-row` in here computed `auto` while the Data rail's computed `0px` β€”
663
+ the owner's "not exactly the same format". The Data rail's rows sit in a plain block
664
+ `.cg-fold-root` inside a flex `.cg-view-list`, so the row rhythm there comes from the
665
+ LIST between fold groups and rows inside one group are flush. Matching that is what
666
+ makes the two computed styles identical, and the gap went with the class. */}
667
  <div
668
  className={
669
+ "cg-views-scroll cg-fold-root"
670
  + (dropOn === "__level__" ? " is-drop" : "")
671
  }
672
  {...dropProps(at, "__level__")}
 
695
  aria-label={`Open folder ${folder.name}`}
696
  onClick={() => goTo(folder.id)}
697
  >
698
+ <FolderMark size={16} />
699
  <span className="cg-fold-name">{folder.name}</span>
700
  </button>
701
  <button
 
764
  {needle ? "No workbook here matches what you typed." : "Nothing filed here yet."}
765
  </p>
766
  ) : null}
767
+
768
+ {/* ⭐⭐ W51-T10 / CONTRACT C5 β€” "SHARED TO ME", AND IT IS ABSENT UNTIL SOMEBODY SHARES.
769
+ The list arrives on `GET /sheets/index` once W51-T25 serves it; today it is empty,
770
+ and an empty heading would announce a feature that has given this account nothing.
771
+ So the guard is on the ROWS, not on the flag.
772
+ β›” NO `…` MENU ON THESE ROWS. Rename, Duplicate, Star, Move and Delete are all acts
773
+ on a workbook you own; a shared one is somebody else's, and the strata that would
774
+ record a star or a placement are the OWNER's index, not this reader's. Wave-49 R2
775
+ again: a control that cannot be honoured is absent.
776
+ ⚠ TOP LEVEL ONLY. These workbooks are not filed into this account's folders, so
777
+ repeating them inside every folder would say they were. */}
778
+ {at === null && sharedRows.length > 0 ? (
779
+ <div className="sheet-shared">
780
+ <p className="sheet-shared-head">Shared to me</p>
781
+ {sharedRows.map((row) => (
782
+ <div
783
+ key={row.id}
784
+ className={"cg-view-row" + (row.id === activeId ? " is-active" : "")}
785
+ >
786
+ <button
787
+ type="button"
788
+ className="cg-view-main"
789
+ aria-current={row.id === activeId ? "true" : undefined}
790
+ onClick={() => onOpen(row.id)}
791
+ >
792
+ <SheetViewIcon />
793
+ <span className="cg-view-text">
794
+ <span className="cg-view-name">{row.name}</span>
795
+ </span>
796
+ </button>
797
+ </div>
798
+ ))}
799
+ </div>
800
+ ) : null}
801
  </div>
802
  </>
803
  )}
 
833
  {/* β›” A WORKBOOK IS MADE AND OPENED IN ONE ACT, with no name step. The page shows
834
  the new workbook the moment the server answers, which is the done-when clause,
835
  and renaming it is one item down in its own `…` menu. */}
836
+ {/* ⭐ W51-T10 β€” EACH ROW WEARS A MARK, THROUGH `MenuLabel`, so the icon slot and the
837
+ label sit in the `cg-mi-ic` / `cg-mi-text` anatomy `index.css` already paints for
838
+ the Data rail's menus. A Workbook wears the Sheet module's own glyph and a Folder
839
+ wears `FolderMark`: the two things this rail can make, each named by the mark it
840
+ will wear once it exists. */}
841
  <button
842
  type="button"
843
  role="menuitem"
844
  onClick={() => { setCreateAt(null); onCreateWorkbook(); }}
845
  >
846
+ <MenuLabel icon={<SheetMark size={16} />} text="Workbook" />
847
  </button>
848
  <button
849
  type="button"
850
  role="menuitem"
851
  onClick={() => { setFolderName(""); setNamingFolder(true); }}
852
  >
853
+ <MenuLabel icon={<FolderMark size={16} />} text="Folder" />
854
+ </button>
855
+ {/* ⭐⭐ W51-T13 (owner instruction 7, ruling R1) β€” THE THIRD THING THIS RAIL CAN
856
+ MAKE: a workbook that already exists somewhere else. It sits with Workbook and
857
+ Folder because those two and this one answer the same question ("where does a new
858
+ workbook come from"), and it wears `upload` from `MENU_ICONS`, which is the
859
+ vocabulary's own word for bytes arriving from outside. Nothing new was drawn. */}
860
+ <button
861
+ type="button"
862
+ role="menuitem"
863
+ onClick={() => { setCreateAt(null); setImporting(true); }}
864
+ >
865
+ <MenuLabel icon="upload" text="Import .xlsx" />
866
  </button>
867
  </>
868
  )}
 
904
  </form>
905
  ) : (
906
  <>
907
+ {/* ⭐⭐ W51-T10 / R13 β€” THE WORKBOOK MENU IS THE VIEW MENU'S, WITH SHARE. Rename,
908
+ Duplicate, Star or Unstar, Move to folder, Share, Delete, IN THAT ORDER, each
909
+ through `MenuLabel` with the view menu's own icon component. The order is the
910
+ ruling's; before this ticket Duplicate came first and only four of the six
911
+ existed.
912
+ β›” A FOLDER KEEPS THE REDUCED SET (Rename and Delete). Wave-49 R2: a control the
913
+ rail cannot honour is ABSENT, not present and inert. There is no duplicate-folder
914
+ door, no folder star stratum and no folder share kind, and a folder already moves
915
+ by drag, so offering four dead rows would be four fake affordances. */}
 
 
 
916
  <button
917
  type="button"
918
  role="menuitem"
919
  onClick={() => {
920
  const current = menu.kind === "folder"
921
  ? byId[menu.id]?.name ?? ""
922
+ : nameOfWorkbook(menu.id);
923
  setFolderName(current);
924
  setRenaming(menu.id);
925
  }}
926
  >
927
+ <MenuLabel icon="rename" text="Rename" />
928
  </button>
929
+ {/* ⭐ DUPLICATE IS COMPOSED FROM DOORS THAT ALREADY EXIST (read, create, write) and
930
+ needs no route of its own. It is here rather than absent because the Sheet CAN
931
+ honour it, which is the test R2 sets. */}
932
+ {menu.kind === "workbook" ? (
933
+ <button
934
+ type="button"
935
+ role="menuitem"
936
+ onClick={() => { const id = menu.id; closeMenu(); onDuplicateWorkbook(id); }}
937
+ >
938
+ <MenuLabel icon="duplicate" text="Duplicate" />
939
+ </button>
940
+ ) : null}
941
  {menu.kind === "workbook" ? (
942
  <button
943
  type="button"
944
  role="menuitem"
945
  onClick={() => { const id = menu.id; closeMenu(); toggleStar(id); }}
946
  >
947
+ <MenuLabel
948
+ icon={<StarIcon size={16} filled={isStarred(menu.id)} />}
949
+ text={isStarred(menu.id) ? "Unstar" : "Star"}
950
+ />
951
+ </button>
952
+ ) : null}
953
+ {menu.kind === "workbook" ? (
954
+ <button
955
+ type="button"
956
+ role="menuitem"
957
+ onClick={() => {
958
+ const target = { id: menu.id, anchor: menu.anchor };
959
+ closeMenu();
960
+ setMoveFor(target);
961
+ }}
962
+ >
963
+ <MenuLabel icon={<FolderMark size={16} />} text="Move to folder" />
964
+ </button>
965
+ ) : null}
966
+ {menu.kind === "workbook" ? (
967
+ <button
968
+ type="button"
969
+ role="menuitem"
970
+ onClick={() => {
971
+ const id = menu.id;
972
+ const name = nameOfWorkbook(id);
973
+ closeMenu();
974
+ shareWorkbook(id, name);
975
+ }}
976
+ >
977
+ <MenuLabel icon={<ShareMark size={16} />} text="Share" />
978
  </button>
979
  ) : null}
980
+ {/* β›”β›” R6 β€” THE DELETE ASKS FIRST, AND UNTIL THIS TICKET IT DID NOT. One click on
981
+ this row removed a workbook and everything in it with no confirmation anywhere in
982
+ `src/sheet/`: no dialog, no armed second click, not even a native confirm. The
983
+ row now only ARMS the one `ConfirmDialog` the whole app shares. */}
984
  <button
985
  type="button"
986
  role="menuitem"
987
  className="is-danger"
988
  onClick={() => {
989
  const target = menu;
990
+ const name = target.kind === "folder"
991
+ ? byId[target.id]?.name ?? ""
992
+ : nameOfWorkbook(target.id);
993
  closeMenu();
994
+ setConfirmDelete({ kind: target.kind, id: target.id, name });
 
995
  }}
996
  >
997
+ <MenuLabel icon="trash" text="Delete" />
998
  </button>
999
  </>
1000
  )}
1001
  </AnchoredOverlay>
1002
  ) : null}
1003
+
1004
+ {/* ⭐ W51-T10 / R13 β€” THE FOLDER PICKER, ANCHORED WHERE THE MENU WAS. Same anatomy as the
1005
+ Data rail's own move picker (`cg-pop`, `cg-pop-title`, `cg-pop-list`, `cg-pick-row`), so
1006
+ the two rails ask the same question the same way. Every folder in the workbook index is
1007
+ offered, flat: this rail navigates folders by walking INTO them rather than by unfolding
1008
+ a tree, so a path is the honest label and an indent would draw a shape the rail does not
1009
+ otherwise have. The folder a workbook is already in is marked, and Top level is a row
1010
+ rather than a "remove from folder" verb, because moving to the top is a move. */}
1011
+ {moveFor ? (
1012
+ <AnchoredOverlay
1013
+ anchor={moveFor.anchor}
1014
+ className="cg-pop"
1015
+ role="dialog"
1016
+ ariaLabel={`Move ${nameOfWorkbook(moveFor.id)} to a folder`}
1017
+ placement="right-start"
1018
+ onDismiss={() => setMoveFor(null)}
1019
+ >
1020
+ <div className="cg-pop-title">Move to folder</div>
1021
+ <div className="cg-pop-list">
1022
+ <button
1023
+ type="button"
1024
+ className={"cg-pick-row" + (placedIn(moveFor.id) === null ? " is-on" : "")}
1025
+ onClick={() => moveWorkbook(moveFor.id, null)}
1026
+ >
1027
+ <FolderMark size={16} />
1028
+ Top level
1029
+ </button>
1030
+ {folders.map((folder) => (
1031
+ <button
1032
+ key={folder.id}
1033
+ type="button"
1034
+ className={
1035
+ "cg-pick-row" + (placedIn(moveFor.id) === folder.id ? " is-on" : "")
1036
+ }
1037
+ onClick={() => moveWorkbook(moveFor.id, folder.id)}
1038
+ >
1039
+ <FolderMark size={16} />
1040
+ {folder.name}
1041
+ </button>
1042
+ ))}
1043
+ {folders.length === 0 ? (
1044
+ <div className="cg-pop-note">
1045
+ There are no folders yet. Create one from Create new.
1046
+ </div>
1047
+ ) : null}
1048
+ </div>
1049
+ </AnchoredOverlay>
1050
+ ) : null}
1051
+
1052
+ {/* β›”β›” R6 / CONTRACT C8 β€” THE ONE CONFIRM DIALOG, NOT A SECOND ONE SHAPED LIKE IT. It brings
1053
+ the centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap,
1054
+ Escape, the backdrop and the return of focus to the opener. Re-implementing any of that
1055
+ here would be the second shape DESIGN.md Β§4 refuses.
1056
+ ⚠ THE TITLE IS A QUESTION on purpose, and it is the done-when's own wording: a title that
1057
+ names the workbook is what stops a person confirming the wrong one from muscle memory. */}
1058
+ <ConfirmDialog
1059
+ open={Boolean(confirmDelete)}
1060
+ title={`Delete ${confirmDelete?.name ?? ""}?`}
1061
+ body={
1062
+ confirmDelete?.kind === "folder"
1063
+ ? "The workbooks inside it are not deleted. They move back to the top level."
1064
+ : "This deletes the workbook and every sheet in it. It cannot be undone."
1065
+ }
1066
+ confirmLabel="Delete"
1067
+ tone="destructive"
1068
+ onConfirm={runDelete}
1069
+ onCancel={() => setConfirmDelete(null)}
1070
+ />
1071
+
1072
+ {/* ⭐ W51-T13 / CONTRACT C4 β€” THE IMPORT DIALOG, MOUNTED WHERE ITS DOOR IS. The create menu
1073
+ is this rail's, so the dialog it opens is this rail's too, and mounting it here needs no
1074
+ edit to `SheetPage.tsx` at all.
1075
+ β›” `onOpened` IS THE RAIL'S OWN `onOpen`, which is the page's `openWorkbook`. An import
1076
+ that finished and left the person looking at the dialog would have done the work and
1077
+ hidden the result. */}
1078
+ {importing ? (
1079
+ <ImportDialog
1080
+ open
1081
+ onCancel={() => setImporting(false)}
1082
+ onOpened={(workbookId) => { setImporting(false); onOpen(workbookId); }}
1083
+ />
1084
+ ) : null}
1085
  </nav>
1086
  );
1087
  }
web/src/sheet/ShortcutsPanel.tsx ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/ShortcutsPanel.tsx β€” W51-T17, the Ctrl+/ panel (ruling R7, contract C8).
2
+ //
3
+ // ⭐⭐ THIS FILE CONTAINS NO CHORDS. Every row it renders comes from `shortcuts.ts::SHORTCUTS`,
4
+ // the same table `SheetGrid.tsx::onKeyDown` matches against, so the panel cannot advertise a key
5
+ // the handler does not answer and the handler cannot answer a key the panel does not show.
6
+ // `verify_api.py` asserts BOTH halves of that: this file maps over the table, and no chord shaped
7
+ // string literal survives in its own source. A hand written list that happens to agree today is
8
+ // exactly the defect the clause exists to stop, and it would agree right up until somebody added
9
+ // the thirty first shortcut.
10
+ //
11
+ // β›” IT IS A REACT COMPONENT AND IS NEVER NODE COMPILED, which is why it MAY import the base kit
12
+ // (`../ui/useEscapeClose`). `shortcuts.ts` may not: tsc's emitted root moves with the import
13
+ // graph and the Sheet's node proofs `require` `sheetState.js` at the top of the out directory.
14
+ //
15
+ // ⭐⭐ CONTRACT C8, AMENDMENT A2 β€” THE ESCAPE DECISION, MADE DELIBERATELY AND SAID OUT LOUD.
16
+ // A2 makes "first Escape cancels a live text edit, the second closes" OPT IN per overlay and
17
+ // names the Sheet's right side panels as the family that opts in. This is one of those panels, so
18
+ // it opts IN and passes its own `container`, which is what lets the arbiter decide whether the
19
+ // focus is inside it at all. In practice the option is inert here, because the panel holds no
20
+ // text input to cancel; opting in keeps the family's rule true rather than leaving one member of
21
+ // it behaving differently for a reason nobody would remember.
22
+ //
23
+ // β›” THERE IS NO SECOND ESCAPE LISTENER. `useEscapeClose` is the one arbiter, topmost wins, and a
24
+ // `document.addEventListener("keydown", …)` added here would race it and win or lose depending on
25
+ // registration order.
26
+ //
27
+ // ⚠ DESIGN CONTRACT: sentence case, scale tokens only and no literal font-size, tokens never
28
+ // hues, inline SVG on `currentColor` and no emoji, 150 ms ease-out on opacity and transform, and
29
+ // no em dash or en dash in any string that reaches a screen.
30
+
31
+ import { useRef } from "react";
32
+ import { useEscapeClose } from "../ui/useEscapeClose";
33
+ import { SHORTCUTS } from "./shortcuts";
34
+
35
+ export interface ShortcutsPanelProps {
36
+ open: boolean;
37
+ onClose: () => void;
38
+ }
39
+
40
+ /** The close cross. An inline SVG on `currentColor`, never a glyph and never an emoji. */
41
+ function IconClose() {
42
+ return (
43
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-shortcuts-icon">
44
+ <path d="M4.5 4.5l7 7M11.5 4.5l-7 7" />
45
+ </svg>
46
+ );
47
+ }
48
+
49
+ export default function ShortcutsPanel({ open, onClose }: ShortcutsPanelProps) {
50
+ const boxRef = useRef<HTMLDivElement | null>(null);
51
+ useEscapeClose(open, onClose, {
52
+ cancelEditFirst: true,
53
+ container: () => boxRef.current,
54
+ });
55
+ if (!open) return null;
56
+
57
+ return (
58
+ <div
59
+ className="sheet-shortcuts"
60
+ role="dialog"
61
+ aria-label="Keyboard shortcuts"
62
+ ref={boxRef}
63
+ >
64
+ <div className="sheet-shortcuts-head">
65
+ <h2 className="sheet-shortcuts-title">Keyboard shortcuts</h2>
66
+ <button
67
+ type="button"
68
+ className="sheet-shortcuts-close"
69
+ aria-label="Close the shortcuts list"
70
+ title="Close the shortcuts list"
71
+ onMouseDown={(e) => e.preventDefault()}
72
+ onClick={onClose}
73
+ >
74
+ <IconClose />
75
+ </button>
76
+ </div>
77
+
78
+ {/* ⭐⭐ ONE ROW PER TABLE ENTRY, AND NOTHING ELSE. No filter, no slice and no second list:
79
+ the panel's contents ARE the table, which is the only shape in which the two cannot
80
+ drift. `when` is shown because a shortcut that needs a selection and one that does not
81
+ are different promises, and a panel that hides the difference teaches the wrong thing. */}
82
+ <ul className="sheet-shortcuts-list">
83
+ {SHORTCUTS.map((entry) => (
84
+ <li className="sheet-shortcuts-row" key={entry.id}>
85
+ <kbd className="sheet-shortcuts-keys">{entry.keys}</kbd>
86
+ <span className="sheet-shortcuts-action">{entry.action}</span>
87
+ <span className="sheet-shortcuts-when">{entry.when}</span>
88
+ </li>
89
+ ))}
90
+ </ul>
91
+
92
+ <p className="sheet-shortcuts-foot">
93
+ Press Escape to close this list.
94
+ </p>
95
+ </div>
96
+ );
97
+ }
web/src/sheet/rules.ts ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------------------------
2
+ // sheet/rules.ts β€” W51-T18, conditional formatting (contract C2, rulings R1 and R8).
3
+ //
4
+ // ⭐⭐ A RULE'S STYLE IS NEVER WRITTEN INTO A CELL. It is computed at paint. That is the whole
5
+ // difference between a rule a person can still edit and a rule that has already smeared itself
6
+ // across the document: once the fill is in `cell.style`, deleting the rule leaves every cell it
7
+ // ever touched painted, with nothing on the screen to explain why. So this module answers ONE
8
+ // question β€” "which style does this address get?" β€” as a pure function of the tab's rule list and
9
+ // the cell's own `{value, text}`, and `SheetGrid.tsx::drawCell` overlays the answer at paint time.
10
+ //
11
+ // β›”β›” NOTHING HERE MAY IMPORT OUTSIDE `src/sheet/`. tsc's emitted ROOT moves with the import
12
+ // graph, and `verify_api.py` compiles this module beside `sheetState.js` into
13
+ // `node_modules/.aios-test-sheet` and `require`s it from there. One import of `../ui` would drop
14
+ // every emitted module a level down and break every `require` path the battery's Sheet proofs
15
+ // already use. `./types` and `./a1` are sheet-local and safe; the DIALOG is React, is never node
16
+ // compiled, and may import the base kit.
17
+ //
18
+ // ⭐ ORDER IS PART OF THE ANSWER, AND IT IS ANSWERED WHOLESALE. Two rules matching one cell is
19
+ // ordinary in Excel. This module says: THE FIRST MATCHING RULE IN THE LIST WINS, and it wins the
20
+ // WHOLE style rather than contributing the keys the ones below it did not set. A per-aspect merge
21
+ // reads as reasonable until a person deletes the top rule and a bold they never asked for appears
22
+ // from a rule three rows down. One rule paints one cell; the dialog says so in those words and
23
+ // `_test/sheetRules.test.ts` drives a fill-only rule above a bold-only one and asserts the bold
24
+ // never lands.
25
+ // ---------------------------------------------------------------------------------------------
26
+
27
+ import { colToIndex, parseRef } from "./a1";
28
+ import { MAX_SHEET_RULES, SHEET_RULE_OPS } from "./types";
29
+ import type { Cell, SheetRule, SheetRuleOp } from "./types";
30
+
31
+ /**
32
+ * β›” C2's WIRE VOCABULARY AND THE DONE-WHEN's LABELS ARE TWO DIFFERENT LISTS, mapped here and
33
+ * nowhere else. `gt` is what the document stores and what `core/sheets.py::SHEET_RULE_OPS` will
34
+ * grep for; "Greater than" is what a person reads. Letting the two drift means a picker offering
35
+ * a word that stores nothing, so the map is exhaustive over `SheetRuleOp` and tsc enforces it.
36
+ *
37
+ * ⚠ SENTENCE CASE, and no em dash or en dash anywhere in it (DESIGN.md 2, standing rule 2).
38
+ */
39
+ export const RULE_OP_LABEL: Record<SheetRuleOp, string> = {
40
+ gt: "Greater than",
41
+ lt: "Less than",
42
+ gte: "At least",
43
+ lte: "At most",
44
+ eq: "Equal",
45
+ neq: "Not equal",
46
+ between: "Between",
47
+ contains: "Text contains",
48
+ empty: "Is empty",
49
+ notEmpty: "Is not empty",
50
+ };
51
+
52
+ /** The ops in the order the picker offers them, which is the done-when's own order. */
53
+ export const RULE_OPS: readonly SheetRuleOp[] = SHEET_RULE_OPS;
54
+
55
+ /** How many value boxes an op needs: two for `between`, none for the empty pair, one otherwise. */
56
+ export const ruleArity = (op: SheetRuleOp): 0 | 1 | 2 => {
57
+ if (op === "empty" || op === "notEmpty") return 0;
58
+ return op === "between" ? 2 : 1;
59
+ };
60
+
61
+ /**
62
+ * β›” THE PALETTE IS TOKEN NAMES, AND THEY ARE THE RIBBON'S OWN.
63
+ *
64
+ * `Ribbon.tsx` holds `INKS` and `FILLS` as module constants and does not export them, and
65
+ * `Ribbon.tsx` is not in this ticket's fence. So the two lists are restated here with the SAME
66
+ * token names, and `verify_api.py` compares them literal for literal: a palette entry added or
67
+ * renamed on either side reds the gate rather than leaving a rules dialog offering a colour the
68
+ * ribbon retired. A hex would outlive every palette change and is forbidden outright (DESIGN.md 3).
69
+ */
70
+ export const RULE_FILLS: readonly { token: string; label: string }[] = [
71
+ { token: "--lp-surface-2", label: "Grey" },
72
+ { token: "--lp-blue-tint", label: "Blue" },
73
+ { token: "--lp-green-tint", label: "Green" },
74
+ { token: "--lp-yellow-tint", label: "Amber" },
75
+ { token: "--lp-red-tint", label: "Red" },
76
+ { token: "--lp-purple-tint", label: "Purple" },
77
+ ];
78
+
79
+ /** The inks, which are the text safe end of the same hues (DESIGN.md 3). */
80
+ export const RULE_INKS: readonly { token: string; label: string }[] = [
81
+ { token: "--lp-ink", label: "Default" },
82
+ { token: "--lp-muted", label: "Muted" },
83
+ { token: "--lp-blue-deep", label: "Blue" },
84
+ { token: "--lp-green-deep", label: "Green" },
85
+ { token: "--lp-yellow-deep", label: "Amber" },
86
+ { token: "--lp-red-deep", label: "Red" },
87
+ { token: "--lp-purple-deep", label: "Purple" },
88
+ ];
89
+
90
+ /** What a rule may paint. A subset of `CellStyle` on purpose: nothing here moves a pixel of
91
+ * geometry, because a rule that changed a row's height would repaint the sheet as data arrived. */
92
+ export type RuleStyle = SheetRule["style"];
93
+
94
+ /** What a rule is asked about: the cell's value and the text a reader actually sees. */
95
+ export interface RuleSubject {
96
+ value: unknown;
97
+ text: string;
98
+ }
99
+
100
+ /**
101
+ * The subject of an address, from the cell record that may not exist.
102
+ *
103
+ * β›”β›” AN ABSENT CELL IS A REAL SUBJECT, AND THIS IS THE HALF THAT GETS MISSED. `is empty` is one
104
+ * of the ten operators, so a rule over `B2:D40` is asked about addresses with NO record at all:
105
+ * a blank cell is not an address the rule engine may skip, it is the exact case that operator
106
+ * exists for. Returning `{value: null, text: ""}` for `null` is what makes that reachable.
107
+ *
108
+ * ⚠ A REFUSED CELL IS NOT ITS SENTENCE. `displayText` hands back the refusal message for one, and
109
+ * running "You do not have access to this view." through `contains` would match a rule looking for
110
+ * the word "access" in the DATA. A refused cell has no value, so it reads as empty.
111
+ */
112
+ export const ruleSubject = (cell: Cell | null | undefined): RuleSubject => {
113
+ if (!cell || cell.kind === "empty") return { value: null, text: "" };
114
+ if (cell.state === "refused") return { value: null, text: "" };
115
+ const value = cell.value;
116
+ const text = cell.display ?? (value == null ? (cell.text ?? "") : String(value));
117
+ return { value: value == null ? (cell.text ?? null) : value, text: String(text ?? "") };
118
+ };
119
+
120
+ /**
121
+ * The number a comparison is made on, or `null` when there is not one.
122
+ *
123
+ * ⚠ IT MIRRORS `types.ts::asNumber` DELIBERATELY rather than importing it, because the two answer
124
+ * different questions: that one decides whether a FORMAT applies, this one decides whether a
125
+ * numeric comparison is possible at all. They agree today; if one ever has to change, the other
126
+ * must not follow it by accident.
127
+ */
128
+ const asNumeric = (raw: unknown): number | null => {
129
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
130
+ if (typeof raw === "boolean") return null;
131
+ if (typeof raw !== "string") return null;
132
+ const trimmed = raw.replace(/[,\s]/g, "");
133
+ if (trimmed === "") return null;
134
+ const n = Number(trimmed);
135
+ return Number.isFinite(n) ? n : null;
136
+ };
137
+
138
+ /**
139
+ * β›”β›” ZERO IS NOT EMPTY, AND THAT IS THE CLASSIC BUG THIS FUNCTION EXISTS TO NAME.
140
+ *
141
+ * `!value` is true for `0`, for `""`, for `null` and for `false`, so the obvious one-liner paints
142
+ * every zero in a column as a hole in the data. A cell is empty when it holds NOTHING: no value
143
+ * and no text. A zero is a number somebody either typed or computed, and a rule reading "is empty"
144
+ * must leave it alone.
145
+ */
146
+ export const isEmptySubject = (subject: RuleSubject): boolean => {
147
+ const { value, text } = subject;
148
+ if (value === null || value === undefined) return String(text ?? "").trim() === "";
149
+ if (typeof value === "string") return value.trim() === "";
150
+ return false;
151
+ };
152
+
153
+ /**
154
+ * Does one rule match one subject? THE ten operators, and nothing else reaches them.
155
+ *
156
+ * ⚠ A NUMERIC OPERATOR AGAINST TEXT FALLS BACK TO A TEXT COMPARISON rather than refusing, because
157
+ * a person comparing account codes reasonably expects `eq` to work on `"A-100"`. The four
158
+ * inequalities need an ordering, so they answer FALSE where neither side reads as a number: a
159
+ * silent lexicographic ">" would report that "9" is greater than "10".
160
+ */
161
+ export const matchesRule = (rule: SheetRule, subject: RuleSubject): boolean => {
162
+ const op = rule.op;
163
+ if (op === "empty") return isEmptySubject(subject);
164
+ if (op === "notEmpty") return !isEmptySubject(subject);
165
+
166
+ const text = String(subject.text ?? "");
167
+ if (op === "contains") {
168
+ const needle = String(rule.value ?? "");
169
+ if (needle === "") return false;
170
+ return text.toLowerCase().indexOf(needle.toLowerCase()) >= 0;
171
+ }
172
+
173
+ const left = asNumeric(subject.value != null ? subject.value : text);
174
+ const right = asNumeric(rule.value);
175
+
176
+ if (op === "eq" || op === "neq") {
177
+ const same = left !== null && right !== null
178
+ ? left === right
179
+ : text.trim().toLowerCase() === String(rule.value ?? "").trim().toLowerCase();
180
+ return op === "eq" ? same : !same;
181
+ }
182
+
183
+ if (op === "between") {
184
+ const lo = asNumeric(rule.value);
185
+ const hi = asNumeric(rule.value2);
186
+ if (left === null || lo === null || hi === null) return false;
187
+ // ⚠ THE BOUNDS ARE SORTED, so a person who typed the larger number first still gets the band
188
+ // they meant rather than a rule that can never match.
189
+ const low = Math.min(lo, hi);
190
+ const high = Math.max(lo, hi);
191
+ return left >= low && left <= high;
192
+ }
193
+
194
+ if (left === null || right === null) return false;
195
+ if (op === "gt") return left > right;
196
+ if (op === "lt") return left < right;
197
+ if (op === "gte") return left >= right;
198
+ return left <= right;
199
+ };
200
+
201
+ /** A rectangle of the sheet, zero based and inclusive, as a rule's `range` resolves to. */
202
+ export interface RuleRect {
203
+ col0: number;
204
+ row0: number;
205
+ col1: number;
206
+ row1: number;
207
+ }
208
+
209
+ /**
210
+ * `B2:D40`, `B2` or `B2:B2` as a rectangle, or `null` when the text is not a range at all.
211
+ *
212
+ * ⚠ THE CORNERS ARE NORMALISED. `D40:B2` is the same rectangle a person dragged the other way,
213
+ * and a rule that only matched when the anchor happened to be top left would be a rule that works
214
+ * for whoever wrote it and for nobody who edits it.
215
+ */
216
+ export const parseRange = (range: string): RuleRect | null => {
217
+ const text = String(range ?? "").trim();
218
+ if (!text) return null;
219
+ const parts = text.split(":");
220
+ if (parts.length > 2) return null;
221
+ const a = parseRef(parts[0]);
222
+ const b = parseRef(parts[parts.length - 1]);
223
+ if (!a || !b || a.sheet || b.sheet) return null;
224
+ const c0 = colToIndex(a.col) - 1;
225
+ const c1 = colToIndex(b.col) - 1;
226
+ const r0 = a.row - 1;
227
+ const r1 = b.row - 1;
228
+ return {
229
+ col0: Math.min(c0, c1), col1: Math.max(c0, c1),
230
+ row0: Math.min(r0, r1), row1: Math.max(r0, r1),
231
+ };
232
+ };
233
+
234
+ /** Does a rule's range cover this zero-based cell? `false` for a range that does not parse. */
235
+ export const rangeCovers = (range: string, col: number, row: number): boolean => {
236
+ const rect = parseRange(range);
237
+ if (!rect) return false;
238
+ return col >= rect.col0 && col <= rect.col1 && row >= rect.row0 && row <= rect.row1;
239
+ };
240
+
241
+ /**
242
+ * ⭐⭐ THE ONE QUESTION THIS MODULE ANSWERS: which style does this address get?
243
+ *
244
+ * `null` means no rule applies, which is what lets `drawCell` keep handing an unstyled cell back
245
+ * to glide. THE FIRST MATCHING RULE WINS, WHOLESALE (see the head note), so the walk stops at the
246
+ * first hit rather than folding the rest in.
247
+ */
248
+ export const ruleStyleAt = (
249
+ rules: readonly SheetRule[] | null | undefined,
250
+ col: number,
251
+ row: number,
252
+ subject: RuleSubject,
253
+ ): RuleStyle | null => {
254
+ for (const rule of rules ?? []) {
255
+ if (!rule || !rule.style) continue;
256
+ if (!rangeCovers(rule.range, col, row)) continue;
257
+ if (!matchesRule(rule, subject)) continue;
258
+ return rule.style;
259
+ }
260
+ return null;
261
+ };
262
+
263
+ /**
264
+ * A rule's style laid OVER the cell's own, as `drawCell` paints it.
265
+ *
266
+ * ⚠ THE RULE WINS THE KEYS IT SETS AND ONLY THOSE. A rule that names a fill must not blank a
267
+ * person's own italic, and a rule that names nothing must not repaint anything: the cell's border,
268
+ * size, indent, wrap, align and valign all survive, because a rule is a colour decision about the
269
+ * DATA and never a layout decision about the sheet.
270
+ */
271
+ export const overlayRuleStyle = <T extends object>(
272
+ own: T | null | undefined,
273
+ rule: RuleStyle | null | undefined,
274
+ ): T => {
275
+ const base = { ...((own ?? {}) as object) } as Record<string, unknown>;
276
+ if (rule) {
277
+ if (rule.fill) base.fill = rule.fill;
278
+ if (rule.color) base.color = rule.color;
279
+ if (rule.bold === true) base.bold = true;
280
+ }
281
+ return base as T;
282
+ };
283
+
284
+ // ── the list editor's own arithmetic, kept pure so the gate can execute it ────────────────────
285
+
286
+ /** What a rules edit answers with: the new list, and the SENTENCE it refused with, if it did. */
287
+ export interface RulesEdit {
288
+ rules: SheetRule[];
289
+ refusal?: string;
290
+ }
291
+
292
+ /**
293
+ * β›”β›” THE CAP REFUSES, IT DOES NOT TRUNCATE, AND IT NAMES BOTH NUMBERS.
294
+ *
295
+ * Silently dropping the hundred and first rule is the worst of the three possible behaviours: the
296
+ * person sees their rule vanish and has no way to learn it was a limit rather than a bug. C2's
297
+ * cap is 100 per tab and the refusal says so in a sentence, in sentence case, with no dash.
298
+ */
299
+ export const capRefusal = (kind: "rules" | "list", have: number, cap: number): string =>
300
+ kind === "rules"
301
+ ? `This sheet already has ${have} of the ${cap} conditional formatting rules it can hold. `
302
+ + "Delete one before adding another."
303
+ : `That list has ${have} values and a cell can hold ${cap}. `
304
+ + "Shorten the list and try again.";
305
+
306
+ /** A new rule's id. Time plus a random tail, because two rules added in one millisecond are one
307
+ * gesture apart in this dialog and an id collision would make them the same row. */
308
+ export const newRuleId = (): string =>
309
+ `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
310
+
311
+ /** A rule as the dialog first offers it: the selection's range, the commonest op, one fill. */
312
+ export const blankRule = (range: string): SheetRule => ({
313
+ id: newRuleId(),
314
+ range: range || "A1",
315
+ op: "gt",
316
+ value: "",
317
+ style: { fill: "--lp-yellow-tint" },
318
+ });
319
+
320
+ /** Append a rule, or REFUSE at the cap. */
321
+ export const addRule = (rules: readonly SheetRule[], rule: SheetRule): RulesEdit => {
322
+ const current = rules ?? [];
323
+ if (current.length >= MAX_SHEET_RULES) {
324
+ return { rules: [...current], refusal: capRefusal("rules", current.length, MAX_SHEET_RULES) };
325
+ }
326
+ return { rules: [...current, rule] };
327
+ };
328
+
329
+ /** Replace one rule by id, leaving the order alone. */
330
+ export const updateRule = (
331
+ rules: readonly SheetRule[],
332
+ id: string,
333
+ patch: Partial<SheetRule>,
334
+ ): SheetRule[] => (rules ?? []).map((r) => (r.id === id ? { ...r, ...patch } : r));
335
+
336
+ /** Remove one rule by id. */
337
+ export const removeRule = (rules: readonly SheetRule[], id: string): SheetRule[] =>
338
+ (rules ?? []).filter((r) => r.id !== id);
339
+
340
+ /**
341
+ * Move one rule up or down, which is what makes the order EDITABLE rather than merely visible.
342
+ *
343
+ * ⚠ A MOVE OFF EITHER END IS A NO-OP, not a wrap. Wrapping would send the top rule to the bottom
344
+ * on a stray click and change which rule paints every cell in the sheet.
345
+ */
346
+ export const moveRule = (
347
+ rules: readonly SheetRule[],
348
+ id: string,
349
+ delta: number,
350
+ ): SheetRule[] => {
351
+ const list = [...(rules ?? [])];
352
+ const at = list.findIndex((r) => r.id === id);
353
+ if (at < 0) return list;
354
+ const to = at + delta;
355
+ if (to < 0 || to >= list.length) return list;
356
+ const [moved] = list.splice(at, 1);
357
+ list.splice(to, 0, moved);
358
+ return list;
359
+ };
360
+
361
+ /**
362
+ * Is this rule complete enough to store? A rule with an unparseable range or a missing bound is a
363
+ * rule that can never match, and saving one leaves a person staring at a list that does nothing.
364
+ */
365
+ export const ruleRefusal = (rule: SheetRule): string | null => {
366
+ if (!parseRange(rule.range)) {
367
+ return `The range "${rule.range}" is not a cell or a block of cells. Write it as B2 or B2:D40.`;
368
+ }
369
+ const arity = ruleArity(rule.op);
370
+ const first = String(rule.value ?? "").trim();
371
+ const second = String(rule.value2 ?? "").trim();
372
+ if (arity >= 1 && first === "") {
373
+ return `The rule reading "${RULE_OP_LABEL[rule.op]}" needs a value to compare against.`;
374
+ }
375
+ if (arity === 2 && second === "") {
376
+ return "A rule reading \"Between\" needs both bounds.";
377
+ }
378
+ if (!rule.style || (!rule.style.fill && !rule.style.color && rule.style.bold !== true)) {
379
+ return "Choose a fill, a text colour or bold, or the rule would paint nothing.";
380
+ }
381
+ return null;
382
+ };
383
+
384
+ /** The first refusal in a list, or `null` when every rule is complete. */
385
+ export const rulesRefusal = (rules: readonly SheetRule[]): string | null => {
386
+ for (const rule of rules ?? []) {
387
+ const why = ruleRefusal(rule);
388
+ if (why) return why;
389
+ }
390
+ return null;
391
+ };
392
+
393
+ /** How the dialog reads one rule back, so a person can check the list without opening each row. */
394
+ export const ruleSummary = (rule: SheetRule): string => {
395
+ const label = RULE_OP_LABEL[rule.op] ?? rule.op;
396
+ const arity = ruleArity(rule.op);
397
+ if (arity === 0) return `${rule.range}, ${label.toLowerCase()}`;
398
+ if (arity === 2) return `${rule.range}, between ${rule.value} and ${rule.value2}`;
399
+ return `${rule.range}, ${label.toLowerCase()} ${rule.value}`;
400
+ };
web/src/sheet/sheetApi.ts CHANGED
@@ -7,7 +7,7 @@
7
  // declared now so the later ticket changes the SERVER and not this file's shape.
8
  import { API_V1, CREDENTIALS } from "../apiContract";
9
  import { emptyIndex } from "./types";
10
- import type { Workbook, WorkbookIndex, WorkbookRow } from "./types";
11
 
12
  export type Result<T> =
13
  | { ok: true; value: T }
@@ -72,19 +72,52 @@ export const listWorkbooks = (): Promise<Result<WorkbookRow[]>> =>
72
  // `/sheets/{workbook_id}`. FastAPI matches in declaration order, so the literal has to come
73
  // first or `index` arrives as a workbook id.
74
 
75
- const asIndex = (body: unknown): WorkbookIndex => {
76
- const raw = (body as { index?: Partial<WorkbookIndex> } | null)?.index ?? null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  if (!raw) return emptyIndex();
78
- return {
79
  workbooks: Array.isArray(raw.workbooks) ? raw.workbooks : [],
80
  folders: Array.isArray(raw.folders) ? raw.folders : [],
81
  itemFolders: raw.itemFolders && typeof raw.itemFolders === "object" ? raw.itemFolders : {},
82
  starred: Array.isArray(raw.starred) ? raw.starred : [],
83
  repairs: Array.isArray(raw.repairs) ? raw.repairs : [],
84
  };
 
 
 
 
 
 
85
  };
86
 
87
- export const readIndex = (): Promise<Result<WorkbookIndex>> =>
88
  call("/sheets/index", { method: "GET" }, asIndex);
89
 
90
  /**
@@ -96,8 +129,8 @@ export const readIndex = (): Promise<Result<WorkbookIndex>> =>
96
  */
97
  export const writeIndex = (
98
  next: { folders: WorkbookIndex["folders"]; itemFolders: WorkbookIndex["itemFolders"];
99
- starred: WorkbookIndex["starred"] },
100
- ): Promise<Result<WorkbookIndex>> =>
101
  call("/sheets/index", sends("PUT", next), asIndex);
102
 
103
  export const createWorkbook = (name = ""): Promise<Result<Workbook>> =>
@@ -123,10 +156,106 @@ export const deleteWorkbook = (id: string): Promise<Result<boolean>> =>
123
  (body) => Boolean((body as { deleted?: boolean } | null)?.deleted),
124
  );
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  // ── the doors W49-T04 fills in ───────────────────────────────────────────────────────────────
127
 
128
- export const refreshWorkbook = (id: string): Promise<Result<Workbook>> =>
129
- call(`/sheets/${encodeURIComponent(id)}/refresh`, { method: "POST" }, asWorkbook);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  export const previewCell = (
132
  id: string,
@@ -153,3 +282,110 @@ export const drillCell = (id: string, addr: string): Promise<Result<CellDrill>>
153
  { method: "GET" },
154
  (body) => body as CellDrill,
155
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  // declared now so the later ticket changes the SERVER and not this file's shape.
8
  import { API_V1, CREDENTIALS } from "../apiContract";
9
  import { emptyIndex } from "./types";
10
+ import type { Cell, SheetTab, Workbook, WorkbookIndex, WorkbookRow } from "./types";
11
 
12
  export type Result<T> =
13
  | { ok: true; value: T }
 
72
  // `/sheets/{workbook_id}`. FastAPI matches in declaration order, so the literal has to come
73
  // first or `index` arrives as a workbook id.
74
 
75
+ /**
76
+ * ⭐⭐ W51-T10 β€” THE INDEX AS THIS CLIENT READS IT, WIDENED HERE AND NOT IN `types.ts`.
77
+ *
78
+ * `sheet/types.ts` is another lane's file this wave, and an object literal typed as its
79
+ * `WorkbookIndex` REJECTS an excess property, so the two new strata could not simply be attached
80
+ * to what `asIndex` builds. Extending the type in this file is the change that needs no other
81
+ * lane's permission, and it collapses to a rename the day `types.ts` grows the members itself.
82
+ *
83
+ * ⚠ BOTH MEMBERS ARE OPTIONAL BECAUSE THE SERVER DOES NOT SEND EITHER ONE YET. `sharedWithMe`
84
+ * arrives with contract C5 (W51-T25) and `rev` with the same ticket's optimistic-concurrency
85
+ * stratum; until then the parser simply does not find them and every reader must work without
86
+ * them. An `emptyIndex()` from `types.ts` stays assignable for exactly that reason.
87
+ */
88
+ export interface SheetIndex extends WorkbookIndex {
89
+ /** C5: the workbooks other people have shared with this account. */
90
+ sharedWithMe?: WorkbookRow[];
91
+ /**
92
+ * The index's own revision, once W51-T25 stamps one.
93
+ *
94
+ * β›” THE INDEX PUT IS WHOLESALE AND CARRIES NO `rev` TODAY (D-639), so the last writer wins and
95
+ * two people filing at once silently overwrite each other. `writeIndex` FORWARDS this when it is
96
+ * present and omits the key entirely when it is not, so the guard starts working the moment the
97
+ * server starts sending one and nothing 400s in the meantime on an unexpected field.
98
+ */
99
+ rev?: number;
100
+ }
101
+
102
+ const asIndex = (body: unknown): SheetIndex => {
103
+ const raw = (body as { index?: Partial<SheetIndex> } | null)?.index ?? null;
104
  if (!raw) return emptyIndex();
105
+ const next: SheetIndex = {
106
  workbooks: Array.isArray(raw.workbooks) ? raw.workbooks : [],
107
  folders: Array.isArray(raw.folders) ? raw.folders : [],
108
  itemFolders: raw.itemFolders && typeof raw.itemFolders === "object" ? raw.itemFolders : {},
109
  starred: Array.isArray(raw.starred) ? raw.starred : [],
110
  repairs: Array.isArray(raw.repairs) ? raw.repairs : [],
111
  };
112
+ // ⚠ ADDED ONLY WHEN THE SERVER ACTUALLY SENT ONE. An always-present empty list would be a
113
+ // second way to say "absent", and the rail's "Shared to me" section would then have to test for
114
+ // both; a `rev: undefined` key would be forwarded on the next PUT as a literal null.
115
+ if (Array.isArray(raw.sharedWithMe)) next.sharedWithMe = raw.sharedWithMe as WorkbookRow[];
116
+ if (typeof raw.rev === "number") next.rev = raw.rev;
117
+ return next;
118
  };
119
 
120
+ export const readIndex = (): Promise<Result<SheetIndex>> =>
121
  call("/sheets/index", { method: "GET" }, asIndex);
122
 
123
  /**
 
129
  */
130
  export const writeIndex = (
131
  next: { folders: WorkbookIndex["folders"]; itemFolders: WorkbookIndex["itemFolders"];
132
+ starred: WorkbookIndex["starred"]; rev?: number },
133
+ ): Promise<Result<SheetIndex>> =>
134
  call("/sheets/index", sends("PUT", next), asIndex);
135
 
136
  export const createWorkbook = (name = ""): Promise<Result<Workbook>> =>
 
156
  (body) => Boolean((body as { deleted?: boolean } | null)?.deleted),
157
  );
158
 
159
+ // ── contract C3 (W51-T11, ruling R4) β€” SAVE A RANGE, OPEN ONE TAB AT A TIME ──────────────────
160
+ //
161
+ // ⭐⭐ R4, verbatim: *"the client saves a cell-range PATCH per commit with `rev`, opens one tab at
162
+ // a time"*. The three doors below are the whole of the client half. C3 gives them as:
163
+ //
164
+ // GET /sheets/{id}?tabs=meta the workbook WITHOUT cells
165
+ // GET /sheets/{id}/tabs/{tab} one tab, cells and all
166
+ // PATCH /sheets/{id}/tabs/{tab}/cells {cells, rev} -> {rev, refused[]}
167
+ //
168
+ // β›”β›” NONE OF THEM EXIST ON THIS BRANCH. Lane D serves them; they are declared here so the day
169
+ // they land is a server change and not a second edit to every caller. Until then `?tabs=meta` is
170
+ // an unread query parameter on today's `GET /sheets/{workbook_id}` (which declares none, so
171
+ // FastAPI ignores it and answers with the FULL workbook), the tab read answers 405, and the cell
172
+ // PATCH answers 405 as well because it sits under the `/sheets/{workbook_id}` path parameter.
173
+ // That 405 is why no caller may test for 404: [[an-unbuilt-route-under-a-path-param-answers-405]].
174
+
175
+ /** C3: what one address in a cell PATCH was refused for, in the server's own sentence. */
176
+ export interface CellRefused {
177
+ addr: string;
178
+ code: string;
179
+ sentence: string;
180
+ }
181
+
182
+ /** C3: what `PATCH /sheets/{id}/tabs/{tab}/cells` answers with. */
183
+ export interface TabCellsSaved {
184
+ /** The revision the workbook is now at, to send with the next PATCH. */
185
+ rev: number;
186
+ /** The addresses that did not land, each with its own reason. Empty when everything saved. */
187
+ refused: CellRefused[];
188
+ }
189
+
190
+ const asTabCellsSaved = (body: unknown): TabCellsSaved => {
191
+ const raw = (body as { rev?: unknown; refused?: unknown } | null) ?? {};
192
+ return {
193
+ rev: typeof raw.rev === "number" ? raw.rev : 0,
194
+ refused: Array.isArray(raw.refused) ? (raw.refused as CellRefused[]) : [],
195
+ };
196
+ };
197
+
198
+ /**
199
+ * Send ONLY the addresses that changed, with the revision they were changed against.
200
+ *
201
+ * ⚠ A `null` VALUE IS A DELETE, and that is why the map is `Cell | null` rather than `Cell`.
202
+ * Leaving a cleared address out of the body would mean "nothing changed here", which is the
203
+ * opposite of what a range delete is saying.
204
+ */
205
+ export const patchTabCells = (
206
+ id: string,
207
+ tab: string,
208
+ patch: { cells: Record<string, Cell | null>; rev?: number },
209
+ ): Promise<Result<TabCellsSaved>> =>
210
+ call(
211
+ `/sheets/${encodeURIComponent(id)}/tabs/${encodeURIComponent(tab)}/cells`,
212
+ sends("PATCH", patch),
213
+ asTabCellsSaved,
214
+ );
215
+
216
+ /** The workbook's identity, revision and tab list, without the cells. */
217
+ export const readTabMeta = (id: string): Promise<Result<Workbook>> =>
218
+ call(`/sheets/${encodeURIComponent(id)}?tabs=meta`, { method: "GET" }, asWorkbook);
219
+
220
+ /**
221
+ * ⚠ IT CAN ANSWER `null`, AND THE CALLER MUST SAY SO. A body this parser does not recognise is
222
+ * not an empty tab: painting one as empty is indistinguishable from the tab's contents being
223
+ * deleted, so the absence is carried in the type rather than smoothed into `{cells: {}}`.
224
+ */
225
+ const asTab = (body: unknown): SheetTab | null => {
226
+ const raw = body as { tab?: unknown; sheet?: unknown } | null;
227
+ const found = (raw?.tab ?? raw?.sheet ?? null) as SheetTab | null;
228
+ return found && typeof found.id === "string" ? found : null;
229
+ };
230
+
231
+ export const readTab = (id: string, tab: string): Promise<Result<SheetTab | null>> =>
232
+ call(
233
+ `/sheets/${encodeURIComponent(id)}/tabs/${encodeURIComponent(tab)}`,
234
+ { method: "GET" },
235
+ asTab,
236
+ );
237
+
238
  // ── the doors W49-T04 fills in ───────────────────────────────────────────────────────────────
239
 
240
+ /**
241
+ * ⭐ W51-T11 / R4: *"recalc runs only on Refresh or a formula commit and its time is shown."*
242
+ *
243
+ * β›” `recalcMs` IS `null` WHEN THE SERVER DID NOT SAY, NEVER 0. A zero would render as
244
+ * "Recalculated in 0.0 s", which is a MEASUREMENT nobody took, on a screen. Today's
245
+ * `POST /sheets/{id}/refresh` sends no such field, so the line is simply not shown.
246
+ */
247
+ export interface RefreshResult {
248
+ workbook: Workbook;
249
+ recalcMs: number | null;
250
+ }
251
+
252
+ export const refreshWorkbook = (id: string): Promise<Result<RefreshResult>> =>
253
+ call(`/sheets/${encodeURIComponent(id)}/refresh`, { method: "POST" }, (body) => ({
254
+ workbook: asWorkbook(body),
255
+ recalcMs: typeof (body as { recalc_ms?: unknown } | null)?.recalc_ms === "number"
256
+ ? (body as { recalc_ms: number }).recalc_ms
257
+ : null,
258
+ }));
259
 
260
  export const previewCell = (
261
  id: string,
 
282
  { method: "GET" },
283
  (body) => body as CellDrill,
284
  );
285
+
286
+ // ── contract C4 (W51-T13, ruling R1) β€” IMPORT AN .xlsx, SERVER SIDE ─────────────────────────
287
+ //
288
+ // ⭐⭐ R1, verbatim: *"a server-side .xlsx importer (openpyxl, MIT) lands the treasury workbook as
289
+ // a Loopable workbook"*. The word that shapes this file's half is SERVER SIDE. Nothing below
290
+ // reads the file: no `FileReader`, no `arrayBuffer()`, no parse, no inspection beyond the byte
291
+ // count and the name. A client that peeked would be a SECOND reader of the same bytes, disagreeing
292
+ // with openpyxl about merged cells, shared strings and cached values the first time a real
293
+ // workbook arrived, and the disagreement would surface as a number on a screen rather than an
294
+ // error.
295
+ //
296
+ // β›”β›” NEITHER DOOR EXISTS ON THIS BRANCH. `routes_sheet.py` declares ten routes and no import;
297
+ // lane D lands these two at the combine. Until then the POST answers 404 or 405 and the dialog
298
+ // says import is not available yet. They are declared HERE, now, so the day the server lands is a
299
+ // server change and not a second edit to every caller.
300
+ //
301
+ // β›” AND THE MULTIPART BODY DOES NOT GO THROUGH `sends()`. That helper stamps
302
+ // `Content-Type: application/json`, which overwrites the multipart boundary the browser generates
303
+ // and leaves the server with a body it cannot split into parts. `call`'s default init carries no
304
+ // headers at all, so passing the `FormData` bare is what lets the browser stamp its own.
305
+
306
+ /** The whole of the cap, in ONE place, so the guard and the sentence cannot drift apart. */
307
+ export const IMPORT_MAX_MB = 25;
308
+ export const BYTES_PER_MB = 1024 * 1024;
309
+ export const IMPORT_MAX_BYTES = IMPORT_MAX_MB * BYTES_PER_MB;
310
+
311
+ /** C4's six job states. `done` and `refused` are the only terminal ones the SERVER can name. */
312
+ export type ImportState = "reading" | "cells" | "formats" | "recalc" | "done" | "refused";
313
+
314
+ /** One computed cell whose value did not come out equal to the file's cached one. */
315
+ export interface ImportMismatch {
316
+ addr: string;
317
+ tab: string;
318
+ kind: string;
319
+ }
320
+
321
+ /**
322
+ * C4's report. `matched / (matched + mismatched)` is R1's differential: *"done when every computed
323
+ * cell matches the file's cached value"*, said as a number rather than as a claim.
324
+ */
325
+ export interface ImportReport {
326
+ cells: number;
327
+ formulas: number;
328
+ matched: number;
329
+ mismatched: ImportMismatch[];
330
+ unsupported: string[];
331
+ }
332
+
333
+ export interface ImportJob {
334
+ state: ImportState;
335
+ /** 0..1. Clamped at the reader, because a bar wider than its track paints outside the dialog. */
336
+ progress: number;
337
+ workbook_id?: string;
338
+ report?: ImportReport;
339
+ /**
340
+ * The server's own refusal sentence, shown VERBATIM. A rephrasing here would be this client
341
+ * inventing a reason for something only the server watched happen.
342
+ */
343
+ sentence?: string;
344
+ }
345
+
346
+ const IMPORT_STATES: readonly ImportState[] = [
347
+ "reading", "cells", "formats", "recalc", "done", "refused",
348
+ ];
349
+
350
+ const asImportJob = (body: unknown): ImportJob => {
351
+ const raw = (body as Partial<ImportJob> | null) ?? {};
352
+ const state = IMPORT_STATES.includes(raw.state as ImportState)
353
+ ? (raw.state as ImportState)
354
+ : "reading";
355
+ const progress = typeof raw.progress === "number" && Number.isFinite(raw.progress)
356
+ ? Math.min(1, Math.max(0, raw.progress))
357
+ : 0;
358
+ const job: ImportJob = { state, progress };
359
+ if (typeof raw.workbook_id === "string" && raw.workbook_id) job.workbook_id = raw.workbook_id;
360
+ if (typeof raw.sentence === "string" && raw.sentence) job.sentence = raw.sentence;
361
+ const report = raw.report;
362
+ if (report && typeof report === "object") {
363
+ job.report = {
364
+ cells: typeof report.cells === "number" ? report.cells : 0,
365
+ formulas: typeof report.formulas === "number" ? report.formulas : 0,
366
+ matched: typeof report.matched === "number" ? report.matched : 0,
367
+ mismatched: Array.isArray(report.mismatched) ? report.mismatched : [],
368
+ unsupported: Array.isArray(report.unsupported)
369
+ ? report.unsupported.filter((u): u is string => typeof u === "string")
370
+ : [],
371
+ };
372
+ }
373
+ return job;
374
+ };
375
+
376
+ /**
377
+ * Hand ONE workbook file to the server and get the job that is reading it.
378
+ *
379
+ * β›” THE FILE IS NEVER OPENED HERE. `file.size` and `file.name` are the only two things this
380
+ * client is allowed to know about it, and both are metadata the browser already had.
381
+ */
382
+ export const importWorkbook = (file: File): Promise<Result<{ job: string }>> => {
383
+ const form = new FormData();
384
+ form.append("file", file, file.name);
385
+ return call("/sheets/import", { method: "POST", body: form }, (body) => ({
386
+ job: String((body as { job?: unknown } | null)?.job ?? ""),
387
+ }));
388
+ };
389
+
390
+ export const readImportJob = (job: string): Promise<Result<ImportJob>> =>
391
+ call(`/sheets/import/${encodeURIComponent(job)}`, { method: "GET" }, asImportJob);