fsanyoto commited on
Commit
a878ebb
Β·
verified Β·
1 Parent(s): 665e5ea

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "6fffe9d",
3
  "releases": [
4
  {
5
  "version": "v24",
 
1
  {
2
+ "current": "75ff9d9",
3
  "releases": [
4
  {
5
  "version": "v24",
VERSION CHANGED
@@ -1 +1 @@
1
- 6fffe9d
 
1
+ 75ff9d9
api/routes_changes.py CHANGED
@@ -27,22 +27,34 @@ enforcing that silence. A push channel could therefore only ever carry 1 of the
27
  counter on the store sees the automation and the connector sync for free, and the loop-prevention
28
  law is untouched.
29
 
30
- WHAT WALLS THIS, and why it is not `may_open`:
31
 
32
  * The TENANT is the wall, and it is structural. Every bucket name is namespaced through the
33
  session's OWN runtime (`TenantRuntime.store_key`), so a scope naming another tenant's table
34
  resolves to a bucket this tenant does not have and reads 0. There is no cross-tenant answer
35
- to give.
36
- * A per-table `may_open` check would cost the very deep copy this route exists to avoid β€”
37
- `user_tables.get()` reads the whole `user_tables` bucket to answer it.
38
- * ⭐ And it would protect nothing, because `user_tables.STORE_KEY` is ONE bucket holding EVERY
39
- `ut_*` table in the tenant: the rows token for `ut_a` and `ut_b` is literally the same
40
- number. There is no per-table fact here to withhold. (Which also means a write to any one of
41
- them invites every open tab to re-read its own table β€” over-signalling, i.e. the safe
42
- direction: the cost is one extra fetch, never a missed change.)
43
-
44
- So: a valid session, a scope sanitised to a bucket-safe shape, and nothing else.
 
 
 
 
 
 
 
 
 
 
 
45
  """
 
46
  from fastapi import APIRouter, Depends
47
 
48
  import core.shared_overlay as shared_overlay
@@ -136,12 +148,67 @@ def buckets_for(scope):
136
  return names
137
 
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  @router.get("/changes")
140
  def changes(scope: str = "", session: Session = Depends(require_session)):
141
  """One tiny read per tab per interval. The response is small, uncacheable and boring."""
142
  names = buckets_for(scope)
143
  if names is None:
144
  raise err(400, "bad_scope", "name the table you are watching, e.g. ?scope=customer")
 
 
 
 
 
 
145
  if not names:
146
  # β›” A well-formed scope this map does not know is a 404, NOT an empty `tokens` object.
147
  # An empty map is indistinguishable from "nothing here ever changes", so a topic added
 
27
  counter on the store sees the automation and the connector sync for free, and the loop-prevention
28
  law is untouched.
29
 
30
+ WHAT WALLS THIS:
31
 
32
  * The TENANT is the wall, and it is structural. Every bucket name is namespaced through the
33
  session's OWN runtime (`TenantRuntime.store_key`), so a scope naming another tenant's table
34
  resolves to a bucket this tenant does not have and reads 0. There is no cross-tenant answer
35
+ to give. **Measured, wave-29 QA:** a real `nurilab-admin` session against a `royal-imports`
36
+ table gets no data here.
37
+ * β›” …AND, SINCE W29-T82, A PER-TABLE WALL INSIDE THE TENANT. The paragraph that used to sit
38
+ here argued this route needed none, on the ground that `user_tables.STORE_KEY` is ONE bucket
39
+ for every `ut_*` table so "there is no per-table fact to withhold". **Half of that is false
40
+ and the QA pass measured it.** The `rows` token is indeed shared β€” but `overlay` and `shared`
41
+ are PER-TABLE buckets (`<scope>_table_workspace`), so a non-zero token against `:0` told a
42
+ session whether a table it may not open EXISTS and is being edited. That is an
43
+ existence/activity oracle, and every sibling door (`GET rows`, `POST rows`, `PATCH rows/{pid}`,
44
+ `PATCH fields/{k}`, `POST rows/import`) answers **404 `unknown_table`** rather than leak it.
45
+ One door out of six holding a different line is the door somebody probes.
46
+ * ⚠ AND THE COST ARGUMENT WAS RIGHT, so the wall is CACHED rather than paid per poll.
47
+ `user_tables.may_open` reads the whole `user_tables` bucket through `store.get`, which is a
48
+ JSON round-trip deep copy under the store lock β€” the exact 1.4 s this route exists not to
49
+ spend, and it would be spent by every tab on every interval. `_may_watch` below memoises the
50
+ verdict per (tenant, user, scope) for `_WALL_TTL` seconds. The common case costs nothing: a
51
+ tab only polls a scope it already has OPEN, which already passed the same wall on the
52
+ workspace fetch. A prober pays one read per scope per TTL and gets 404s.
53
+
54
+ So: a valid session, a scope sanitised to a bucket-safe shape, and β€” for a `ut_*` table β€” a
55
+ cached verdict that this session may open it.
56
  """
57
+ import time
58
  from fastapi import APIRouter, Depends
59
 
60
  import core.shared_overlay as shared_overlay
 
148
  return names
149
 
150
 
151
+ #: How long a may-open verdict is trusted. Short enough that a REVOKED grant stops answering
152
+ #: within a poll interval or two; long enough that a tab polling every few seconds pays the
153
+ #: bucket read at most once per TTL. ⚠ A REVOCATION is therefore visible here up to `_WALL_TTL`
154
+ #: late β€” stated rather than glossed, because the alternative (no cache) is the 1.4 s-per-poll
155
+ #: cost this route was built to avoid, and the leak this bounds is an existence oracle, not data.
156
+ _WALL_TTL = 30.0
157
+ #: (tenant, user, scope) -> (expires_at, verdict). Bounded: a prober walking thousands of scopes
158
+ #: must not be able to grow this without limit, so it is cleared wholesale when it gets large β€”
159
+ #: cheaper than an LRU and the only cost of being wrong is one extra bucket read.
160
+ _WALL_CACHE = {}
161
+ _WALL_MAX = 512
162
+
163
+
164
+ def _may_watch(session, scope):
165
+ """May this session watch this scope? Cached, because the honest check is expensive.
166
+
167
+ β›” FAIL-CLOSED THROUGH THE ONE RESOLVER. `user_tables.may_open` is where "who may open this
168
+ database" is decided (creator Β· admin Β· an explicit share grant); asking a second way here is
169
+ how two doors end up with two answers ([[one-evaluator-per-question]]). Non-`ut_*` scopes
170
+ (`customer`, `product`) are module-gated surfaces whose own doors decide access and whose
171
+ buckets are tenant-wide, so there is no per-table fact to withhold for them.
172
+ """
173
+ if not scope.startswith(user_tables.KEY_PREFIX):
174
+ return True
175
+ # ⚠ THE NAMESPACE STRING, not `runtime.tenant` β€” that attribute is a `Tenant` OBJECT and is
176
+ # unhashable, so keying on it raised a TypeError INSIDE the handler, which `TestClient`
177
+ # re-raises: the gate CRASHED rather than reddening ([[gate-must-go-red-not-crash]], caught
178
+ # by the very leg added for this ticket). `store_namespace` is the string that already makes
179
+ # one tenant's buckets distinct from another's, so it is the right axis anyway.
180
+ key = (str(getattr(session.runtime, "store_namespace", "")), session.uname, scope)
181
+ now = time.monotonic()
182
+ hit = _WALL_CACHE.get(key)
183
+ if hit and hit[0] > now:
184
+ return hit[1]
185
+ verdict = bool(user_tables.may_open(scope, session.uname, session.admin, st=session.runtime))
186
+ # β›” ONLY A `True` IS CACHED, and the asymmetry is deliberate. `user_tables.all_tables()`
187
+ # SWALLOWS a store error and answers `{}`, which makes `may_open` False β€” so caching a
188
+ # negative would turn one transient store hiccup into "no database <name> here" for the whole
189
+ # TTL, on a poller, for a table the user has open. A false negative that expires in 30 s is a
190
+ # worse failure than one extra bucket read: the read costs latency, the cache costs trust
191
+ # ([[lost-write-looks-like-failed-read]] β€” a refusal derived from a swallowed error reads to
192
+ # the user as their data being gone).
193
+ if verdict:
194
+ if len(_WALL_CACHE) >= _WALL_MAX:
195
+ _WALL_CACHE.clear()
196
+ _WALL_CACHE[key] = (now + _WALL_TTL, True)
197
+ return verdict
198
+
199
+
200
  @router.get("/changes")
201
  def changes(scope: str = "", session: Session = Depends(require_session)):
202
  """One tiny read per tab per interval. The response is small, uncacheable and boring."""
203
  names = buckets_for(scope)
204
  if names is None:
205
  raise err(400, "bad_scope", "name the table you are watching, e.g. ?scope=customer")
206
+ # β›” W29-T82 β€” THE SAME REFUSAL EVERY SIBLING DOOR GIVES, word for word. A session that may
207
+ # not open this table must not be able to tell whether it exists, and "404 unknown_table" is
208
+ # the sentence the other five row doors answer with. A different code here would itself be
209
+ # the tell.
210
+ if names and not _may_watch(session, _clean_scope(scope)):
211
+ raise err(404, "unknown_table", f"no database {_clean_scope(scope)!r} here")
212
  if not names:
213
  # β›” A well-formed scope this map does not know is a 404, NOT an empty `tokens` object.
214
  # An empty map is indistinguishable from "nothing here ever changes", so a topic added
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -37,6 +37,12 @@ import { formatDisplay } from "./cells";
37
  import { actionHref } from "./display";
38
  import { optionTint } from "./choiceColors";
39
  import { ModeIcon } from "./icons";
 
 
 
 
 
 
40
 
41
  export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
42
 
 
37
  import { actionHref } from "./display";
38
  import { optionTint } from "./choiceColors";
39
  import { ModeIcon } from "./icons";
40
+ // ⭐ W29-T73 β€” the line its three siblings all have, and the one this file shipped without.
41
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
42
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β€”
43
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
44
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
45
+ import "./SwipeView.css";
46
 
47
  export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
48
 
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -1661,11 +1661,11 @@ export default function ViewSidebar({
1661
  padding: "6px 10px 2px",
1662
  fontSize: "10px",
1663
  fontWeight: 600,
1664
- letterSpacing: "0.06em",
1665
  color: "var(--lp-muted)",
1666
  }}
1667
  >
1668
- DATA
1669
  </div>
1670
  {onExport && (
1671
  <button
@@ -1697,7 +1697,7 @@ export default function ViewSidebar({
1697
  setMenu(null);
1698
  }}
1699
  >
1700
- <MenuLabel icon="cohortAdd" text="Import…" />
1701
  </button>
1702
  )}
1703
  <div className="cg-menu-sep" role="separator" aria-hidden />
@@ -1709,11 +1709,11 @@ export default function ViewSidebar({
1709
  padding: "2px 10px 2px",
1710
  fontSize: "10px",
1711
  fontWeight: 600,
1712
- letterSpacing: "0.06em",
1713
  color: "var(--lp-muted)",
1714
  }}
1715
  >
1716
- VIEW
1717
  </div>
1718
  </>
1719
  )}
 
1661
  padding: "6px 10px 2px",
1662
  fontSize: "10px",
1663
  fontWeight: 600,
1664
+ letterSpacing: "0.02em",
1665
  color: "var(--lp-muted)",
1666
  }}
1667
  >
1668
+ Data
1669
  </div>
1670
  {onExport && (
1671
  <button
 
1697
  setMenu(null);
1698
  }}
1699
  >
1700
+ <MenuLabel icon="upload" text="Import…" />
1701
  </button>
1702
  )}
1703
  <div className="cg-menu-sep" role="separator" aria-hidden />
 
1709
  padding: "2px 10px 2px",
1710
  fontSize: "10px",
1711
  fontWeight: 600,
1712
+ letterSpacing: "0.02em",
1713
  color: "var(--lp-muted)",
1714
  }}
1715
  >
1716
+ View
1717
  </div>
1718
  </>
1719
  )}
web/src/customer-grid/aggregations.ts CHANGED
@@ -1,109 +1,119 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / aggregations.ts
3
- // COLUMN SUMMARIES β€” the per-group subtotal AND the table's own totals row.
4
- // `computeAggs` folds every field carrying an `agg` over a bucket of rows and
5
- // returns fieldKey -> formatted display string. Non-agg fields are simply
6
- // absent from the map, so the footer renderer draws them blank.
7
- //
8
- // Called ONCE per group inside the useVisibleRows memo (never per cell/frame);
9
- // the resulting object is shared by that group's header and footer, and once
10
- // more for the ungrouped totals row.
11
- // ---------------------------------------------------------------------------
12
-
13
- import { isNumericFieldType } from "./types";
14
- import type { AggName, Field, Row } from "./types";
15
-
16
- /**
17
- * ⭐⭐ WAVE-29 CONTRACT C7 β€” **THE CLIENT MIRROR of `platform/aios_grid.FIELD_AGGS`**, published
18
- * by session C and held in step by a parity gate that reads both files. The ORDER is the
19
- * picker's order.
20
- *
21
- * β›” THREE VOCABULARIES EXIST AND THEY ARE NOT ONE LIST β€” merging them is the trap on this
22
- * contract:
23
- * Β· `FIELD_AGGS` (here + aios_grid) a FIELD's `agg`: the column summary. This.
24
- * Β· `CHART_AGGS` (aios_grid, `avg`) STORED chart values with live data. Untouchable:
25
- * an unknown agg falls back to `sum` and drops a
26
- * calendar metric card, with nothing red.
27
- * Β· `ROLLUP_FNS` (user_tables, 16 names) rollup FOLDS. Overlaps; is not the same list.
28
- *
29
- * ⚠ `average`, not `avg`: `ROLLUP_FNS` already spells it that way and 47 rollups run on it in
30
- * production, so a column summary and a rollup fold name the same operation the same way.
31
- * ⚠ `median` is in NEITHER of the other two β€” it is net-new on both sides of this contract.
32
- */
33
- export const FIELD_AGGS: readonly AggName[] = [
34
- "sum", "average", "median", "min", "max", "count",
35
- ];
36
-
37
- /** How each one reads in the picker. Sentence case, because it is a menu row, not a header. */
38
- export const AGG_LABELS: Record<AggName, string> = {
39
- sum: "Sum",
40
- average: "Average",
41
- median: "Median",
42
- min: "Min",
43
- max: "Max",
44
- count: "Count",
45
- };
46
-
47
- /**
48
- * What THIS column may be summarised by (C7's semantics, not a preference):
49
- * `sum Β· average Β· median Β· min Β· max` are numeric-only; `count` counts ROWS and so applies to
50
- * every type. Offering Sum on a text column would render a number nobody can reconcile.
51
- */
52
- export function aggOptions(field: Field): readonly AggName[] {
53
- return isNumericFieldType(field.type)
54
- ? FIELD_AGGS
55
- : FIELD_AGGS.filter((a) => a === "count");
56
- }
57
-
58
- /** The numeric value of a cell, or `undefined` β€” blank and unparseable are NOT zero. */
59
- function numOf(v: unknown): number | undefined {
60
- if (v === null || v === undefined || v === "") return undefined;
61
- const n = typeof v === "number" ? v : Number(String(v).replace(/[$,\s]/g, ""));
62
- return Number.isFinite(n) ? n : undefined;
63
- }
64
-
65
- function median(sorted: number[]): number {
66
- const mid = sorted.length >> 1;
67
- return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
68
- }
69
-
70
- /**
71
- * Fold every field carrying an `agg` over `rows`, formatted to match its column:
72
- * currency -> "$" + toLocaleString | everything else -> toLocaleString
73
- * Values are rounded to 2 decimals first to kill floating-point drift (1234.5600000001).
74
- *
75
- * β›” **BLANK, NEVER ZERO** (C7, and the codebase's standing law): a numeric fold over a set
76
- * holding no numeric value at all returns nothing and the cell stays empty β€” `0` is a
77
- * measurement and this is an admission that there was nothing to measure. Only `count` returns
78
- * `0`, because "no rows" genuinely is a count. This is also what `_rollup_fold` already does.
79
- *
80
- * ⚠ `count` counts ROWS IN SCOPE, not non-blank cells. `ROLLUP_FNS` splits that hair three ways
81
- * (`count`/`counta`/`countall`); a column summary does not, and must not grow a second spelling.
82
- */
83
- export function computeAggs(rows: Row[], fields: Field[]): Record<string, string> {
84
- const out: Record<string, string> = {};
85
- for (const f of fields) {
86
- const agg = f.agg as AggName | undefined;
87
- if (!agg || !FIELD_AGGS.includes(agg)) continue;
88
- if (agg === "count") {
89
- out[f.key] = rows.length.toLocaleString();
90
- continue;
91
- }
92
- if (!isNumericFieldType(f.type)) continue;
93
- const nums: number[] = [];
94
- for (const r of rows) {
95
- const n = numOf(r[f.key]);
96
- if (n !== undefined) nums.push(n);
97
- }
98
- if (!nums.length) continue; // blank, never zero
99
- let value: number;
100
- if (agg === "sum") value = nums.reduce((a, b) => a + b, 0);
101
- else if (agg === "average") value = nums.reduce((a, b) => a + b, 0) / nums.length;
102
- else if (agg === "median") value = median([...nums].sort((a, b) => a - b));
103
- else if (agg === "min") value = Math.min(...nums);
104
- else value = Math.max(...nums);
105
- const clean = Math.round(value * 100) / 100; // drop float artifacts
106
- out[f.key] = f.type === "currency" ? "$" + clean.toLocaleString() : clean.toLocaleString();
107
- }
108
- return out;
109
- }
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / aggregations.ts
3
+ // COLUMN SUMMARIES β€” the per-group subtotal AND the table's own totals row.
4
+ // `computeAggs` folds every field carrying an `agg` over a bucket of rows and
5
+ // returns fieldKey -> formatted display string. Non-agg fields are simply
6
+ // absent from the map, so the footer renderer draws them blank.
7
+ //
8
+ // Called ONCE per group inside the useVisibleRows memo (never per cell/frame);
9
+ // the resulting object is shared by that group's header and footer, and once
10
+ // more for the ungrouped totals row.
11
+ // ---------------------------------------------------------------------------
12
+
13
+ import { isNumericFieldType } from "./types";
14
+ // β›” ONE numeric reading of a stored cell, shared with the CANVAS renderer β€” see its
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 { AggName, Field, Row } from "./types";
18
+ // ⭐⭐ W29-T74 β€” IMPORTED, NOT RE-DECLARED, which is what `iconShapes.ts` always claimed.
19
+ import { FIELD_AGGS, FIELD_AGG_LABELS } from "./iconShapes";
20
+
21
+ /**
22
+ * ⭐⭐ WAVE-29 CONTRACT C7 β€” **THE CLIENT MIRROR of `platform/aios_grid.FIELD_AGGS`**, published
23
+ * by session C and held in step by a parity gate. The ORDER is the picker's order.
24
+ *
25
+ * β›” THE MIRROR IS NOW AN IMPORT, AND UNTIL W29-T74 IT WAS A LIE. Both `iconShapes.ts:620` and
26
+ * `aios_grid.py:1069` said *"ONE CLIENT LIST, IMPORTED β€” never re-declared"* while this file
27
+ * re-declared it three lines later. Every runtime consumer (`ColumnMenu`, `CustomerGrid`,
28
+ * `useVisibleRows`) imports `./aggregations`, so `iconShapes`' copy had ZERO importers and the
29
+ * parity gate was diffing a literal no production file read, while the live list drifted free
30
+ * ([[gate-answers-the-wrong-question]]). Re-exported under this module's own name so no call
31
+ * site had to change β€” the fix is the import, not a rename cascade.
32
+ *
33
+ * β›” THREE VOCABULARIES EXIST AND THEY ARE NOT ONE LIST β€” merging them is the trap on this
34
+ * contract:
35
+ * Β· `FIELD_AGGS` (iconShapes + aios_grid + user_tables) a FIELD's `agg`: the column summary.
36
+ * Β· `CHART_AGGS` (aios_grid, `avg`) STORED chart values with live data. Untouchable:
37
+ * an unknown agg falls back to `sum` and drops a
38
+ * calendar metric card, with nothing red.
39
+ * Β· `ROLLUP_FNS` (user_tables, 16 names) rollup FOLDS. Overlaps; is not the same list.
40
+ *
41
+ * ⚠ `average`, not `avg`: `ROLLUP_FNS` already spells it that way and 47 rollups run on it in
42
+ * production, so a column summary and a rollup fold name the same operation the same way.
43
+ * ⚠ `median` is in NEITHER of the other two β€” it is net-new on both sides of this contract.
44
+ */
45
+ export { FIELD_AGGS };
46
+
47
+ /** How each one reads in the picker. Sentence case, because it is a menu row, not a header.
48
+ * ⚠ The NAME differs from its source on purpose: `viewModes.tsx` has a module-local `AGG_LABELS`
49
+ * over `CHART_AGGS` where the same names wear different words, so the icon module's copy is
50
+ * prefixed. This alias keeps this module's callers reading `AGG_LABELS` and keeps ONE table. */
51
+ export const AGG_LABELS: Record<AggName, string> = FIELD_AGG_LABELS;
52
+
53
+ /**
54
+ * What THIS column may be summarised by (C7's semantics, not a preference):
55
+ * `sum Β· average Β· median Β· min Β· max` are numeric-only; `count` counts ROWS and so applies to
56
+ * every type. Offering Sum on a text column would render a number nobody can reconcile.
57
+ */
58
+ export function aggOptions(field: Field): readonly AggName[] {
59
+ return isNumericFieldType(field.type)
60
+ ? FIELD_AGGS
61
+ : FIELD_AGGS.filter((a) => a === "count");
62
+ }
63
+
64
+ /**
65
+ * The numeric value of a cell, or `undefined` β€” blank and unparseable are NOT zero.
66
+ *
67
+ * β›” IMPORTED, NOT RE-DERIVED (W29-T81 follow-up). This function and `display.numericIsBlank`
68
+ * are the same question asked by two surfaces β€” "is there a number in this cell" β€” and while
69
+ * they were two implementations they answered differently: this one stripped `$` and `,`, the
70
+ * renderer's only trimmed, so `"1,234.50"` was COUNTED in the totals row under a cell that
71
+ * painted BLANK. The fold's normalisation was the correct one and is now the only one.
72
+ */
73
+ const numOf = numericOrUndefined;
74
+
75
+ function median(sorted: number[]): number {
76
+ const mid = sorted.length >> 1;
77
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
78
+ }
79
+
80
+ /**
81
+ * Fold every field carrying an `agg` over `rows`, formatted to match its column:
82
+ * currency -> "$" + toLocaleString | everything else -> toLocaleString
83
+ * Values are rounded to 2 decimals first to kill floating-point drift (1234.5600000001).
84
+ *
85
+ * β›” **BLANK, NEVER ZERO** (C7, and the codebase's standing law): a numeric fold over a set
86
+ * holding no numeric value at all returns nothing and the cell stays empty β€” `0` is a
87
+ * measurement and this is an admission that there was nothing to measure. Only `count` returns
88
+ * `0`, because "no rows" genuinely is a count. This is also what `_rollup_fold` already does.
89
+ *
90
+ * ⚠ `count` counts ROWS IN SCOPE, not non-blank cells. `ROLLUP_FNS` splits that hair three ways
91
+ * (`count`/`counta`/`countall`); a column summary does not, and must not grow a second spelling.
92
+ */
93
+ export function computeAggs(rows: Row[], fields: Field[]): Record<string, string> {
94
+ const out: Record<string, string> = {};
95
+ for (const f of fields) {
96
+ const agg = f.agg as AggName | undefined;
97
+ if (!agg || !FIELD_AGGS.includes(agg)) continue;
98
+ if (agg === "count") {
99
+ out[f.key] = rows.length.toLocaleString();
100
+ continue;
101
+ }
102
+ if (!isNumericFieldType(f.type)) continue;
103
+ const nums: number[] = [];
104
+ for (const r of rows) {
105
+ const n = numOf(r[f.key]);
106
+ if (n !== undefined) nums.push(n);
107
+ }
108
+ if (!nums.length) continue; // blank, never zero
109
+ let value: number;
110
+ if (agg === "sum") value = nums.reduce((a, b) => a + b, 0);
111
+ else if (agg === "average") value = nums.reduce((a, b) => a + b, 0) / nums.length;
112
+ else if (agg === "median") value = median([...nums].sort((a, b) => a - b));
113
+ else if (agg === "min") value = Math.min(...nums);
114
+ else value = Math.max(...nums);
115
+ const clean = Math.round(value * 100) / 100; // drop float artifacts
116
+ out[f.key] = f.type === "currency" ? "$" + clean.toLocaleString() : clean.toLocaleString();
117
+ }
118
+ return out;
119
+ }
web/src/customer-grid/display.ts CHANGED
@@ -98,10 +98,31 @@ export function num(v: CellValue): number {
98
  * number nobody typed.
99
  */
100
  export function numericIsBlank(v: CellValue): boolean {
101
- if (v === null || v === undefined) return true;
102
- const text = typeof v === "number" ? String(v) : String(v).trim();
103
- if (text === "") return true;
104
- return !Number.isFinite(Number(text));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  }
106
 
107
  /**
 
98
  * number nobody typed.
99
  */
100
  export function numericIsBlank(v: CellValue): boolean {
101
+ return numericOrUndefined(v) === undefined;
102
+ }
103
+
104
+ /**
105
+ * β›”β›” THE ONE NUMERIC READING OF A STORED CELL, and it has to be one.
106
+ *
107
+ * `numericIsBlank` decides whether the CANVAS paints anything; `aggregations.numOf` decides
108
+ * whether the TOTALS ROW counts it. They were written separately and normalised differently β€”
109
+ * this one trimmed, that one stripped `$`, `,` and spaces β€” so `"1,234.50"` painted BLANK in the
110
+ * cell and was COUNTED in the total underneath it. That is T81's own defect ("two surfaces
111
+ * disagreeing about one cell") reintroduced in the opposite direction, by the fix for it, and no
112
+ * test could see it because every value in the legs was comma-free.
113
+ *
114
+ * ⚠ Human spellings are ACCEPTED here on purpose. `coerceClipboardValue` canonicalises what the
115
+ * UI writes, but the import door refuses-without-rewriting by design, so a `"$45"` posted by curl
116
+ * is storable β€” and the honest reading of that cell is 45 on BOTH surfaces, never 45 in the total
117
+ * and nothing in the cell ([[one-evaluator-per-question]]).
118
+ */
119
+ export function numericOrUndefined(v: CellValue): number | undefined {
120
+ if (v === null || v === undefined || v === "") return undefined;
121
+ if (typeof v === "number") return Number.isFinite(v) ? v : undefined;
122
+ const cleaned = String(v).replace(/[$,\s]/g, "");
123
+ if (cleaned === "") return undefined; // " " is blank, not the zero `Number("")` gives
124
+ const n = Number(cleaned);
125
+ return Number.isFinite(n) ? n : undefined;
126
  }
127
 
128
  /**
web/src/customer-grid/iconShapes.ts CHANGED
@@ -16,7 +16,7 @@
16
  // currentColor. Vector paths only β€” NEVER emoji (owner constant).
17
  // ---------------------------------------------------------------------------
18
 
19
- import type { DisplayMode, FieldType, FolderShape, FolderTone } from "./types";
20
  import {
21
  LP_BLUE,
22
  LP_BLUE_DEEP,
@@ -634,7 +634,10 @@ export const TYPE_LABELS: Record<FieldType, string> = {
634
  * for that is ALREADY `isNumericFieldType` (types.ts) β€” do not write a second one. `count` is
635
  * legal on any type.
636
  */
637
- export type FieldAgg = "sum" | "average" | "median" | "min" | "max" | "count";
 
 
 
638
 
639
  /** ORDERED β€” the order is the picker's order, on both engines. */
640
  export const FIELD_AGGS: readonly FieldAgg[] = [
 
16
  // currentColor. Vector paths only β€” NEVER emoji (owner constant).
17
  // ---------------------------------------------------------------------------
18
 
19
+ import type { AggName, DisplayMode, FieldType, FolderShape, FolderTone } from "./types";
20
  import {
21
  LP_BLUE,
22
  LP_BLUE_DEEP,
 
634
  * for that is ALREADY `isNumericFieldType` (types.ts) β€” do not write a second one. `count` is
635
  * legal on any type.
636
  */
637
+ // ⭐ W29-T74 β€” an ALIAS of `types.AggName`, not a fifth copy of the union. `Field.agg` is typed
638
+ // `AggName`, so a second literal here would be a type that has to be kept in step by eye with a
639
+ // type the compiler already owns β€” the same defect as the array below, one level up.
640
+ export type FieldAgg = AggName;
641
 
642
  /** ORDERED β€” the order is the picker's order, on both engines. */
643
  export const FIELD_AGGS: readonly FieldAgg[] = [
web/src/customer-grid/icons.tsx CHANGED
@@ -316,6 +316,22 @@ const MENU_ICONS = {
316
  <path d="M11.5 8.5v5M9 11h5" {...miStroke} />
317
  </>
318
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  } as const;
320
 
321
  export type MenuIconName = keyof typeof MENU_ICONS;
 
316
  <path d="M11.5 8.5v5M9 11h5" {...miStroke} />
317
  </>
318
  ),
319
+ /**
320
+ * ⭐ W29 close-out β€” IMPORT's own mark, asked for by E and taken by the integrator while
321
+ * W29-T78 had this menu open anyway.
322
+ *
323
+ * `download` MIRRORED: the same tray, the same stem, the arrowhead at the top instead of the
324
+ * bottom β€” so Export and Import read as one gesture in two directions rather than as two
325
+ * unrelated glyphs. It replaces a borrowed `cohortAdd` (a LIST with a plus), which named
326
+ * "add to a cohort" on a row that imports a spreadsheet: a borrowed mark is a small lie that
327
+ * a menu repeats every time it opens.
328
+ */
329
+ upload: (
330
+ <>
331
+ <path d="M8 9.5v-7M5.3 5.2 8 2.5l2.7 2.7" {...miStroke} />
332
+ <path d="M3 11v1.5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V11" {...miStroke} />
333
+ </>
334
+ ),
335
  } as const;
336
 
337
  export type MenuIconName = keyof typeof MENU_ICONS;
web/src/customer-grid/viewModes.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/index.css CHANGED
@@ -3837,6 +3837,22 @@ body {
3837
  min-width: 0;
3838
  overflow-wrap: anywhere;
3839
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3840
  /* ⚠ WHICH OF THE TWO SHRINKS, and why `min-width: 0` alone was not the answer.
3841
  Both children default to `flex-shrink: 1`, and flexbox distributes shrinkage in proportion to
3842
  BASE SIZE β€” so once `min-width: 0` let them shrink at all, the 80-character value (base ~500px)
 
3837
  min-width: 0;
3838
  overflow-wrap: anywhere;
3839
  }
3840
+ /* β›” W29-T80 β€” a CHOICE value on a card is a tinted chip, as it is on the canvas, in the record
3841
+ panel and on the lane header. The colours are INLINE (they come from the field's stored
3842
+ `optionColors` and are per-option, so they cannot live in a stylesheet); this rule is only the
3843
+ chip's shape. Kept beside the pair above because it must inherit the same wrap behaviour β€” a
3844
+ long option label has to break inside the chip rather than widen the card. */
3845
+ .cg-kb-cell .cg-kb-chip {
3846
+ border: 1px solid transparent;
3847
+ border-radius: 999px;
3848
+ padding: 0 8px;
3849
+ line-height: 1.5;
3850
+ font-weight: 500;
3851
+ /* `inline-block`, not `inline`: an inline box ignores the vertical padding above and the
3852
+ tint would paint outside the row it belongs to. */
3853
+ display: inline-block;
3854
+ max-width: 100%;
3855
+ }
3856
  /* ⚠ WHICH OF THE TWO SHRINKS, and why `min-width: 0` alone was not the answer.
3857
  Both children default to `flex-shrink: 1`, and flexbox distributes shrinkage in proportion to
3858
  BASE SIZE β€” so once `min-width: 0` let them shrink at all, the 80-character value (base ~500px)