fsanyoto commited on
Commit
992a41f
·
verified ·
1 Parent(s): b756371

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (50) hide show
  1. Dockerfile +25 -14
  2. RELEASES.json +2 -435
  3. VERSION +1 -1
  4. api/connectors_amazon.py +76 -19
  5. api/main.py +51 -0
  6. api/odoo_relational.py +85 -7
  7. api/routes_auth.py +178 -2
  8. api/routes_connectors.py +197 -51
  9. api/routes_security.py +501 -0
  10. api/routes_sheet.py +131 -12
  11. api/routes_templates.py +90 -0
  12. platform/core/audit.py +176 -0
  13. platform/core/keychain.py +136 -19
  14. platform/core/sheet_templates.py +253 -0
  15. platform/core/users.py +20 -8
  16. platform/harness/amazon_client.py +177 -0
  17. platform/harness/amazon_schema.py +114 -0
  18. platform/harness/amazon_store.py +594 -64
  19. platform/modules/sheet.py +89 -38
  20. web/package-lock.json +26 -15
  21. web/package.json +4 -0
  22. web/src/connectors/ConnectorModal.tsx +109 -27
  23. web/src/connectors/DatabasesTab.tsx +110 -39
  24. web/src/connectors/KeychainTab.tsx +244 -46
  25. web/src/customer-grid/SwipeView.tsx +586 -586
  26. web/src/settings/CompliancePane.tsx +151 -0
  27. web/src/settings/SecurityPane.tsx +303 -24
  28. web/src/sheet/BindingEditor.tsx +186 -35
  29. web/src/sheet/ChartDialog.tsx +205 -16
  30. web/src/sheet/Ribbon.tsx +170 -95
  31. web/src/sheet/SheetChart.tsx +15 -3
  32. web/src/sheet/SheetGrid.tsx +138 -29
  33. web/src/sheet/SheetRail.tsx +17 -0
  34. web/src/sheet/ribbonIcons.tsx +68 -0
  35. web/src/sheet/ribbonInsert.tsx +55 -13
  36. web/src/sheet/shortcuts.ts +24 -3
  37. web/src/sheet/templates/TemplateGallery.tsx +167 -0
  38. web/src/sheet/templates/templatesApi.ts +87 -0
  39. web/src/sheet/templates/types.ts +13 -0
  40. web/src/shell/LoginPage.tsx +27 -141
  41. web/src/shell/Shell.tsx +149 -7
  42. web/src/shell/qrcode.ts +242 -0
  43. web/src/styles/wave52/ribbon.css +74 -0
  44. web/src/styles/wave54/ribbon-insert.css +60 -33
  45. web/src/styles/wave55/apps.css +47 -9
  46. web/src/styles/wave59/binding.css +43 -0
  47. web/src/styles/wave59/chart-dialog.css +156 -0
  48. web/src/styles/wave59/connectors.css +101 -0
  49. web/src/styles/wave59/security.css +61 -0
  50. web/src/styles/wave59/templates.css +150 -0
Dockerfile CHANGED
@@ -23,19 +23,17 @@ WORKDIR /web
23
  # The lockfile is the audited supply-chain boundary. It now resolves entirely from the public
24
  # registry; discarding it here made every image an unreviewed dependency upgrade.
25
  #
26
- # ⛔⛔ `npm ci` WAS TRIED HERE AND CANNOT WORK FROM A WINDOWS-RESOLVED LOCKFILE. Measured
27
- # 2026-09-13: the build died with `Missing: @emnapi/runtime@1.11.3 from lock file`. npm on Windows
28
- # prunes the linux-x64 rolldown binding and its transitive `@emnapi/runtime`, and `npm ci` treats
29
- # any absent entry as a fatal lockfile mismatch rather than a platform gap. Regenerating with
30
- # `--os=linux --cpu=x64` only inverts the failure: the lockfile then builds on Linux and breaks
31
- # `npm ci` on every developer's Windows box.
32
- #
33
- # `npm install` WITH the lockfile present keeps the audited versions as the boundary — it honours
34
- # every pin it can resolve — while repairing a platform-only gap instead of aborting. This is NOT
35
- # the pre-83bfed7 `--no-package-lock`, which discarded the audit entirely.
36
- # The real fix is a lockfile generated on Linux; booked as W-170.
37
  COPY web/package.json web/package-lock.json ./
38
- RUN npm install --no-audit --no-fund --ignore-scripts
 
 
39
  COPY web/ ./
40
  RUN npm run build # -> /web/dist
41
 
@@ -43,7 +41,12 @@ RUN npm run build # -> /web/dist
43
  FROM python:3.12-slim
44
  WORKDIR /app
45
  COPY requirements.txt ./
46
- RUN pip install --no-cache-dir -r requirements.txt
 
 
 
 
 
47
  COPY api/ ./api/
48
  # the reused data layer (modules/core/harness)
49
  # ⛔ COMMENT ON ITS OWN LINE. Docker does NOT support a trailing comment on an instruction:
@@ -60,6 +63,7 @@ COPY platform/ ./platform/
60
  # up: a file the product opens BY PATH is invisible to every import-following guard we own.
61
  COPY jobs/ ./jobs/
62
  COPY --from=web /web/dist ./web/dist
 
63
 
64
  # Run unprivileged — the C2 security baseline, and matched to ops/Dockerfile.api so the two images
65
  # do not differ on a property that would only surface after a migration. uid 1000 is what HF
@@ -69,6 +73,7 @@ USER user
69
 
70
  ENV RI_DIR=/app/platform \
71
  PORT=7860 \
 
72
  PYTHONUNBUFFERED=1 \
73
  AIOS_PREWARM=1
74
  # ⛔ AIOS_INSECURE_SSL is deliberately NOT set. It disables TLS verification for every outbound
@@ -85,4 +90,10 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
85
  # a launcher argument — which is what makes moving hosts a config change instead of a code change.
86
  # Secrets (Odoo creds, APP_PASSWORD, AIOS_SESSION_SECRET, APP_BASE_URL) arrive as env at RUN time
87
  # and are never baked; the repo-root .dockerignore drops **/.env from the build context.
88
- CMD ["sh", "-c", "uvicorn api.main:app --host 0.0.0.0 --port ${PORT}"]
 
 
 
 
 
 
 
23
  # The lockfile is the audited supply-chain boundary. It now resolves entirely from the public
24
  # registry; discarding it here made every image an unreviewed dependency upgrade.
25
  #
26
+ # 2026-09-13: the Windows-resolved lockfile failed `npm ci` with
27
+ # `Missing: @emnapi/runtime@1.11.3 from lock file`, so this stage temporarily used `npm install`
28
+ # to repair the platform gap. W59-T35 regenerated from the committed lock with node_modules
29
+ # absent on Linux x64 (Node 22.23.2 / npm 10.9.8), then proved a fresh `npm ci` succeeds.
30
+ # Restore the frozen install: future lockfile gaps must fail the build, not resolve during it.
31
+ # Windows execution still needs its own proof. --engine-strict makes the Node/npm engines a
32
+ # build failure on a mismatched toolchain; npm otherwise only warns.
 
 
 
 
33
  COPY web/package.json web/package-lock.json ./
34
+ RUN npm ci --no-audit --no-fund --ignore-scripts --engine-strict
35
+ # Keep the resolved build tree: the final image has the bundle but no Node installation.
36
+ RUN mkdir -p /deps && npm ls --all --json > /deps/web-deps.json
37
  COPY web/ ./
38
  RUN npm run build # -> /web/dist
39
 
 
41
  FROM python:3.12-slim
42
  WORKDIR /app
43
  COPY requirements.txt ./
44
+ # W59-T35, 2026-09-13: pin the locally installed resolver instead of upgrading pip implicitly.
45
+ # The Space uploader still sends aios-web/requirements.txt with open bounds and excludes the
46
+ # pinned api/requirements.txt. Wiring those pins into the upload is a separate deployment fix;
47
+ # changing COPY to api/requirements.txt alone would refer to a file absent from the Space.
48
+ RUN python -m pip install --no-cache-dir --disable-pip-version-check --upgrade "pip==25.0.1" \
49
+ && python -m pip install --no-cache-dir --disable-pip-version-check -r requirements.txt
50
  COPY api/ ./api/
51
  # the reused data layer (modules/core/harness)
52
  # ⛔ COMMENT ON ITS OWN LINE. Docker does NOT support a trailing comment on an instruction:
 
63
  # up: a file the product opens BY PATH is invisible to every import-following guard we own.
64
  COPY jobs/ ./jobs/
65
  COPY --from=web /web/dist ./web/dist
66
+ COPY --from=web /deps/web-deps.json ./deps/web-deps.json
67
 
68
  # Run unprivileged — the C2 security baseline, and matched to ops/Dockerfile.api so the two images
69
  # do not differ on a property that would only surface after a migration. uid 1000 is what HF
 
73
 
74
  ENV RI_DIR=/app/platform \
75
  PORT=7860 \
76
+ FORWARDED_ALLOW_IPS=* \
77
  PYTHONUNBUFFERED=1 \
78
  AIOS_PREWARM=1
79
  # ⛔ AIOS_INSECURE_SSL is deliberately NOT set. It disables TLS verification for every outbound
 
90
  # a launcher argument — which is what makes moving hosts a config change instead of a code change.
91
  # Secrets (Odoo creds, APP_PASSWORD, AIOS_SESSION_SECRET, APP_BASE_URL) arrive as env at RUN time
92
  # and are never baked; the repo-root .dockerignore drops **/.env from the build context.
93
+ # W59-T35: the Space terminates TLS at its ingress proxy, so honour its forwarded scheme/client.
94
+ # '*' assumes the container is unreachable except through that trusted proxy, which must replace
95
+ # client-supplied forwarded headers. For any direct ingress, set FORWARDED_ALLOW_IPS to the actual
96
+ # proxy IPs/CIDRs before exposing the port; do not carry wildcard trust onto a public listener.
97
+ # Suppress the server banner and release idle keep-alive sockets after five seconds. W59-T36
98
+ # owns the API posture read-back and application host/header policy; these flags are its launcher seam.
99
+ CMD ["sh", "-c", "uvicorn api.main:app --host 0.0.0.0 --port ${PORT} --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS}\" --no-server-header --timeout-keep-alive 5"]
RELEASES.json CHANGED
@@ -1,437 +1,4 @@
1
  {
2
- "current": "3859b71",
3
- "releases": [
4
- {
5
- "version": "v73",
6
- "sha": "bb94de5",
7
- "date": "2026-09-13",
8
- "subject": "release v73"
9
- },
10
- {
11
- "version": "v71",
12
- "sha": "96143dc",
13
- "date": "2026-09-04",
14
- "subject": "release v71 - wave 51, QA'd 24 PASS / 6 FAIL / 5 UNPROVEN"
15
- },
16
- {
17
- "version": "v70",
18
- "sha": "eedfb6a",
19
- "date": "2026-09-03",
20
- "subject": "release v70 - wave 50 (grid analytics, the Sheet as a spreadsheet, view trash and audit)"
21
- },
22
- {
23
- "version": "v69",
24
- "sha": "8598f56",
25
- "date": "2026-09-02",
26
- "subject": "release v69: wave48-continuation validated + hotfixes v67/v68/d4e3e31 + go-live QA repairs (Supplier option limit, optio"
27
- },
28
- {
29
- "version": "v68",
30
- "sha": "62b065a",
31
- "date": "2026-09-01",
32
- "subject": "release v68: unified holiday date offsets"
33
- },
34
- {
35
- "version": "v67",
36
- "sha": "3b22419",
37
- "date": "2026-09-01",
38
- "subject": "release v67"
39
- },
40
- {
41
- "version": "v66",
42
- "sha": "73c94f0",
43
- "date": "2026-08-31",
44
- "subject": "release v66"
45
- },
46
- {
47
- "version": "v65",
48
- "sha": "9f6cfed",
49
- "date": "2026-08-31",
50
- "subject": "release v65"
51
- },
52
- {
53
- "version": "v64",
54
- "sha": "bb8985c",
55
- "date": "2026-08-31",
56
- "subject": "release v64"
57
- },
58
- {
59
- "version": "v63",
60
- "sha": "ec75cb8",
61
- "date": "2026-08-31",
62
- "subject": "release v63"
63
- },
64
- {
65
- "version": "v62",
66
- "sha": "2c8f702",
67
- "date": "2026-08-31",
68
- "subject": "release v62"
69
- },
70
- {
71
- "version": "v61",
72
- "sha": "bbc4c07",
73
- "date": "2026-08-30",
74
- "subject": "v61 - wave 46 hotfix: D-590 schema overlay reaches the grid read (all three assemblies), D-599 route to zone association"
75
- },
76
- {
77
- "version": "v60",
78
- "sha": "dd1b062",
79
- "date": "2026-08-30",
80
- "subject": "v60 - wave 46"
81
- },
82
- {
83
- "version": "v59",
84
- "sha": "3cb73ce",
85
- "date": "2026-08-29",
86
- "subject": "release v59"
87
- },
88
- {
89
- "version": "v58",
90
- "sha": "c526ced",
91
- "date": "2026-08-29",
92
- "subject": "release v58"
93
- },
94
- {
95
- "version": "v57",
96
- "sha": "4859c03",
97
- "date": "2026-08-29",
98
- "subject": "release v57"
99
- },
100
- {
101
- "version": "v56",
102
- "sha": "2970b72",
103
- "date": "2026-08-28",
104
- "subject": "release v56"
105
- },
106
- {
107
- "version": "v55",
108
- "sha": "b766b90",
109
- "date": "2026-08-28",
110
- "subject": "release v55"
111
- },
112
- {
113
- "version": "v54",
114
- "sha": "6a8e99a",
115
- "date": "2026-08-27",
116
- "subject": "release v54"
117
- },
118
- {
119
- "version": "v53",
120
- "sha": "89ed2cb",
121
- "date": "2026-08-24",
122
- "subject": "release v53"
123
- },
124
- {
125
- "version": "v52",
126
- "sha": "8263493",
127
- "date": "2026-08-23",
128
- "subject": "release v52"
129
- },
130
- {
131
- "version": "v51",
132
- "sha": "5740d20",
133
- "date": "2026-08-23",
134
- "subject": "release v51"
135
- },
136
- {
137
- "version": "v50",
138
- "sha": "8027c83",
139
- "date": "2026-08-23",
140
- "subject": "release v50"
141
- },
142
- {
143
- "version": "v49",
144
- "sha": "9a14c01",
145
- "date": "2026-08-23",
146
- "subject": "release v49"
147
- },
148
- {
149
- "version": "v48",
150
- "sha": "3c69fd9",
151
- "date": "2026-08-23",
152
- "subject": "release v48"
153
- },
154
- {
155
- "version": "v47",
156
- "sha": "917f9a0",
157
- "date": "2026-08-23",
158
- "subject": "release v47"
159
- },
160
- {
161
- "version": "v46",
162
- "sha": "a8dc531",
163
- "date": "2026-08-23",
164
- "subject": "release v46"
165
- },
166
- {
167
- "version": "v45",
168
- "sha": "0b2b501",
169
- "date": "2026-08-23",
170
- "subject": "release v45"
171
- },
172
- {
173
- "version": "v44",
174
- "sha": "a7877aa",
175
- "date": "2026-08-23",
176
- "subject": "Hotfix: allow renaming the active Map view"
177
- },
178
- {
179
- "version": "v43",
180
- "sha": "e2ba461",
181
- "date": "2026-08-23",
182
- "subject": "release v43"
183
- },
184
- {
185
- "version": "v42",
186
- "sha": "25b885e",
187
- "date": "2026-08-23",
188
- "subject": "release v42"
189
- },
190
- {
191
- "version": "v41",
192
- "sha": "1d6adcc",
193
- "date": "2026-08-22",
194
- "subject": "v41 vertical route navigation"
195
- },
196
- {
197
- "version": "v40",
198
- "sha": "1451837",
199
- "date": "2026-08-22",
200
- "subject": "release v40 route UI correction"
201
- },
202
- {
203
- "version": "v39",
204
- "sha": "a78bdf0",
205
- "date": "2026-08-21",
206
- "subject": "W39 clean stale migration targets"
207
- },
208
- {
209
- "version": "v38",
210
- "sha": "a556631",
211
- "date": "2026-08-21",
212
- "subject": "W39 reversible Live store cutover"
213
- },
214
- {
215
- "version": "v37",
216
- "sha": "1ddd8cf",
217
- "date": "2026-08-21",
218
- "subject": "W39: coalesce derived workspace reads"
219
- },
220
- {
221
- "version": "v36",
222
- "sha": "51db3b7",
223
- "date": "2026-08-21",
224
- "subject": "W39 share-field oid repair"
225
- },
226
- {
227
- "version": "v35",
228
- "sha": "0f64212",
229
- "date": "2026-08-21",
230
- "subject": "W39 visual QA fixture"
231
- },
232
- {
233
- "version": "v34",
234
- "sha": "cb4caa1",
235
- "date": "2026-08-21",
236
- "subject": "W39 Staging PostgreSQL egress controls"
237
- },
238
- {
239
- "version": "v33",
240
- "sha": "2b115e5",
241
- "date": "2026-08-21",
242
- "subject": "W39: stop nonproduction Postgres background egress"
243
- },
244
- {
245
- "version": "v32",
246
- "sha": "b47b27c",
247
- "date": "2026-08-21",
248
- "subject": "W39: repair Staging Postgres projection"
249
- },
250
- {
251
- "version": "v31",
252
- "sha": "8880a49",
253
- "date": "2026-08-21",
254
- "subject": "v31: Wave 39 staging candidate"
255
- },
256
- {
257
- "version": "v30",
258
- "sha": "71776ca",
259
- "date": "2026-08-20",
260
- "subject": "v30: W39-T29 Member-owned View first-share hotfix"
261
- },
262
- {
263
- "version": "v29",
264
- "sha": "55ced50",
265
- "date": "2026-08-18",
266
- "subject": "v29: the build staging has been running since 2026-08-18 (55ced50)."
267
- },
268
- {
269
- "version": "v28",
270
- "sha": "2793e4b",
271
- "date": "2026-08-18",
272
- "subject": "release v28"
273
- },
274
- {
275
- "version": "v27",
276
- "sha": "c05a794",
277
- "date": "2026-08-18",
278
- "subject": "release v27"
279
- },
280
- {
281
- "version": "v25",
282
- "sha": "bc24829",
283
- "date": "2026-08-14",
284
- "subject": "v25 - wave 32's LIVE build (deployed 2026-08-13, bc24829)"
285
- },
286
- {
287
- "version": "v26",
288
- "sha": "6a642e1",
289
- "date": "2026-08-14",
290
- "subject": "v26 - wave 33's build (deployed 2026-08-14, 6a642e1)"
291
- },
292
- {
293
- "version": "v24",
294
- "sha": "514d829",
295
- "date": "2026-08-09",
296
- "subject": "release v24"
297
- },
298
- {
299
- "version": "v23",
300
- "sha": "44cc283",
301
- "date": "2026-08-09",
302
- "subject": "release v23"
303
- },
304
- {
305
- "version": "v22",
306
- "sha": "f14e199",
307
- "date": "2026-08-09",
308
- "subject": "release v22"
309
- },
310
- {
311
- "version": "v21",
312
- "sha": "5fdffce",
313
- "date": "2026-08-09",
314
- "subject": "release v21"
315
- },
316
- {
317
- "version": "v20",
318
- "sha": "442e4a1",
319
- "date": "2026-08-09",
320
- "subject": "release v20"
321
- },
322
- {
323
- "version": "v19",
324
- "sha": "94cb4a4",
325
- "date": "2026-08-09",
326
- "subject": "release v19"
327
- },
328
- {
329
- "version": "v18",
330
- "sha": "0106ef9",
331
- "date": "2026-08-09",
332
- "subject": "release v18"
333
- },
334
- {
335
- "version": "v17",
336
- "sha": "308240c",
337
- "date": "2026-08-09",
338
- "subject": "release v17"
339
- },
340
- {
341
- "version": "v16",
342
- "sha": "a804df5",
343
- "date": "2026-08-09",
344
- "subject": "release v16"
345
- },
346
- {
347
- "version": "v15",
348
- "sha": "6b84d72",
349
- "date": "2026-08-09",
350
- "subject": "release v15"
351
- },
352
- {
353
- "version": "v14",
354
- "sha": "bee5eaf",
355
- "date": "2026-08-07",
356
- "subject": "release v14"
357
- },
358
- {
359
- "version": "v13",
360
- "sha": "314c0e3",
361
- "date": "2026-08-06",
362
- "subject": "release v13"
363
- },
364
- {
365
- "version": "v12",
366
- "sha": "4908f39",
367
- "date": "2026-08-06",
368
- "subject": "release v12"
369
- },
370
- {
371
- "version": "v11",
372
- "sha": "3126617",
373
- "date": "2026-08-05",
374
- "subject": "release v11"
375
- },
376
- {
377
- "version": "v10",
378
- "sha": "43f8042",
379
- "date": "2026-08-05",
380
- "subject": "release v10"
381
- },
382
- {
383
- "version": "v9",
384
- "sha": "2e26f57",
385
- "date": "2026-08-05",
386
- "subject": "release v9"
387
- },
388
- {
389
- "version": "v8",
390
- "sha": "8073b3e",
391
- "date": "2026-08-05",
392
- "subject": "release v8"
393
- },
394
- {
395
- "version": "v7",
396
- "sha": "b1c5a7e",
397
- "date": "2026-08-05",
398
- "subject": "release v7"
399
- },
400
- {
401
- "version": "v6",
402
- "sha": "a344020",
403
- "date": "2026-08-05",
404
- "subject": "release v6"
405
- },
406
- {
407
- "version": "v5",
408
- "sha": "c0b0fbb",
409
- "date": "2026-08-05",
410
- "subject": "release v5"
411
- },
412
- {
413
- "version": "v4",
414
- "sha": "de5037f",
415
- "date": "2026-08-05",
416
- "subject": "release v4"
417
- },
418
- {
419
- "version": "v3",
420
- "sha": "6b9fa62",
421
- "date": "2026-08-05",
422
- "subject": "release v3"
423
- },
424
- {
425
- "version": "v2",
426
- "sha": "fd05861",
427
- "date": "2026-08-04",
428
- "subject": "release v2"
429
- },
430
- {
431
- "version": "v1",
432
- "sha": "5b4e2c4",
433
- "date": "2026-08-04",
434
- "subject": "release v1"
435
- }
436
- ]
437
  }
 
1
  {
2
+ "current": "3ba892f",
3
+ "releases": []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 3859b71
 
1
+ 3ba892f
api/connectors_amazon.py CHANGED
@@ -44,6 +44,56 @@ from harness.amazon_client import ( # noqa: F
44
  #: comments in `keychain.py` warn about it in as many words.
45
  ENTRY_TYPE = "amazon_sp"
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  #: W55-T19 / R7 / C10 — AMAZON'S OWN ENABLEMENT DOCUMENT. This is deliberately not Odoo's
48
  #: model catalogue or connector config: Amazon publishes report schemas, not ``fields_get``, and
49
  #: its seven databases are enabled at the provider boundary rather than masquerading as Odoo
@@ -139,7 +189,13 @@ def enablement_capability(rt, is_admin):
139
  "available": state["available"]}
140
 
141
 
142
- def probe_credential(fields, timeout=8):
 
 
 
 
 
 
143
  """`{ok, message}` for a stored `amazon_sp` credential: the keychain's liveness probe.
144
 
145
  ⛔ IT LIVES HERE, IN THE API LAYER, AND IS REGISTERED INTO `core.keychain` RATHER THAN IMPORTED
@@ -151,26 +207,27 @@ def probe_credential(fields, timeout=8):
151
  reports zero ad accounts that way: a credential that authenticates but reaches nothing is an
152
  authorization answer, and `ok: true` would hide the one thing the admin has to fix.
153
  """
154
- f = fields or {}
155
- missing = [k for k in ("client_id", "client_secret", "refresh_token") if not f.get(k)]
 
156
  if missing:
157
  return {"ok": False,
158
- "message": "store " + ", ".join(f"`{m}`" for m in missing)
159
- + " alongside `seller_id` and `marketplace_id`"}
160
  try:
161
- parts = marketplace_participations(f, timeout=timeout)
162
- except AmazonError as e:
163
- return {"ok": False, "message": str(e)[:200]}
164
- live = [p for p in parts
165
- if ((p or {}).get("participation") or {}).get("isParticipating") is not False]
166
- n = len(live)
167
- if not n:
 
 
 
 
168
  return {"ok": False,
169
- "message": "the credential authenticates but participates in NO marketplace: "
170
- "that is an authorization answer, not an empty account"}
171
- names = ", ".join(sorted({str(((p or {}).get("marketplace") or {}).get("countryCode") or "?")
172
- for p in live}))
173
- return {"ok": True, "message": f"Amazon answered. {n} marketplace(s) reachable: {names}"}
174
 
175
 
176
  def register():
@@ -294,11 +351,11 @@ def main(argv):
294
  print("")
295
  try:
296
  probe_report(f, report_type=which)
297
- except Exception as e: # noqa: BLE001
298
  # ⚠ REPORTED, NOT RAISED. The probe is a diagnostic: a refusal is a RESULT the operator
299
  # needs to read (a role they lack, a throttle, an unsupported sandbox report type), not
300
  # a traceback that buries it.
301
- print(f"REPORT PROBE REFUSED: {type(e).__name__}: {e}")
302
  return 1
303
  return 0
304
 
 
44
  #: comments in `keychain.py` warn about it in as many words.
45
  ENTRY_TYPE = "amazon_sp"
46
 
47
+
48
+ class AmazonStatusSafetyError(ValueError):
49
+ """A status response contains a forbidden credential shape."""
50
+
51
+
52
+ def status_payload_has_secret(serialized_payload):
53
+ """Scan serialized JSON for C2's credential keys, token shapes and oversized values.
54
+
55
+ Pure and usable without a server. Invalid JSON is unsafe too; never echo rejected content.
56
+ The credential key roster is the same one the connector accepts at connect time.
57
+ """
58
+ import json
59
+ import re
60
+
61
+ try:
62
+ pending = [json.loads(serialized_payload, object_pairs_hook=lambda pairs: pairs)]
63
+ except (TypeError, ValueError, UnicodeError, RecursionError):
64
+ return True
65
+ credential_keys = {key.casefold() for key in CREDENTIAL_FIELDS}
66
+ while pending:
67
+ value = pending.pop()
68
+ if isinstance(value, tuple):
69
+ key, item = value
70
+ if key.casefold() in credential_keys:
71
+ return True
72
+ pending.extend((key, item))
73
+ elif isinstance(value, list):
74
+ pending.extend(value)
75
+ elif isinstance(value, str):
76
+ if (len(value) > 512 or 'Atzr|' in value
77
+ or re.search(r'\bbearer\s+\S+', value, flags=re.IGNORECASE)):
78
+ return True
79
+ elif value is not None and len(str(value)) > 512:
80
+ return True
81
+ return False
82
+
83
+
84
+ def assert_safe_status(payload):
85
+ """Return a status only after scanning its serialized form, or raise without its content."""
86
+ import json
87
+
88
+ try:
89
+ serialized = json.dumps(payload, ensure_ascii=False, allow_nan=False)
90
+ except (TypeError, ValueError, RecursionError):
91
+ raise AmazonStatusSafetyError('Amazon status could not be safely serialized.') from None
92
+ if status_payload_has_secret(serialized):
93
+ raise AmazonStatusSafetyError('Amazon status contains a forbidden credential shape.')
94
+ return payload
95
+
96
+
97
  #: W55-T19 / R7 / C10 — AMAZON'S OWN ENABLEMENT DOCUMENT. This is deliberately not Odoo's
98
  #: model catalogue or connector config: Amazon publishes report schemas, not ``fields_get``, and
99
  #: its seven databases are enabled at the provider boundary rather than masquerading as Odoo
 
189
  "available": state["available"]}
190
 
191
 
192
+ def probe_credential(fields, timeout=8, *, fetch_participations=None):
193
+ """Return the guarded Amazon status; a disclosure violation must raise at this boundary."""
194
+ return assert_safe_status(_probe_credential_result(
195
+ fields, timeout, fetch_participations=fetch_participations))
196
+
197
+
198
+ def _probe_credential_result(fields, timeout=8, *, fetch_participations=None):
199
  """`{ok, message}` for a stored `amazon_sp` credential: the keychain's liveness probe.
200
 
201
  ⛔ IT LIVES HERE, IN THE API LAYER, AND IS REGISTERED INTO `core.keychain` RATHER THAN IMPORTED
 
207
  reports zero ad accounts that way: a credential that authenticates but reaches nothing is an
208
  authorization answer, and `ok: true` would hide the one thing the admin has to fix.
209
  """
210
+ f = fields if isinstance(fields, dict) else {}
211
+ missing = [key for key in CREDENTIAL_FIELDS
212
+ if not isinstance(f.get(key), str) or not f[key].strip()]
213
  if missing:
214
  return {"ok": False,
215
+ "message": "Missing " + ", ".join(missing) + ". Enter every required field."}
 
216
  try:
217
+ # Bind only when explicitly tested. Shape gates can inject a local response function.
218
+ fetch = fetch_participations if fetch_participations is not None else marketplace_participations
219
+ parts = fetch(f, timeout=timeout)
220
+ live = [part for part in parts if isinstance(part, dict)
221
+ and isinstance(part.get("participation"), dict)
222
+ and part["participation"].get("isParticipating") is True]
223
+ if not live:
224
+ return {"ok": False,
225
+ "message": "Amazon reported no active marketplace access. Check authorization and test again."}
226
+ except Exception: # noqa: BLE001
227
+ # AmazonError includes provider-supplied text and an invalid region can echo user input.
228
  return {"ok": False,
229
+ "message": "Amazon did not confirm marketplace access. Check the five fields and test again."}
230
+ return {"ok": True, "message": "Amazon confirmed marketplace access."}
 
 
 
231
 
232
 
233
  def register():
 
351
  print("")
352
  try:
353
  probe_report(f, report_type=which)
354
+ except Exception: # noqa: BLE001
355
  # ⚠ REPORTED, NOT RAISED. The probe is a diagnostic: a refusal is a RESULT the operator
356
  # needs to read (a role they lack, a throttle, an unsupported sandbox report type), not
357
  # a traceback that buries it.
358
+ print("REPORT PROBE REFUSED: Amazon did not confirm the report. Check authorization and try again.")
359
  return 1
360
  return 0
361
 
api/main.py CHANGED
@@ -286,6 +286,28 @@ def health():
286
  return {"ok": True}
287
 
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  app.include_router(routes_auth.router)
290
  app.include_router(routes_nav.router)
291
  app.include_router(routes_customers.router)
@@ -463,6 +485,7 @@ app.include_router(routes_agent_harness.router) # R8 / C4 — versioned agent h
463
  # rate-limited by POLITENESS rather than by a bill (~1 req/s, and bulk harvesting is forbidden).
464
  app.include_router(routes_geo.router) # R14 / A11 — D's router, A's line (map providers)
465
  app.include_router(routes_external.router)
 
466
 
467
 
468
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
@@ -632,6 +655,7 @@ def _seed_and_sync_store():
632
  # than in tomorrow's. It is idempotent, so every later boot is one `list_entries` read.
633
  _migrate_env_odoo("boot")
634
  _pull_meta("boot")
 
635
  _rebuild_odoo_relational("boot")
636
  # ⭐⭐ W32-T07 — owner items 13 and 15, DELIVERED. See `_sweep_automation_schemas`.
637
  # ⚠ AFTER the two above and not before: those advance the mirror and can take minutes, and
@@ -716,6 +740,32 @@ def _pull_meta(why):
716
  return False
717
 
718
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
719
  def _rebuild_meta_relational(why, rt, previous_fingerprint=None, force_relations=False):
720
  """Spawn/refresh the `ut_meta_*` locked databases off the SAME mirror the Odoo half just used.
721
 
@@ -1386,6 +1436,7 @@ def _store_resync_loop():
1386
  # from being permanently absent.
1387
  # ⚠ Cheap when there is nothing to do: no token => one line and return.
1388
  _meta_pull_confirmed = _pull_meta("resync")
 
1389
  _meta_now = _t.time()
1390
  _meta_reason = _meta_rebuild_force_reason(
1391
  _meta_pull_confirmed, last_meta_fingerprint, last_meta_applied_at, _meta_now)
 
286
  return {"ok": True}
287
 
288
 
289
+ # W59-T43: boot stays available while a cross-lane module is absent, but never silently.
290
+ # verify_wiring.W59_PENDING_CROSS_LANE_HALVES owns the shrink-only declarations and rejects
291
+ # any failure outside them, including a missing dependency INSIDE a declared router.
292
+ ROUTER_MOUNT_FAILURES = {}
293
+
294
+
295
+ def _mount_router(module_name):
296
+ """Mount the module's own router/prefix and retain every failed boot attempt for checks."""
297
+ try:
298
+ from importlib import import_module
299
+ app.include_router(import_module(module_name).router)
300
+ return True
301
+ except Exception as exc: # Boot must answer even when a router cannot load.
302
+ failure = {"error": type(exc).__name__,
303
+ "missing_module": exc.name if isinstance(exc, ModuleNotFoundError) else ""}
304
+ ROUTER_MOUNT_FAILURES.setdefault(module_name, []).append(failure)
305
+ # Exception messages can contain configuration values; report the class/module only.
306
+ print(f"[aios-api] ROUTER MOUNT FAILED: {module_name}: {failure}; "
307
+ "routes unavailable; check W59_PENDING_CROSS_LANE_HALVES in verify_wiring.py")
308
+ return False
309
+
310
+
311
  app.include_router(routes_auth.router)
312
  app.include_router(routes_nav.router)
313
  app.include_router(routes_customers.router)
 
485
  # rate-limited by POLITENESS rather than by a bill (~1 req/s, and bulk harvesting is forbidden).
486
  app.include_router(routes_geo.router) # R14 / A11 — D's router, A's line (map providers)
487
  app.include_router(routes_external.router)
488
+ _mount_router("routes_security") # W59-T43: lane F declares the router; keep before static mount.
489
 
490
 
491
  # --- DEPRECATED ALIASES (removed when S2's shell flips; kept so the current bundle keeps working)
 
655
  # than in tomorrow's. It is idempotent, so every later boot is one `list_entries` read.
656
  _migrate_env_odoo("boot")
657
  _pull_meta("boot")
658
+ _pull_amazon("boot")
659
  _rebuild_odoo_relational("boot")
660
  # ⭐⭐ W32-T07 — owner items 13 and 15, DELIVERED. See `_sweep_automation_schemas`.
661
  # ⚠ AFTER the two above and not before: those advance the mirror and can take minutes, and
 
740
  return False
741
 
742
 
743
+ def _pull_amazon(why):
744
+ """Produce Amazon rows in this container before projecting them, on the caller's thread."""
745
+ try:
746
+ from harness import amazon_store as _amazon
747
+ from harness import runtime as _runtime
748
+ # The existing boot/resync projection targets tenant #0. Keep credential, mirror and
749
+ # projection on that same tenant; never fall back to an operator's environment credential.
750
+ tenant_key = "royal-imports"
751
+ rt = _runtime.get_runtime(tenant_key)
752
+ if not _amazon.credential(tenant_key, rt=rt):
753
+ print(f"[aios-api] amazon sync skipped ({why}): no stored amazon_sp credential "
754
+ "for royal-imports; the connector is idle, not broken")
755
+ return False
756
+ rep = _amazon.sync(tenant_key, rt=rt, scheduled=True,
757
+ log=lambda message: print(f"[aios-api] amazon sync ({why}): {message}"))
758
+ for problem in rep.get("problems") or []:
759
+ print(f"[aios-api] amazon sync PROBLEM ({why}): {problem}")
760
+ print(f"[aios-api] amazon sync done ({why}): " + ", ".join(
761
+ f"{table}={row.get('state', str(row.get('rows', 0)) + ' rows')}"
762
+ for table, row in rep["tables"].items()))
763
+ return not bool(rep.get("problems"))
764
+ except Exception as exc: # noqa: BLE001
765
+ print(f"[aios-api] amazon sync FAILED ({why}): {type(exc).__name__}: {exc}")
766
+ return False
767
+
768
+
769
  def _rebuild_meta_relational(why, rt, previous_fingerprint=None, force_relations=False):
770
  """Spawn/refresh the `ut_meta_*` locked databases off the SAME mirror the Odoo half just used.
771
 
 
1436
  # from being permanently absent.
1437
  # ⚠ Cheap when there is nothing to do: no token => one line and return.
1438
  _meta_pull_confirmed = _pull_meta("resync")
1439
+ _pull_amazon("resync")
1440
  _meta_now = _t.time()
1441
  _meta_reason = _meta_rebuild_force_reason(
1442
  _meta_pull_confirmed, last_meta_fingerprint, last_meta_applied_at, _meta_now)
api/odoo_relational.py CHANGED
@@ -2002,6 +2002,66 @@ def refresh_readable_model_catalog(rt, connection_id=None, client=None, force=Fa
2002
  return result
2003
 
2004
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2005
  # The population fact is deliberately separate from the readable-model catalogue. Measured on
2006
  # Royal Imports on 2026-09-08: discovery found 499 readable models in 22.62 s, then exact
2007
  # search_count calls took 67.87 s for 494 models at 137 ms per model; 239 held rows. A sampled
@@ -2143,7 +2203,7 @@ def population_census(rt, connection_id=None):
2143
  """The last census, from the tenant store. Reading it never contacts Odoo."""
2144
  empty = {"version": POPULATION_CENSUS_VERSION, "capturedAt": "", "complete": False,
2145
  "durationMs": 0, "counts": {}, "errors": [], "modelsCounted": 0,
2146
- "modelsWithRows": 0}
2147
  try:
2148
  cached = rt.get(POPULATION_CENSUS_KEY) if rt is not None else None
2149
  except Exception: # noqa: BLE001
@@ -2172,6 +2232,8 @@ def population_census(rt, connection_id=None):
2172
 
2173
  return {"version": POPULATION_CENSUS_VERSION,
2174
  "capturedAt": str(slot.get("capturedAt") or ""),
 
 
2175
  "complete": slot.get("complete") is True,
2176
  "durationMs": _nonnegative_int(slot.get("durationMs")),
2177
  "counts": counts,
@@ -2180,10 +2242,15 @@ def population_census(rt, connection_id=None):
2180
  "modelsWithRows": _nonnegative_int(slot.get("modelsWithRows"))}
2181
 
2182
 
2183
- def refresh_population_census(rt, connection_id=None, client=None, force=False):
2184
- """Count every readable model with read-only ``search_count`` and cache the result."""
 
 
 
 
2185
  current = population_census(rt, connection_id)
2186
- if current["capturedAt"] and not force:
 
2187
  return current
2188
 
2189
  # Start before possible discovery so durationMs is the wall clock the person waiting sees:
@@ -2208,10 +2275,16 @@ def refresh_population_census(rt, connection_id=None, client=None, force=False):
2208
  errors.append("catalogue: no complete readable model catalogue is available")
2209
 
2210
  def _count_all(bound_client):
 
 
 
 
2211
  for model in models:
2212
  try:
2213
- # search_count is the only Odoo operation in the census. It cannot mutate data.
2214
- counts[model] = int(bound_client.search_count(model, []))
 
 
2215
  except Exception as exc: # noqa: BLE001
2216
  errors.append(f"{model}: {type(exc).__name__}: {exc}")
2217
 
@@ -2233,6 +2306,7 @@ def refresh_population_census(rt, connection_id=None, client=None, force=False):
2233
  result = {
2234
  "version": POPULATION_CENSUS_VERSION,
2235
  "capturedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(),
 
2236
  "complete": catalogue.get("complete") is True and not errors
2237
  and len(counts) == len(models),
2238
  "durationMs": int((_time.monotonic() - started) * 1000),
@@ -3641,8 +3715,9 @@ def _model_field_specs(catalogue_row):
3641
 
3642
 
3643
  def publish_database_schema(rt, table_key, connection_id=None, username="automation", today=None):
3644
- """Publish one cached, permission-visible database definition without source calls or row work.
3645
 
 
3646
  Enable owns the choice and a durable sync job owns materialization. This seam only merges the
3647
  schema, so retrying it preserves existing rows, authored fields and the navigation rename.
3648
  """
@@ -3664,6 +3739,9 @@ def publish_database_schema(rt, table_key, connection_id=None, username="automat
3664
  raw = (_ut().odoo_schema_snapshot(rt).get("models") or {}).get(model)
3665
  if isinstance(raw, dict):
3666
  row = {"model": model, "fields": raw}
 
 
 
3667
  if not row or not row.get("fields"):
3668
  raise Refused("the field catalogue is unavailable for this database. Refresh the catalogue first.")
3669
  raw_fields = _model_field_specs(row)
 
2002
  return result
2003
 
2004
 
2005
+ def refresh_model_catalog_entry(rt, model, connection_id=None, client=None):
2006
+ """Refresh one model's fields with two read-only calls, without enumerating other models."""
2007
+ current = readable_model_catalog(rt, connection_id)
2008
+
2009
+ def _read_fields(bound_client):
2010
+ readable = bound_client.execute_kw(
2011
+ model, "check_access_rights", ["read"], {"raise_exception": False})
2012
+ if not bool(readable):
2013
+ return None
2014
+ fields = bound_client.fields_get(
2015
+ model, attributes=("string", "type", "required", "readonly", "relation"))
2016
+ clean_fields = {}
2017
+ for name, meta in (fields if isinstance(fields, dict) else {}).items():
2018
+ if not str(name).strip() or not isinstance(meta, dict):
2019
+ continue
2020
+ clean_fields[str(name)] = {k: meta.get(k) for k in
2021
+ ("string", "type", "required", "readonly", "relation")
2022
+ if k in meta}
2023
+ return clean_fields
2024
+
2025
+ try:
2026
+ if client is not None:
2027
+ fields = _read_fields(client)
2028
+ else:
2029
+ source = (rt.odoo_source() if connection_id is None
2030
+ else rt.odoo_source(connection_id))
2031
+ if source is None:
2032
+ return current
2033
+ from core.odoo import get_odoo
2034
+ with source._bound(): # tenant credential + scope
2035
+ fields = _read_fields(get_odoo())
2036
+ except Exception: # noqa: BLE001
2037
+ # No answer (including unavailable credentials) is not evidence of denied model access.
2038
+ return current
2039
+ if fields is None:
2040
+ raise Refused(f"This Odoo account cannot read the model {model}. "
2041
+ "Ask your Odoo administrator to grant read access in Odoo, not here.")
2042
+ slot = _catalog_slot(connection_id)
2043
+
2044
+ def _cache(current_cache):
2045
+ current_cache = dict(current_cache) if isinstance(current_cache, dict) else {}
2046
+ connections = dict(current_cache.get("connections") or {})
2047
+ result = dict(connections.get(slot) or current)
2048
+ rows = list(result.get("models") or ())
2049
+ previous = next((row for row in rows if row.get("model") == model), None)
2050
+ row = {"model": model,
2051
+ "name": " ".join(str((previous or {}).get("name") or model).split()),
2052
+ "fields": fields}
2053
+ result["models"] = [row if item.get("model") == model else item for item in rows]
2054
+ if previous is None:
2055
+ result["models"].append(row)
2056
+ # One model neither captures a whole catalogue nor changes its completeness. Preserve
2057
+ # complete and capturedAt exactly, along with every unrelated row and connection slot.
2058
+ connections[slot] = result
2059
+ return {"version": MODEL_CATALOG_VERSION, "connections": connections}
2060
+
2061
+ rt.update(MODEL_CATALOG_KEY, _cache, flush="sync")
2062
+ return readable_model_catalog(rt, connection_id)
2063
+
2064
+
2065
  # The population fact is deliberately separate from the readable-model catalogue. Measured on
2066
  # Royal Imports on 2026-09-08: discovery found 499 readable models in 22.62 s, then exact
2067
  # search_count calls took 67.87 s for 494 models at 137 ms per model; 239 held rows. A sampled
 
2203
  """The last census, from the tenant store. Reading it never contacts Odoo."""
2204
  empty = {"version": POPULATION_CENSUS_VERSION, "capturedAt": "", "complete": False,
2205
  "durationMs": 0, "counts": {}, "errors": [], "modelsCounted": 0,
2206
+ "modelsWithRows": 0, "mode": "unknown"}
2207
  try:
2208
  cached = rt.get(POPULATION_CENSUS_KEY) if rt is not None else None
2209
  except Exception: # noqa: BLE001
 
2232
 
2233
  return {"version": POPULATION_CENSUS_VERSION,
2234
  "capturedAt": str(slot.get("capturedAt") or ""),
2235
+ # Documents predating bounded counts were always exact.
2236
+ "mode": (slot.get("mode", "exact") if slot.get("capturedAt") else "unknown"),
2237
  "complete": slot.get("complete") is True,
2238
  "durationMs": _nonnegative_int(slot.get("durationMs")),
2239
  "counts": counts,
 
2242
  "modelsWithRows": _nonnegative_int(slot.get("modelsWithRows"))}
2243
 
2244
 
2245
+ def refresh_population_census(rt, connection_id=None, client=None, force=False, *, exact=False):
2246
+ """Cache model counts using at most 101 ids, or an explicitly requested exact count.
2247
+
2248
+ This limit bounds census work only; connected-source row readers remain uncapped.
2249
+ Clients without search retain the exact search_count path and record that fallback.
2250
+ """
2251
  current = population_census(rt, connection_id)
2252
+ mode = "exact" if exact else "bounded"
2253
+ if current["capturedAt"] and not force and current["mode"] == mode:
2254
  return current
2255
 
2256
  # Start before possible discovery so durationMs is the wall clock the person waiting sees:
 
2275
  errors.append("catalogue: no complete readable model catalogue is available")
2276
 
2277
  def _count_all(bound_client):
2278
+ nonlocal mode
2279
+ search = getattr(bound_client, "search", None) if not exact else None
2280
+ if not exact and not callable(search):
2281
+ mode = "exact_fallback"
2282
  for model in models:
2283
  try:
2284
+ # Both operations are reads. search_count has no limit argument in Odoo.
2285
+ counts[model] = (len(search(model, [], limit=101))
2286
+ if mode == "bounded"
2287
+ else int(bound_client.search_count(model, [])))
2288
  except Exception as exc: # noqa: BLE001
2289
  errors.append(f"{model}: {type(exc).__name__}: {exc}")
2290
 
 
2306
  result = {
2307
  "version": POPULATION_CENSUS_VERSION,
2308
  "capturedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(),
2309
+ "mode": mode,
2310
  "complete": catalogue.get("complete") is True and not errors
2311
  and len(counts) == len(models),
2312
  "durationMs": int((_time.monotonic() - started) * 1000),
 
3715
 
3716
 
3717
  def publish_database_schema(rt, table_key, connection_id=None, username="automation", today=None):
3718
+ """Publish one permission-visible database definition without row work.
3719
 
3720
+ Make at most two source calls on one model, on the miss path only.
3721
  Enable owns the choice and a durable sync job owns materialization. This seam only merges the
3722
  schema, so retrying it preserves existing rows, authored fields and the navigation rename.
3723
  """
 
3739
  raw = (_ut().odoo_schema_snapshot(rt).get("models") or {}).get(model)
3740
  if isinstance(raw, dict):
3741
  row = {"model": model, "fields": raw}
3742
+ if not row or not row.get("fields"):
3743
+ catalogue = refresh_model_catalog_entry(rt, model, connection_id=namespace)
3744
+ row = next((row for row in catalogue["models"] if row.get("model") == model), None)
3745
  if not row or not row.get("fields"):
3746
  raise Refused("the field catalogue is unavailable for this database. Refresh the catalogue first.")
3747
  raw_fields = _model_field_specs(row)
api/routes_auth.py CHANGED
@@ -7,15 +7,30 @@ replaces, and it is deliberately the same account store so the migration is a sw
7
  CREDENTIAL check, not of the user model.
8
  """
9
  import base64 as _b64
 
10
  import re as _re
11
 
12
  from fastapi import APIRouter, Body, Depends, Request, Response
13
 
14
  import aios_session
 
15
  from deps import Session, err, require_session, users, perms
16
 
17
  router = APIRouter(prefix="/api/v1/auth")
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  #: THE SERVER OWNS BACKOFF: the login page never paces itself. The budget lives in the shared
20
  #: tenant-0 auth store, not this process, so worker rotation or a deploy cannot buy ten more tries.
21
  #: Username and email aliases resolve to one canonical account key; only a SHA-256 digest of that
@@ -108,6 +123,11 @@ def set_avatar(body: dict = Body(default=None),
108
  users.set_avatar(session.uname, raw)
109
  u2 = dict(session.user)
110
  u2["avatar"] = raw
 
 
 
 
 
111
  return {"user": _public_user(u2)}
112
 
113
 
@@ -119,6 +139,11 @@ def clear_avatar(session: Session = Depends(require_session)):
119
  users.set_avatar(session.uname, None)
120
  u2 = dict(session.user)
121
  u2.pop("avatar", None)
 
 
 
 
 
122
  return {"user": _public_user(u2)}
123
 
124
 
@@ -148,6 +173,12 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
148
  throttle_key = None if user else _throttle_key(uname)
149
  wait = _throttled(throttle_key)
150
  if wait:
 
 
 
 
 
 
151
  raise err(429, "too_many_attempts",
152
  f"too many failed attempts. Try again in {wait} seconds")
153
  if not user:
@@ -162,6 +193,11 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
162
  except Exception:
163
  pass
164
  _note_failure(throttle_key)
 
 
 
 
 
165
  raise err(401, "invalid_credentials", "that username and password do not match")
166
 
167
  tenant = str(user.get("tenant") or "royal-imports").strip().lower()
@@ -170,6 +206,11 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
170
  runtime.get_runtime(tenant)
171
  except KeyError:
172
  _note_failure(throttle_key)
 
 
 
 
 
173
  raise err(401, "invalid_credentials", "that username and password do not match")
174
 
175
  # W57-T35 / C12: a correct credential may still need rotation. Check BEFORE bumping or
@@ -193,6 +234,7 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
193
 
194
  # W57-T36 / C12: every STORED account needs its second factor before any cookie is minted.
195
  # qa_runner is the sole exception and is double-gated out of live deployments.
 
196
  if not user.get("qa_runner"):
197
  try:
198
  rec = (users.registry() or {}).get(user["username"])
@@ -208,9 +250,15 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
208
  raise err(401, "mfa_required", "Enter the 6 digit code from your authenticator app.")
209
  # TOTP FIRST: redemption consumes a recovery code. Do not spend one when the app's
210
  # ordinary code already proves the factor, and never reset the guess budget on password.
211
- if not (users.totp_valid(rec.get("mfa_secret"), code)
212
- or users.consume_recovery_code(user["username"], code)):
 
 
213
  _note_failure(throttle_key)
 
 
 
 
214
  raise err(401, "mfa_invalid", _MFA_INVALID)
215
 
216
  # ⭐ WAVE 40, R2 — SINGLE SESSION, NEWEST WINS. Signing in here signs out every session this
@@ -236,11 +284,13 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
236
  # that security write is unavailable, authentication fails closed.
237
  _clear_failures(throttle_key)
238
  session_epoch = int(user.get("epoch") or 0)
 
239
  if not user.get("qa_runner"):
240
  try:
241
  bumped = users.bump_epoch(user["username"])
242
  if bumped is not None:
243
  session_epoch = int(bumped)
 
244
  except Exception as exc:
245
  print(f"[aios-api] login for {user['username']!r}: could not bump the session epoch "
246
  f"({type(exc).__name__}). This sign-in stands, but the account's previous "
@@ -261,6 +311,11 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
261
  import deps as _deps
262
  if not user.get("qa_runner"):
263
  _deps.note_active(user["username"])
 
 
 
 
 
264
  return {"user": _public_user(user)}
265
 
266
 
@@ -279,6 +334,12 @@ def _mfa_credentials(uname, password):
279
  throttle_key = _throttle_key(uname)
280
  wait = _throttled(throttle_key)
281
  if wait:
 
 
 
 
 
 
282
  raise err(429, "too_many_attempts",
283
  f"too many failed attempts. Try again in {wait} seconds")
284
  user = users.verify(uname, password) if (uname and password) else None
@@ -288,6 +349,11 @@ def _mfa_credentials(uname, password):
288
  except Exception:
289
  pass
290
  _note_failure(throttle_key)
 
 
 
 
 
291
  raise err(401, "invalid_credentials", "that username and password do not match")
292
  return user, throttle_key
293
 
@@ -311,6 +377,11 @@ def _mfa_session_tenant(user, rec, throttle_key):
311
  runtime.get_runtime(tenant)
312
  except KeyError:
313
  _note_failure(throttle_key)
 
 
 
 
 
314
  raise err(401, "invalid_credentials", "that username and password do not match")
315
  # Confirming a phone must not become a second login door that accepts an expired password.
316
  # Check before writing the factor, so the person can rotate and resume the same setup.
@@ -387,12 +458,20 @@ def mfa_enroll_confirm(request: Request, response: Response, body: dict = Body(d
387
  secret = str(body.get("secret") or "").strip().upper()
388
  if not users.totp_valid(secret, str(body.get("code") or "")):
389
  _note_failure(throttle_key)
 
 
 
 
390
  raise err(401, "mfa_invalid", _MFA_INVALID)
391
  tenant = _mfa_session_tenant(user, rec, throttle_key)
392
  codes = users.new_recovery_codes()
393
  # The store guard repeats the check atomically: two workers cannot issue two first sets.
394
  landed = _mfa_set(user, secret, codes, require_unenrolled=True)
395
  _mfa_session(request, response, user, rec, tenant, landed, throttle_key)
 
 
 
 
396
  return {"user": _public_user(user), "recoveryCodes": codes}
397
 
398
 
@@ -427,6 +506,71 @@ def mfa_recovery_codes(request: Request, response: Response, body: dict = Body(d
427
  codes = users.new_recovery_codes()
428
  landed = _mfa_set(user, rec["mfa_secret"], codes)
429
  _mfa_session(request, response, user, rec, tenant, landed, throttle_key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  return {"recoveryCodes": codes}
431
 
432
 
@@ -454,6 +598,12 @@ def change_password(body: dict = Body(default=None)):
454
  throttle_key = _throttle_key(uname)
455
  wait = _throttled(throttle_key)
456
  if wait:
 
 
 
 
 
 
457
  raise err(429, "too_many_attempts",
458
  f"too many failed attempts. Try again in {wait} seconds")
459
  user = users.verify(uname, pw) if (uname and pw) else None
@@ -463,6 +613,11 @@ def change_password(body: dict = Body(default=None)):
463
  except Exception:
464
  pass
465
  _note_failure(throttle_key)
 
 
 
 
 
466
  raise err(401, "invalid_credentials", "that username and password do not match")
467
  try:
468
  # verify accepts email addresses too. Rotate the RESOLVED registry key, never the typed
@@ -471,6 +626,12 @@ def change_password(body: dict = Body(default=None)):
471
  except users.PasswordPolicyError as exc:
472
  raise err(400, "weak_password", "That password does not meet the policy: " + str(exc))
473
  _clear_failures(throttle_key)
 
 
 
 
 
 
474
  return Response(status_code=204)
475
 
476
 
@@ -494,6 +655,21 @@ def logout(request: Request):
494
  """
495
  out = Response(status_code=204)
496
  aios_session.clear_cookie(out, request)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
  return out
498
 
499
 
 
7
  CREDENTIAL check, not of the user model.
8
  """
9
  import base64 as _b64
10
+ import hashlib as _hashlib
11
  import re as _re
12
 
13
  from fastapi import APIRouter, Body, Depends, Request, Response
14
 
15
  import aios_session
16
+ from core import audit
17
  from deps import Session, err, require_session, users, perms
18
 
19
  router = APIRouter(prefix="/api/v1/auth")
20
 
21
+ # GET /me, /mfa and /password-policy deliberately emit nothing: polling these reads would
22
+ # evict useful security history from the bounded document. Candidate MFA secrets are stateless;
23
+ # only their confirmation changes the account and earns an enrolled event.
24
+ # Each emit catches only AuditRefused at this HTTP boundary so a programming error is loud
25
+ # without breaking a production sign-in. audit.record itself owns best-effort store failures.
26
+ def _audit_unresolved(identifier):
27
+ """Never persist a typed login name: it might be a password pasted into the wrong box."""
28
+ # Deliberately NOT users' lockout namespace: these digests cannot be joined to that budget.
29
+ normalised = str(identifier or "").strip().lower()
30
+ return "digest:" + _hashlib.sha256(
31
+ ("aios-security-event-identity-v1\0" + normalised).encode("utf-8")).hexdigest()
32
+
33
+
34
  #: THE SERVER OWNS BACKOFF: the login page never paces itself. The budget lives in the shared
35
  #: tenant-0 auth store, not this process, so worker rotation or a deploy cannot buy ten more tries.
36
  #: Username and email aliases resolve to one canonical account key; only a SHA-256 digest of that
 
123
  users.set_avatar(session.uname, raw)
124
  u2 = dict(session.user)
125
  u2["avatar"] = raw
126
+ try:
127
+ audit.record("config.changed", session.tenant, session.user["username"],
128
+ {"setting": "avatar"})
129
+ except audit.AuditRefused as exc:
130
+ print(f"[aios-api] {exc}")
131
  return {"user": _public_user(u2)}
132
 
133
 
 
139
  users.set_avatar(session.uname, None)
140
  u2 = dict(session.user)
141
  u2.pop("avatar", None)
142
+ try:
143
+ audit.record("config.changed", session.tenant, session.user["username"],
144
+ {"setting": "avatar"})
145
+ except audit.AuditRefused as exc:
146
+ print(f"[aios-api] {exc}")
147
  return {"user": _public_user(u2)}
148
 
149
 
 
173
  throttle_key = None if user else _throttle_key(uname)
174
  wait = _throttled(throttle_key)
175
  if wait:
176
+ try:
177
+ # No account is proved at this point. "unknown" avoids inventing tenant attribution.
178
+ audit.record("auth.lockout", "unknown", _audit_unresolved(uname),
179
+ {"seconds_remaining": wait})
180
+ except audit.AuditRefused as exc:
181
+ print(f"[aios-api] {exc}")
182
  raise err(429, "too_many_attempts",
183
  f"too many failed attempts. Try again in {wait} seconds")
184
  if not user:
 
193
  except Exception:
194
  pass
195
  _note_failure(throttle_key)
196
+ try:
197
+ # A failed credential resolves no account or tenant; the raw identifier stays out.
198
+ audit.record("auth.login_failed", "unknown", _audit_unresolved(uname))
199
+ except audit.AuditRefused as exc:
200
+ print(f"[aios-api] {exc}")
201
  raise err(401, "invalid_credentials", "that username and password do not match")
202
 
203
  tenant = str(user.get("tenant") or "royal-imports").strip().lower()
 
206
  runtime.get_runtime(tenant)
207
  except KeyError:
208
  _note_failure(throttle_key)
209
+ try:
210
+ audit.record("auth.login_failed", tenant, user["username"],
211
+ {"reason": "tenant_unavailable"})
212
+ except audit.AuditRefused as exc:
213
+ print(f"[aios-api] {exc}")
214
  raise err(401, "invalid_credentials", "that username and password do not match")
215
 
216
  # W57-T35 / C12: a correct credential may still need rotation. Check BEFORE bumping or
 
234
 
235
  # W57-T36 / C12: every STORED account needs its second factor before any cookie is minted.
236
  # qa_runner is the sole exception and is double-gated out of live deployments.
237
+ recovery_code_used = False
238
  if not user.get("qa_runner"):
239
  try:
240
  rec = (users.registry() or {}).get(user["username"])
 
250
  raise err(401, "mfa_required", "Enter the 6 digit code from your authenticator app.")
251
  # TOTP FIRST: redemption consumes a recovery code. Do not spend one when the app's
252
  # ordinary code already proves the factor, and never reset the guess budget on password.
253
+ factor_valid = users.totp_valid(rec.get("mfa_secret"), code)
254
+ if not factor_valid:
255
+ recovery_code_used = users.consume_recovery_code(user["username"], code)
256
+ if not (factor_valid or recovery_code_used):
257
  _note_failure(throttle_key)
258
+ try:
259
+ audit.record("auth.mfa_failed", tenant, user["username"])
260
+ except audit.AuditRefused as exc:
261
+ print(f"[aios-api] {exc}")
262
  raise err(401, "mfa_invalid", _MFA_INVALID)
263
 
264
  # ⭐ WAVE 40, R2 — SINGLE SESSION, NEWEST WINS. Signing in here signs out every session this
 
284
  # that security write is unavailable, authentication fails closed.
285
  _clear_failures(throttle_key)
286
  session_epoch = int(user.get("epoch") or 0)
287
+ epoch_bumped = False
288
  if not user.get("qa_runner"):
289
  try:
290
  bumped = users.bump_epoch(user["username"])
291
  if bumped is not None:
292
  session_epoch = int(bumped)
293
+ epoch_bumped = True
294
  except Exception as exc:
295
  print(f"[aios-api] login for {user['username']!r}: could not bump the session epoch "
296
  f"({type(exc).__name__}). This sign-in stands, but the account's previous "
 
311
  import deps as _deps
312
  if not user.get("qa_runner"):
313
  _deps.note_active(user["username"])
314
+ try:
315
+ audit.record("auth.login", tenant, user["username"],
316
+ {"recovery_code_used": bool(recovery_code_used), "epoch_bumped": epoch_bumped})
317
+ except audit.AuditRefused as exc:
318
+ print(f"[aios-api] {exc}")
319
  return {"user": _public_user(user)}
320
 
321
 
 
334
  throttle_key = _throttle_key(uname)
335
  wait = _throttled(throttle_key)
336
  if wait:
337
+ try:
338
+ # Password proof has not resolved an account, so no tenant can be asserted.
339
+ audit.record("auth.lockout", "unknown", _audit_unresolved(uname),
340
+ {"seconds_remaining": wait})
341
+ except audit.AuditRefused as exc:
342
+ print(f"[aios-api] {exc}")
343
  raise err(429, "too_many_attempts",
344
  f"too many failed attempts. Try again in {wait} seconds")
345
  user = users.verify(uname, password) if (uname and password) else None
 
349
  except Exception:
350
  pass
351
  _note_failure(throttle_key)
352
+ try:
353
+ audit.record("auth.login_failed", "unknown", _audit_unresolved(uname),
354
+ {"door": "mfa"})
355
+ except audit.AuditRefused as exc:
356
+ print(f"[aios-api] {exc}")
357
  raise err(401, "invalid_credentials", "that username and password do not match")
358
  return user, throttle_key
359
 
 
377
  runtime.get_runtime(tenant)
378
  except KeyError:
379
  _note_failure(throttle_key)
380
+ try:
381
+ audit.record("auth.login_failed", tenant, user["username"],
382
+ {"door": "mfa", "reason": "tenant_unavailable"})
383
+ except audit.AuditRefused as exc:
384
+ print(f"[aios-api] {exc}")
385
  raise err(401, "invalid_credentials", "that username and password do not match")
386
  # Confirming a phone must not become a second login door that accepts an expired password.
387
  # Check before writing the factor, so the person can rotate and resume the same setup.
 
458
  secret = str(body.get("secret") or "").strip().upper()
459
  if not users.totp_valid(secret, str(body.get("code") or "")):
460
  _note_failure(throttle_key)
461
+ try:
462
+ audit.record("auth.mfa_failed", user["tenant"], user["username"], {"door": "enroll"})
463
+ except audit.AuditRefused as exc:
464
+ print(f"[aios-api] {exc}")
465
  raise err(401, "mfa_invalid", _MFA_INVALID)
466
  tenant = _mfa_session_tenant(user, rec, throttle_key)
467
  codes = users.new_recovery_codes()
468
  # The store guard repeats the check atomically: two workers cannot issue two first sets.
469
  landed = _mfa_set(user, secret, codes, require_unenrolled=True)
470
  _mfa_session(request, response, user, rec, tenant, landed, throttle_key)
471
+ try:
472
+ audit.record("auth.mfa_enrolled", tenant, user["username"], {"reason": "first"})
473
+ except audit.AuditRefused as exc:
474
+ print(f"[aios-api] {exc}")
475
  return {"user": _public_user(user), "recoveryCodes": codes}
476
 
477
 
 
506
  codes = users.new_recovery_codes()
507
  landed = _mfa_set(user, rec["mfa_secret"], codes)
508
  _mfa_session(request, response, user, rec, tenant, landed, throttle_key)
509
+ try:
510
+ # "credential" is itself a forbidden secret key; this label identifies the kind only.
511
+ audit.record("credential.rotated", tenant, user["username"],
512
+ {"credential_kind": "recovery_codes"})
513
+ except audit.AuditRefused as exc:
514
+ print(f"[aios-api] {exc}")
515
+ return {"recoveryCodes": codes}
516
+
517
+
518
+ @router.post("/mfa/device")
519
+ def mfa_device(response: Response, body: dict = Body(default=None),
520
+ session: Session = Depends(require_session)):
521
+ """Offer a replacement phone without removing the factor that admitted this session.
522
+
523
+ This is NOT the first-enrolment door: R1 still refuses an unenrolled login without a cookie.
524
+ A candidate is stateless and changes nothing until the new phone proves its first code.
525
+ """
526
+ # Refuse before any credential lookup: the synthetic runner must not read tenant #0.
527
+ if session.user.get("qa_runner"):
528
+ raise err(400, "no_stored_account", "That sign in cannot enrol a second factor.")
529
+ # The session supplies the identity. Body username/tenant fields can never choose a target.
530
+ user, _ = _mfa_credentials(session.uname, str((body or {}).get("password") or ""))
531
+ rec = _mfa_record(session.uname)
532
+ if not users.mfa_enrolled(rec):
533
+ raise err(409, "mfa_not_enrolled", "Sign in again to set up your authenticator app.")
534
+ secret = users.new_mfa_secret()
535
+ response.headers["Cache-Control"] = "no-store"
536
+ return {"secret": secret, "otpauthUri": users.otpauth_uri(secret, user["username"]),
537
+ "issuer": users.MFA_ISSUER, "digits": users.MFA_DIGITS, "period": users.MFA_PERIOD}
538
+
539
+
540
+ @router.post("/mfa/device/confirm")
541
+ def mfa_device_confirm(request: Request, response: Response, body: dict = Body(default=None),
542
+ session: Session = Depends(require_session)):
543
+ """Prove the CANDIDATE phone, replace the factor and revoke the account's other sessions.
544
+
545
+ Checking the installed secret would bless an unproved replacement. Requiring unenrolled
546
+ would refuse every legitimate caller. Re-mint from the landed epoch or this credential
547
+ change signs out its own caller; the replacement recovery codes are shown only once.
548
+ """
549
+ # Refuse before any credential lookup, even when the runner posts a wrong password.
550
+ if session.user.get("qa_runner"):
551
+ raise err(400, "no_stored_account", "That sign in cannot enrol a second factor.")
552
+ body = body or {}
553
+ # The session supplies the identity. Body username/tenant fields can never choose a target.
554
+ user, throttle_key = _mfa_credentials(session.uname, str(body.get("password") or ""))
555
+ rec = _mfa_record(session.uname)
556
+ if not users.mfa_enrolled(rec):
557
+ raise err(409, "mfa_not_enrolled", "Sign in again to set up your authenticator app.")
558
+ secret = str(body.get("secret") or "").strip().upper()
559
+ if not users.totp_valid(secret, str(body.get("code") or "")):
560
+ _note_failure(throttle_key)
561
+ try:
562
+ audit.record("auth.mfa_failed", user["tenant"], user["username"], {"door": "device"})
563
+ except audit.AuditRefused as exc:
564
+ print(f"[aios-api] {exc}")
565
+ raise err(401, "mfa_invalid", _MFA_INVALID)
566
+ tenant = _mfa_session_tenant(user, rec, throttle_key)
567
+ codes = users.new_recovery_codes()
568
+ landed = _mfa_set(user, secret, codes)
569
+ _mfa_session(request, response, user, rec, tenant, landed, throttle_key)
570
+ try:
571
+ audit.record("auth.mfa_enrolled", tenant, user["username"], {"reason": "device_change"})
572
+ except audit.AuditRefused as exc:
573
+ print(f"[aios-api] {exc}")
574
  return {"recoveryCodes": codes}
575
 
576
 
 
598
  throttle_key = _throttle_key(uname)
599
  wait = _throttled(throttle_key)
600
  if wait:
601
+ try:
602
+ # This unauthenticated door has no proved tenant either.
603
+ audit.record("auth.lockout", "unknown", _audit_unresolved(uname),
604
+ {"seconds_remaining": wait})
605
+ except audit.AuditRefused as exc:
606
+ print(f"[aios-api] {exc}")
607
  raise err(429, "too_many_attempts",
608
  f"too many failed attempts. Try again in {wait} seconds")
609
  user = users.verify(uname, pw) if (uname and pw) else None
 
613
  except Exception:
614
  pass
615
  _note_failure(throttle_key)
616
+ try:
617
+ audit.record("auth.login_failed", "unknown", _audit_unresolved(uname),
618
+ {"door": "password"})
619
+ except audit.AuditRefused as exc:
620
+ print(f"[aios-api] {exc}")
621
  raise err(401, "invalid_credentials", "that username and password do not match")
622
  try:
623
  # verify accepts email addresses too. Rotate the RESOLVED registry key, never the typed
 
626
  except users.PasswordPolicyError as exc:
627
  raise err(400, "weak_password", "That password does not meet the policy: " + str(exc))
628
  _clear_failures(throttle_key)
629
+ try:
630
+ # Use a descriptive label; C2 forbids the key "credential" even for non-secret values.
631
+ audit.record("credential.rotated", user["tenant"], user["username"],
632
+ {"credential_kind": "password"})
633
+ except audit.AuditRefused as exc:
634
+ print(f"[aios-api] {exc}")
635
  return Response(status_code=204)
636
 
637
 
 
655
  """
656
  out = Response(status_code=204)
657
  aios_session.clear_cookie(out, request)
658
+ # Only verified cookie claims can name an account here. These were minted from the resolved
659
+ # username; no new admission or store lookup is needed to clear an already-revoked session.
660
+ try:
661
+ claims = aios_session.read(request.cookies.get(aios_session.COOKIE_NAME))
662
+ except (TypeError, ValueError, OverflowError):
663
+ # A malformed signature (including non-ASCII bytes) must not prevent cookie clearing.
664
+ # Its parser exception could contain the cookie, so it never belongs in a log either.
665
+ claims = None
666
+ # Invalid/expired/absent cookies prove no tenant. Never use their raw bytes as attribution.
667
+ tenant = claims["t"] if claims else "unknown"
668
+ principal = claims["u"] if claims else _audit_unresolved("logout-without-identity")
669
+ try:
670
+ audit.record("auth.logout", tenant, principal)
671
+ except audit.AuditRefused as exc:
672
+ print(f"[aios-api] {exc}")
673
  return out
674
 
675
 
api/routes_connectors.py CHANGED
@@ -23,6 +23,7 @@ from __future__ import annotations
23
  import os
24
  import time
25
  import threading
 
26
 
27
  from fastapi import APIRouter, Body, Depends
28
 
@@ -36,6 +37,8 @@ from deps import Session, err, require_session
36
  #: connector is in.
37
  from core import connector_directory
38
  from core import connector_sync
 
 
39
  #: ⭐ W53-T27 / R9 / C2 — the label RESOLVER, imported rather than re-written. "Shipped default,
40
  #: per-tenant override, absent means inherit" is one idea and `core/schema_overlay.py` already
41
  #: owns it for fields; `merge_database_labels` is that idea for a database's own name. This module
@@ -76,6 +79,26 @@ from routes_monid import router as monid_router
76
  # same URL. `verify_api` now asserts the prefix on every mounted router instead.
77
  router = APIRouter(prefix="/api/v1")
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  #: The to-do list (R8). Order is the owner's reading order, not alphabetical: the things most
80
  #: likely to come next first. `queue` mirrors the standing provider queue in wave22-split C5-A2
81
  #: so the two cannot drift into disagreeing about what is coming.
@@ -650,7 +673,12 @@ def _entry_types(rt, uname=""):
650
  types, scopes = set(), {}
651
  for e in rows:
652
  t = str(e.get("type") or "")
653
- types.add(t)
 
 
 
 
 
654
  if scopes.get(t) != rk.DEFAULT_SCOPE:
655
  scopes[t] = str(e.get("scope") or rk.DEFAULT_SCOPE)
656
  return types, scopes, None
@@ -658,6 +686,26 @@ def _entry_types(rt, uname=""):
658
  return set(), {}, f"{type(e).__name__}: {e}"
659
 
660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  def directory(rt, uname, is_admin=False, incomplete=None):
662
  """The composed row set. Pure over the session, so the gate drives it without a request.
663
 
@@ -751,11 +799,21 @@ def directory(rt, uname, is_admin=False, incomplete=None):
751
 
752
  # --- Token connectors (R8): connectable today, and honest that data flows arrive later.
753
  def _tokens():
 
 
 
 
 
 
 
754
  for t in TOKEN_CONNECTORS:
755
  rows.append({
756
  "key": t["key"], "label": t["label"], "kind": "token", "desc": t["desc"],
757
  "hint": t["hint"],
758
- "state": "connected" if t["entry"] in have else "available",
 
 
 
759
  # ⭐ W32-T11 / C1 / R4 — the scope of the credential BEHIND this card, for THIS
760
  # reader. A token connector is the case R4 is really about: a member's own Stripe
761
  # key is theirs, and the card must say which kind of connection it is looking at.
@@ -893,6 +951,7 @@ def directory(rt, uname, is_admin=False, incomplete=None):
893
  # thing the toggle must never do is hide a connection the reader actually holds.
894
  for row in rows:
895
  row["allowedScopes"] = list(allowed_scopes(_entry_type_for(row.get("key"))))
 
896
  return rows
897
 
898
 
@@ -1067,6 +1126,9 @@ def connectors_directory(session: Session = Depends(require_session)):
1067
  # number of cards behind it by construction, and never a sum of endpoint counts (the ticket's
1068
  # trap; `chip_counts` carries the argument).
1069
  served = connector_directory.to_client_rows(rows)
 
 
 
1070
  return {"connectors": served,
1071
  "incomplete": incomplete,
1072
  # ⭐⭐ W53-T29 / OWNER RULING R6 — MAY THIS READER SEE THE COMPANY SIDE AT ALL.
@@ -1124,16 +1186,16 @@ def _sync_payload(connector_key, connection_id, row=None):
1124
  meta = connector_sync.providers()[connector_key]
1125
  slot = str(connection_id or "").strip() or "default"
1126
  if row is None:
1127
- return {"provider": connector_key, "label": meta["label"],
1128
  "connectionId": slot, "recorded": False, "state": None,
1129
  "at": None, "stateAt": None, "from": None,
1130
  "detail": "no sync has been recorded", "errors": [], "errorsTotal": 0,
1131
- "databases": [], "retryable": False, "retryHint": meta["retryHint"]}
1132
  answer = dict(row)
1133
  answer.update({"provider": connector_key, "connectionId": slot,
1134
  "label": meta["label"], "recorded": True,
1135
  "stateAt": row.get("at"), "retryHint": meta["retryHint"]})
1136
- return answer
1137
 
1138
 
1139
  def _odoo_sync_runner(session, connection_id):
@@ -1451,11 +1513,13 @@ def _schema_catalog_rt(rt, database_key=None, connection_id=None):
1451
  return []
1452
 
1453
 
1454
- def _odoo_field_key(rt, database_key, model, raw_name):
1455
- import odoo_relational
 
 
 
1456
  return connector_sync.field_key(
1457
- "odoo", odoo_relational.connection_for_table_key(database_key, rt),
1458
- database_key, model, raw_name)
1459
 
1460
 
1461
  @router.get("/connectors/odoo/status")
@@ -1554,8 +1618,8 @@ def connector_database_jobs(connector_key: str, session: Session = Depends(requi
1554
  _sync_admin(session)
1555
  if connector_key not in connector_sync.providers():
1556
  raise err(404, "sync_provider_unknown", "This connector has no database sync runner.")
1557
- return {"provider": connector_key, "jobs": connector_sync.jobs(
1558
- session.runtime, connector_key, connection_id)}
1559
 
1560
 
1561
  @router.get("/connectors/odoo/schema")
@@ -1582,17 +1646,20 @@ def odoo_schema(session: Session = Depends(require_session)):
1582
 
1583
 
1584
  @router.post("/connectors/odoo/census")
1585
- def odoo_population_census(session: Session = Depends(require_session)):
1586
- """Explicitly count every readable Odoo model; connector detail only reads this cache."""
1587
  _odoo_admin(session)
1588
  import odoo_relational
1589
- census = odoo_relational.refresh_population_census(session.runtime, force=True)
1590
  return {"capturedAt": str(census.get("capturedAt") or ""),
 
 
1591
  "complete": census.get("complete") is True,
1592
  "durationMs": int(census.get("durationMs") or 0),
1593
  "modelsCounted": int(census.get("modelsCounted") or 0),
1594
  "modelsWithRows": int(census.get("modelsWithRows") or 0),
1595
- "errors": [str(value) for value in (census.get("errors") or ())][:50]}
 
1596
 
1597
 
1598
  def _materialisation_failure_reason(result):
@@ -1611,6 +1678,9 @@ def _materialisation_failure_reason(result):
1611
  candidates.extend(errors if isinstance(errors, (list, tuple)) else (errors,))
1612
  reason = str(next((value for value in candidates if str(value or "").strip()), "")).strip()
1613
  # Provider errors can carry typographic punctuation. Screen strings use plain punctuation.
 
 
 
1614
  reason = reason.replace("\u2014", ",").replace("\u2013", "-")
1615
  return reason[:1].upper() + reason[1:] if reason else ""
1616
 
@@ -1707,11 +1777,6 @@ def _enable_odoo_database(table_key, session, connection_id=None):
1707
  return cur
1708
 
1709
  failure = None
1710
- try:
1711
- session.runtime.update(odoo_relational.CONFIG_KEY, _up, flush="sync")
1712
- except Exception: # noqa: BLE001
1713
- raise err(503, "store_unavailable", "the database setting was not saved. Try again.")
1714
-
1715
  try:
1716
  result = odoo_relational.publish_database_schema(
1717
  session.runtime, key, connection_id=namespace, username=session.uname)
@@ -1721,8 +1786,15 @@ def _enable_odoo_database(table_key, session, connection_id=None):
1721
  failure = (409, "odoo_database_refused", str(exc))
1722
  except Exception: # noqa: BLE001
1723
  failure = (500, "database_schema_failed",
1724
- "The setting was enabled, but the database was not created because the "
1725
- "field catalogue could not be published.")
 
 
 
 
 
 
 
1726
 
1727
  facts = (_rename_rights(session.runtime, session.uname, bool(session.admin), [key]).get(key)
1728
  or {"exists": False, "canRename": False})
@@ -1733,9 +1805,8 @@ def _enable_odoo_database(table_key, session, connection_id=None):
1733
  # `key`, `enabled` and the fresh facts BESIDE that key so the client could read them off a
1734
  # failure. Two shapes for one thing is what this module's own comments call the defect it has
1735
  # paid for twice, and a caller that learns to read a sibling off an error will keep doing it.
1736
- # The client does not need them: the FLAG is written before materialisation is attempted, so
1737
- # every outcome of this door can change what `/detail` answers, and `flipTable` therefore
1738
- # re-reads on both paths.
1739
  if failure is not None:
1740
  raise err(*failure)
1741
  if not exists:
@@ -1985,11 +2056,27 @@ def _entry_type_for(connector_key):
1985
  #: connector whose credential grows a field would take a client edit to become storable.
1986
  #: ⚠ `secret` decides the input type, so a field marked secret is typed into a password box and
1987
  #: never echoed back — the masked preview is the only form the stored value takes afterwards.
 
 
 
 
1988
  _CONNECT_FIELDS = {
1989
  "odoo": [{"key": "url", "label": "Server URL (https://...)", "secret": False},
1990
  {"key": "db", "label": "Database", "secret": False},
1991
  {"key": "user", "label": "API user", "secret": False},
1992
  {"key": "api_key", "label": "API key", "secret": True}],
 
 
 
 
 
 
 
 
 
 
 
 
1993
  }
1994
  #: Everything else is one pasted token. The field name is `api_key` because that is the first of
1995
  #: `core.keychain._PREVIEW_FIELDS`, so the stored entry gets a preview rather than a blank cell —
@@ -1997,6 +2084,14 @@ _CONNECT_FIELDS = {
1997
  _CONNECT_TOKEN_FIELD = [{"key": "api_key", "label": "API key", "secret": True}]
1998
 
1999
 
 
 
 
 
 
 
 
 
2000
  def _detail_connect(entry_type, is_admin):
2001
  """C4's `keychain.connect` half: what the Connect form must ask for, and what it may store.
2002
 
@@ -2010,7 +2105,7 @@ def _detail_connect(entry_type, is_admin):
2010
  """
2011
  if not entry_type:
2012
  return None
2013
- fields = _CONNECT_FIELDS.get(entry_type) or _CONNECT_TOKEN_FIELD
2014
  tenant_wide = entry_type in TENANT_WIDE_TYPES
2015
  return {"type": entry_type,
2016
  "fields": [dict(field) for field in fields],
@@ -2027,7 +2122,7 @@ def _replacement_field_specs(entry_type):
2027
 
2028
  This is deliberately a projection of the Connect descriptor rather than another provider
2029
  vocabulary. URL, database, account and every future non-secret field stay server-held during
2030
- replacement; only fields the existing descriptor marks secret cross this door.
2031
  """
2032
  spec = _detail_connect(entry_type, True) or {}
2033
  return [dict(field) for field in (spec.get("fields") or [])
@@ -2117,6 +2212,9 @@ def _detail_keychain(rt, uname, is_admin, row):
2117
  # a masked preview happened to be visible. The replacement endpoint changes
2118
  # this row's encrypted payload in place; no secret is added to this DTO.
2119
  "replaceable": can_replace,
 
 
 
2120
  })
2121
  except Exception: # noqa: BLE001
2122
  entries = []
@@ -2191,6 +2289,9 @@ def _connector_spec_items(connector_key):
2191
  except Exception: # noqa: BLE001
2192
  return ()
2193
  key = str(connector_key or "")
 
 
 
2194
  found = None
2195
  for name in ("tables_for", "for_connector", "tables", "spec", "spec_for"):
2196
  fn = getattr(connector_spec, name, None)
@@ -2427,14 +2528,34 @@ def _detail_databases(rt, is_admin, connector_key, uname="", connection_id=None)
2427
  except Exception: # noqa: BLE001
2428
  catalog = {}
2429
  enabled_fields = rt.get(_ODOO_SCHEMA_ENABLEMENTS) or {} if is_admin else {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2430
  out = []
2431
  for choice in choices:
2432
  key = str(choice.get("key") or "")
 
2433
  model = str(choice.get("model") or models.get(key) or "")
2434
  fields, excluded = catalog.get(model, ([], []))
2435
  scoped_fields = []
2436
  for field in fields:
2437
- field_key = _odoo_field_key(rt, key, model, field["source_field"])
 
2438
  scoped_fields.append({**field, "key": field_key,
2439
  "enabled": enabled_fields.get(field_key,
2440
  field.get("enabled") if namespace is None else False) is True})
@@ -2444,7 +2565,7 @@ def _detail_databases(rt, is_admin, connector_key, uname="", connection_id=None)
2444
  source_rows = counts.get(model) if census_at and model in counts else None
2445
  out.append({"key": key,
2446
  "identity": connector_sync.database_identity(
2447
- "odoo", odoo_relational.connection_for_table_key(key, rt), key, model),
2448
  "label": str(declared.get("label") or choice.get("label") or key),
2449
  "defaultLabel": str(declared.get("label") or choice.get("label") or key),
2450
  "native": str(declared.get("native") or model),
@@ -2728,7 +2849,9 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
2728
  Pure over the session for the same reason `directory` is: a gate can drive it without a
2729
  request, so the modal's payload is provable without a browser.
2730
  """
 
2731
  rows = directory(rt, uname, bool(is_admin))
 
2732
  key = str(connector_key or "")
2733
  row = next((candidate for candidate in rows
2734
  if str(candidate.get("key") or "") == key), None)
@@ -2737,27 +2860,37 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
2737
  graph = relationship_graphs(rows, user, rt, uname, bool(is_admin)).get(key) or _graph_refusal(
2738
  key, "No actual relationship graph was returned for this connection. A provider template "
2739
  "is not shown.")
 
2740
  # ⚠ `uname` REACHES THE DATABASES HALF NOW (W53-T27): `canRename` is `may_open`, which is a
2741
  # question about a PERSON and a table, not about an administrator flag alone.
2742
  databases = _detail_databases(rt, bool(is_admin), key, uname=str(uname or ""))
2743
- return {"overview": _detail_overview(row, databases, graph),
2744
- "keychain": _detail_keychain(rt, uname, bool(is_admin), row),
 
 
 
 
 
 
 
 
 
2745
  "databases": databases,
2746
  "materialization": ({"provider": key, "statusPath": f"/connectors/{key}/jobs",
2747
  "retryPath": f"/connectors/{key}/sync/retry"}
2748
  if is_admin and key in connector_sync.providers() else None),
2749
  # W55-T19 / R7 / C10 — a provider-specific capability. The client neither infers it
2750
  # from ``introspectable`` nor sends Amazon through Odoo's schema/config endpoints.
2751
- "enablement": _detail_enablement(rt, bool(is_admin), row),
2752
  # ⭐ W49-T14 / R24 — WHETHER THE DATABASES TAB MAY DISCLOSE ANYTHING AT ALL, and what
2753
  # THIS reader may do there. An addition to C4, declared on `_detail_introspection`:
2754
  # without it an empty `databases` list is "this connector has no schema" and "this
2755
  # connector's schema could not be read" at the same time.
2756
- "introspection": _detail_introspection(rt, bool(is_admin), row),
2757
  # ⛔ THE `relationship_graphs` SHAPE, UNCHANGED. C4 says so in as many words, and the
2758
  # client already has a reader for it (`parseRelationshipGraph`) that refuses a graph
2759
  # bound to another connection. A second shape here would need a second reader.
2760
- "relationships": graph}
2761
 
2762
 
2763
  def _set_amazon_database_enablement(database_key, body, session):
@@ -2818,8 +2951,9 @@ def connectors_detail(connector_key: str, session: Session = Depends(require_ses
2818
  workspace is connected to. What a member does NOT get is the tenant-wide credential door
2819
  (`canConnect` carries the card's own answer) or the administrator-only Odoo field catalogue.
2820
  """
2821
- detail = connector_detail(session.runtime, session.user, session.uname,
2822
- bool(session.admin), connector_key)
 
2823
  if detail is None:
2824
  raise err(404, "unknown_connector",
2825
  "this workspace has no connector with that key")
@@ -2856,14 +2990,18 @@ def _encrypted_replacement_payload(kc, label, entry_type, fields, username):
2856
  row = ((stage.bucket.get("entries") or {}).get(str(temporary.get("id") or "")) or {})
2857
  if not row.get("enc"):
2858
  raise RuntimeError("the keychain encryptor returned no encrypted payload")
2859
- return {"enc": str(row["enc"]), "preview": str(row.get("preview") or "")}
 
 
 
 
2860
 
2861
 
2862
  def _replace_connector_key(connector_key, entry_id, body, session):
2863
  """Replace only one connector entry's declared secrets while preserving its identity.
2864
 
2865
  The existing row remains untouched through validation, decryption, merge and encryption. The
2866
- final store update compares the complete old row before swapping only ``enc`` and ``preview``;
2867
  a concurrent rename or credential change therefore conflicts instead of being overwritten.
2868
  Scope and owner live in a separate bucket and are never written by this operation.
2869
  """
@@ -2895,15 +3033,16 @@ def _replace_connector_key(connector_key, entry_id, body, session):
2895
  raise err(404, "no_entry", "no such key for this connector")
2896
 
2897
  secret_specs = _replacement_field_specs(entry_type)
2898
- secret_keys = [str(field["key"]) for field in secret_specs]
 
2899
  request = body if isinstance(body, dict) else {}
2900
  supplied = request.get("fields")
2901
  if set(request) != {"fields"} or not isinstance(supplied, dict):
2902
  raise err(400, "bad_replacement",
2903
  "send only the connector's new secret fields")
2904
- if set(supplied) != set(secret_keys):
2905
  raise err(400, "bad_replacement",
2906
- "send every new secret field and no account or server settings")
2907
  replacements = {}
2908
  for field in secret_keys:
2909
  value = supplied.get(field)
@@ -2911,8 +3050,18 @@ def _replace_connector_key(connector_key, entry_id, body, session):
2911
  raise err(400, "bad_replacement", "a replacement secret cannot be blank")
2912
  replacements[field] = value.strip()
2913
 
 
 
 
 
 
 
 
2914
  try:
2915
  current_fields = kc.read_fields(session.runtime, entry_id)
 
 
 
2916
  except kc.KeychainLocked as exc:
2917
  raise err(503, "keychain_locked",
2918
  f"the keychain is locked: {exc}. Nothing was changed.")
@@ -2924,12 +3073,9 @@ def _replace_connector_key(connector_key, entry_id, body, session):
2924
  "the stored credential is incomplete. Nothing was changed.")
2925
 
2926
  merged_fields = {**current_fields, **replacements}
2927
- raw_bucket = session.runtime.get(kc.KEY) or {}
2928
- original = ((raw_bucket.get("entries") or {}).get(str(entry_id)))
2929
- if not isinstance(original, dict):
2930
- raise err(409, "credential_changed",
2931
- "the stored credential changed while replacement was prepared. Reload it.")
2932
- original = dict(original)
2933
  try:
2934
  encrypted = _encrypted_replacement_payload(
2935
  kc, entry.get("label"), entry_type, merged_fields, session.uname)
@@ -2948,10 +3094,10 @@ def _replace_connector_key(connector_key, entry_id, body, session):
2948
  if not isinstance(stored, dict) or stored != original:
2949
  raise _ReplacementConflict()
2950
  replacement = dict(stored)
2951
- replacement["enc"] = encrypted["enc"]
2952
- replacement["preview"] = encrypted["preview"]
2953
- entries[str(entry_id)] = replacement
2954
- return cur
2955
 
2956
  try:
2957
  session.runtime.update(kc.KEY, _swap, flush="sync")
 
23
  import os
24
  import time
25
  import threading
26
+ from datetime import datetime, timezone
27
 
28
  from fastapi import APIRouter, Body, Depends
29
 
 
37
  #: connector is in.
38
  from core import connector_directory
39
  from core import connector_sync
40
+ from core.keychain import AMAZON_ROTATION_DEADLINE_FIELD
41
+ from harness import amazon_client
42
  #: ⭐ W53-T27 / R9 / C2 — the label RESOLVER, imported rather than re-written. "Shipped default,
43
  #: per-tenant override, absent means inherit" is one idea and `core/schema_overlay.py` already
44
  #: owns it for fields; `merge_database_labels` is that idea for a database's own name. This module
 
79
  # same URL. `verify_api` now asserts the prefix on every mounted router instead.
80
  router = APIRouter(prefix="/api/v1")
81
 
82
+ CONNECTOR_DETAIL_DEADLINE_SECONDS = 30
83
+
84
+
85
+ # Measured reads take 1.34 s cold, 0.01 s warm, and above 8 s under boot contention.
86
+ # A thread pool deadline was tried and produced three consecutive 30 s 504s because
87
+ # core/store.py uses reentrant locks whose ownership does not survive a thread
88
+ # boundary while the request thread waits on the result. Keep the work on the
89
+ # request thread. This budget is therefore cooperative: it bounds a read whose
90
+ # phases are each finite and cannot interrupt a single call that is already wedged.
91
+ class _ConnectorDetailBudget:
92
+ def __init__(self):
93
+ self._started = time.monotonic()
94
+
95
+ def check(self):
96
+ if time.monotonic() - self._started >= CONNECTOR_DETAIL_DEADLINE_SECONDS:
97
+ raise err(504, "connector_detail_timeout",
98
+ f"The connector store did not answer within {CONNECTOR_DETAIL_DEADLINE_SECONDS} "
99
+ "seconds, so the read was stopped.")
100
+
101
+
102
  #: The to-do list (R8). Order is the owner's reading order, not alphabetical: the things most
103
  #: likely to come next first. `queue` mirrors the standing provider queue in wave22-split C5-A2
104
  #: so the two cannot drift into disagreeing about what is coming.
 
673
  types, scopes = set(), {}
674
  for e in rows:
675
  t = str(e.get("type") or "")
676
+ if t == "amazon_sp":
677
+ from core import keychain as kc
678
+ if kc.entry_verified(rt, e.get("id")):
679
+ types.add(t)
680
+ else:
681
+ types.add(t)
682
  if scopes.get(t) != rk.DEFAULT_SCOPE:
683
  scopes[t] = str(e.get("scope") or rk.DEFAULT_SCOPE)
684
  return types, scopes, None
 
686
  return set(), {}, f"{type(e).__name__}: {e}"
687
 
688
 
689
+ def _stored_amazon_rotation_deadline(rt, entry_id):
690
+ """Project only the public timestamp from the stored row, without decrypting a credential."""
691
+ from core import keychain as kc
692
+ stored = ((rt.get(kc.KEY) or {}).get("entries") or {}).get(str(entry_id)) or {}
693
+ if stored.get("type") != "amazon_sp":
694
+ return ""
695
+ deadline = stored.get(AMAZON_ROTATION_DEADLINE_FIELD)
696
+ return deadline if isinstance(deadline, str) else ""
697
+
698
+
699
+ def _amazon_rotation_expired(deadline):
700
+ if not deadline:
701
+ return False
702
+ try:
703
+ parsed = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
704
+ return parsed.tzinfo is not None and parsed <= datetime.now(timezone.utc)
705
+ except (TypeError, ValueError):
706
+ return False
707
+
708
+
709
  def directory(rt, uname, is_admin=False, incomplete=None):
710
  """The composed row set. Pure over the session, so the gate drives it without a request.
711
 
 
799
 
800
  # --- Token connectors (R8): connectable today, and honest that data flows arrive later.
801
  def _tokens():
802
+ amazon_expired = False
803
+ if "amazon_sp" in scopes:
804
+ import routes_keychain as rk
805
+ amazon_expired = any(
806
+ _amazon_rotation_expired(_stored_amazon_rotation_deadline(rt, entry.get("id")))
807
+ for entry in rk.visible_entries(rt, uname) or []
808
+ if entry.get("type") == "amazon_sp")
809
  for t in TOKEN_CONNECTORS:
810
  rows.append({
811
  "key": t["key"], "label": t["label"], "kind": "token", "desc": t["desc"],
812
  "hint": t["hint"],
813
+ "state": ("expired" if t["entry"] == "amazon_sp" and amazon_expired
814
+ else "connected" if t["entry"] in have else "reconnect"
815
+ if t["entry"] == "amazon_sp" and t["entry"] in scopes
816
+ else "available"),
817
  # ⭐ W32-T11 / C1 / R4 — the scope of the credential BEHIND this card, for THIS
818
  # reader. A token connector is the case R4 is really about: a member's own Stripe
819
  # key is theirs, and the card must say which kind of connection it is looking at.
 
951
  # thing the toggle must never do is hide a connection the reader actually holds.
952
  for row in rows:
953
  row["allowedScopes"] = list(allowed_scopes(_entry_type_for(row.get("key"))))
954
+ _safe_connector_status(row.get("key"), row)
955
  return rows
956
 
957
 
 
1126
  # number of cards behind it by construction, and never a sum of endpoint counts (the ticket's
1127
  # trap; `chip_counts` carries the argument).
1128
  served = connector_directory.to_client_rows(rows)
1129
+ for row in served:
1130
+ _safe_connector_status(row.get("key"), row)
1131
+ _safe_connector_status("amazon_sp", {"incomplete": incomplete})
1132
  return {"connectors": served,
1133
  "incomplete": incomplete,
1134
  # ⭐⭐ W53-T29 / OWNER RULING R6 — MAY THIS READER SEE THE COMPANY SIDE AT ALL.
 
1186
  meta = connector_sync.providers()[connector_key]
1187
  slot = str(connection_id or "").strip() or "default"
1188
  if row is None:
1189
+ return _safe_connector_status(connector_key, {"provider": connector_key, "label": meta["label"],
1190
  "connectionId": slot, "recorded": False, "state": None,
1191
  "at": None, "stateAt": None, "from": None,
1192
  "detail": "no sync has been recorded", "errors": [], "errorsTotal": 0,
1193
+ "databases": [], "retryable": False, "retryHint": meta["retryHint"]})
1194
  answer = dict(row)
1195
  answer.update({"provider": connector_key, "connectionId": slot,
1196
  "label": meta["label"], "recorded": True,
1197
  "stateAt": row.get("at"), "retryHint": meta["retryHint"]})
1198
+ return _safe_connector_status(connector_key, answer)
1199
 
1200
 
1201
  def _odoo_sync_runner(session, connection_id):
 
1513
  return []
1514
 
1515
 
1516
+ def _odoo_field_key(rt, database_key, model, raw_name, connection_id=...):
1517
+ # An explicitly resolved None must not trigger another lookup.
1518
+ if connection_id is ...:
1519
+ import odoo_relational
1520
+ connection_id = odoo_relational.connection_for_table_key(database_key, rt)
1521
  return connector_sync.field_key(
1522
+ "odoo", connection_id, database_key, model, raw_name)
 
1523
 
1524
 
1525
  @router.get("/connectors/odoo/status")
 
1618
  _sync_admin(session)
1619
  if connector_key not in connector_sync.providers():
1620
  raise err(404, "sync_provider_unknown", "This connector has no database sync runner.")
1621
+ return _safe_connector_status(connector_key, {"provider": connector_key, "jobs": connector_sync.jobs(
1622
+ session.runtime, connector_key, connection_id)})
1623
 
1624
 
1625
  @router.get("/connectors/odoo/schema")
 
1646
 
1647
 
1648
  @router.post("/connectors/odoo/census")
1649
+ def odoo_population_census(session: Session = Depends(require_session), exact: bool = False):
1650
+ """Count up to 101 ids per model by default; exact=true requests the full census."""
1651
  _odoo_admin(session)
1652
  import odoo_relational
1653
+ census = odoo_relational.refresh_population_census(session.runtime, force=True, exact=exact)
1654
  return {"capturedAt": str(census.get("capturedAt") or ""),
1655
+ "mode": census["mode"],
1656
+ "counts": census["counts"],
1657
  "complete": census.get("complete") is True,
1658
  "durationMs": int(census.get("durationMs") or 0),
1659
  "modelsCounted": int(census.get("modelsCounted") or 0),
1660
  "modelsWithRows": int(census.get("modelsWithRows") or 0),
1661
+ "errors": [str(value).replace("\u2014", ",").replace("\u2013", "-")
1662
+ for value in (census.get("errors") or ())][:50]}
1663
 
1664
 
1665
  def _materialisation_failure_reason(result):
 
1678
  candidates.extend(errors if isinstance(errors, (list, tuple)) else (errors,))
1679
  reason = str(next((value for value in candidates if str(value or "").strip()), "")).strip()
1680
  # Provider errors can carry typographic punctuation. Screen strings use plain punctuation.
1681
+ # ⛔ Standing rule 2 names the EM DASH and the EN DASH, never the ASCII hyphen. A blanket
1682
+ # strip of every Unicode dash category also breaks "read-only" and "e-commerce", so the
1683
+ # two characters the rule names are rewritten and nothing else is touched.
1684
  reason = reason.replace("\u2014", ",").replace("\u2013", "-")
1685
  return reason[:1].upper() + reason[1:] if reason else ""
1686
 
 
1777
  return cur
1778
 
1779
  failure = None
 
 
 
 
 
1780
  try:
1781
  result = odoo_relational.publish_database_schema(
1782
  session.runtime, key, connection_id=namespace, username=session.uname)
 
1786
  failure = (409, "odoo_database_refused", str(exc))
1787
  except Exception: # noqa: BLE001
1788
  failure = (500, "database_schema_failed",
1789
+ "The setting was not changed and the database was not created because the "
1790
+ "field catalogue could not be published. Refresh the catalogue and try again.")
1791
+
1792
+ # A refused publication must leave both the flag and its relock stamp untouched.
1793
+ if failure is None:
1794
+ try:
1795
+ session.runtime.update(odoo_relational.CONFIG_KEY, _up, flush="sync")
1796
+ except Exception: # noqa: BLE001
1797
+ raise err(503, "store_unavailable", "the database setting was not saved. Try again.")
1798
 
1799
  facts = (_rename_rights(session.runtime, session.uname, bool(session.admin), [key]).get(key)
1800
  or {"exists": False, "canRename": False})
 
1805
  # `key`, `enabled` and the fresh facts BESIDE that key so the client could read them off a
1806
  # failure. Two shapes for one thing is what this module's own comments call the defect it has
1807
  # paid for twice, and a caller that learns to read a sibling off an error will keep doing it.
1808
+ # The client re-reads `/detail` on both paths; publication precedes the flag write and row
1809
+ # materialisation remains separate work.
 
1810
  if failure is not None:
1811
  raise err(*failure)
1812
  if not exists:
 
2056
  #: connector whose credential grows a field would take a client edit to become storable.
2057
  #: ⚠ `secret` decides the input type, so a field marked secret is typed into a password box and
2058
  #: never echoed back — the masked preview is the only form the stored value takes afterwards.
2059
+ #: Sentence case with the initialism capitalised, which is what the rest of this app does.
2060
+ _AMAZON_FIELD_LABELS = {"client_id": "Client ID", "client_secret": "Client secret",
2061
+ "refresh_token": "Refresh token", "seller_id": "Seller ID",
2062
+ "marketplace_id": "Marketplace ID"}
2063
  _CONNECT_FIELDS = {
2064
  "odoo": [{"key": "url", "label": "Server URL (https://...)", "secret": False},
2065
  {"key": "db", "label": "Database", "secret": False},
2066
  {"key": "user", "label": "API user", "secret": False},
2067
  {"key": "api_key", "label": "API key", "secret": True}],
2068
+ # ⭐ THE KEYS AND THEIR ORDER ARE DERIVED, NEVER TYPED. `amazon_client.CREDENTIAL_FIELDS` is
2069
+ # the one roster, and lane G's `verify_amazon` asserts this sequence against it, so a field
2070
+ # added there appears here rather than drifting. Labels are the one thing NOT derived:
2071
+ # `"client_id".replace("_", " ").capitalize()` renders "Client id", and this app writes the
2072
+ # initialism. The map carries a derived fallback so a new credential field still renders.
2073
+ "amazon_sp": [
2074
+ {"key": key,
2075
+ "label": _AMAZON_FIELD_LABELS.get(key, key.replace("_", " ").capitalize()),
2076
+ "secret": key in ("client_secret", "refresh_token"),
2077
+ **({"default": amazon_client.US_MARKETPLACE_ID} if key == "marketplace_id" else {})}
2078
+ for key in amazon_client.CREDENTIAL_FIELDS
2079
+ ],
2080
  }
2081
  #: Everything else is one pasted token. The field name is `api_key` because that is the first of
2082
  #: `core.keychain._PREVIEW_FIELDS`, so the stored entry gets a preview rather than a blank cell —
 
2084
  _CONNECT_TOKEN_FIELD = [{"key": "api_key", "label": "API key", "secret": True}]
2085
 
2086
 
2087
+ def _safe_connector_status(connector_key, payload):
2088
+ """Apply the provider's disclosure guard at the status boundary, outside fallback catches."""
2089
+ if connector_key == "amazon_sp":
2090
+ import connectors_amazon as cx
2091
+ return cx.assert_safe_status(payload)
2092
+ return payload
2093
+
2094
+
2095
  def _detail_connect(entry_type, is_admin):
2096
  """C4's `keychain.connect` half: what the Connect form must ask for, and what it may store.
2097
 
 
2105
  """
2106
  if not entry_type:
2107
  return None
2108
+ fields = list(_CONNECT_FIELDS.get(entry_type) or _CONNECT_TOKEN_FIELD)
2109
  tenant_wide = entry_type in TENANT_WIDE_TYPES
2110
  return {"type": entry_type,
2111
  "fields": [dict(field) for field in fields],
 
2122
 
2123
  This is deliberately a projection of the Connect descriptor rather than another provider
2124
  vocabulary. URL, database, account and every future non-secret field stay server-held during
2125
+ replacement. Optional rotation metadata is accepted separately from this descriptor.
2126
  """
2127
  spec = _detail_connect(entry_type, True) or {}
2128
  return [dict(field) for field in (spec.get("fields") or [])
 
2212
  # a masked preview happened to be visible. The replacement endpoint changes
2213
  # this row's encrypted payload in place; no secret is added to this DTO.
2214
  "replaceable": can_replace,
2215
+ **({AMAZON_ROTATION_DEADLINE_FIELD:
2216
+ _stored_amazon_rotation_deadline(rt, entry.get("id"))}
2217
+ if entry_type == "amazon_sp" else {}),
2218
  })
2219
  except Exception: # noqa: BLE001
2220
  entries = []
 
2289
  except Exception: # noqa: BLE001
2290
  return ()
2291
  key = str(connector_key or "")
2292
+ # The directory uses the keychain type; the table registry uses the provider name.
2293
+ if key == "amazon_sp":
2294
+ key = "amazon"
2295
  found = None
2296
  for name in ("tables_for", "for_connector", "tables", "spec", "spec_for"):
2297
  fn = getattr(connector_spec, name, None)
 
2528
  except Exception: # noqa: BLE001
2529
  catalog = {}
2530
  enabled_fields = rt.get(_ODOO_SCHEMA_ENABLEMENTS) or {} if is_admin else {}
2531
+ # Connection resolution reaches keychain.list_entries and therefore the store (Postgres).
2532
+ # It ran 12,824 times for fields and database identities, then 501 with a per-key memo.
2533
+ # Resolve the shared default lazily once instead. This local belongs only to this detail
2534
+ # build: request scope keeps the answer per runtime and tenant, never process-wide.
2535
+ default_connection_id = ...
2536
+
2537
+ def resolve_connection_id(key):
2538
+ nonlocal default_connection_id
2539
+ base, cid = odoo_relational.split_table_key(key)
2540
+ if base is None:
2541
+ return None
2542
+ if cid:
2543
+ return cid
2544
+ if default_connection_id is ...:
2545
+ default_connection_id = (odoo_relational.default_connection_id(rt)
2546
+ or odoo_relational.DEFAULT_CONNECTION)
2547
+ return default_connection_id
2548
+
2549
  out = []
2550
  for choice in choices:
2551
  key = str(choice.get("key") or "")
2552
+ resolved_connection_id = resolve_connection_id(key)
2553
  model = str(choice.get("model") or models.get(key) or "")
2554
  fields, excluded = catalog.get(model, ([], []))
2555
  scoped_fields = []
2556
  for field in fields:
2557
+ field_key = _odoo_field_key(rt, key, model, field["source_field"],
2558
+ connection_id=resolved_connection_id)
2559
  scoped_fields.append({**field, "key": field_key,
2560
  "enabled": enabled_fields.get(field_key,
2561
  field.get("enabled") if namespace is None else False) is True})
 
2565
  source_rows = counts.get(model) if census_at and model in counts else None
2566
  out.append({"key": key,
2567
  "identity": connector_sync.database_identity(
2568
+ "odoo", resolved_connection_id, key, model),
2569
  "label": str(declared.get("label") or choice.get("label") or key),
2570
  "defaultLabel": str(declared.get("label") or choice.get("label") or key),
2571
  "native": str(declared.get("native") or model),
 
2849
  Pure over the session for the same reason `directory` is: a gate can drive it without a
2850
  request, so the modal's payload is provable without a browser.
2851
  """
2852
+ budget = _ConnectorDetailBudget()
2853
  rows = directory(rt, uname, bool(is_admin))
2854
+ budget.check()
2855
  key = str(connector_key or "")
2856
  row = next((candidate for candidate in rows
2857
  if str(candidate.get("key") or "") == key), None)
 
2860
  graph = relationship_graphs(rows, user, rt, uname, bool(is_admin)).get(key) or _graph_refusal(
2861
  key, "No actual relationship graph was returned for this connection. A provider template "
2862
  "is not shown.")
2863
+ budget.check()
2864
  # ⚠ `uname` REACHES THE DATABASES HALF NOW (W53-T27): `canRename` is `may_open`, which is a
2865
  # question about a PERSON and a table, not about an administrator flag alone.
2866
  databases = _detail_databases(rt, bool(is_admin), key, uname=str(uname or ""))
2867
+ budget.check()
2868
+ overview = _detail_overview(row, databases, graph)
2869
+ budget.check()
2870
+ keychain = _detail_keychain(rt, uname, bool(is_admin), row)
2871
+ budget.check()
2872
+ enablement = _detail_enablement(rt, bool(is_admin), row)
2873
+ budget.check()
2874
+ introspection = _detail_introspection(rt, bool(is_admin), row)
2875
+ budget.check()
2876
+ return _safe_connector_status(key, {"overview": overview,
2877
+ "keychain": keychain,
2878
  "databases": databases,
2879
  "materialization": ({"provider": key, "statusPath": f"/connectors/{key}/jobs",
2880
  "retryPath": f"/connectors/{key}/sync/retry"}
2881
  if is_admin and key in connector_sync.providers() else None),
2882
  # W55-T19 / R7 / C10 — a provider-specific capability. The client neither infers it
2883
  # from ``introspectable`` nor sends Amazon through Odoo's schema/config endpoints.
2884
+ "enablement": enablement,
2885
  # ⭐ W49-T14 / R24 — WHETHER THE DATABASES TAB MAY DISCLOSE ANYTHING AT ALL, and what
2886
  # THIS reader may do there. An addition to C4, declared on `_detail_introspection`:
2887
  # without it an empty `databases` list is "this connector has no schema" and "this
2888
  # connector's schema could not be read" at the same time.
2889
+ "introspection": introspection,
2890
  # ⛔ THE `relationship_graphs` SHAPE, UNCHANGED. C4 says so in as many words, and the
2891
  # client already has a reader for it (`parseRelationshipGraph`) that refuses a graph
2892
  # bound to another connection. A second shape here would need a second reader.
2893
+ "relationships": graph})
2894
 
2895
 
2896
  def _set_amazon_database_enablement(database_key, body, session):
 
2951
  workspace is connected to. What a member does NOT get is the tenant-wide credential door
2952
  (`canConnect` carries the card's own answer) or the administrator-only Odoo field catalogue.
2953
  """
2954
+ detail = connector_detail(
2955
+ session.runtime, session.user, session.uname,
2956
+ bool(session.admin), connector_key)
2957
  if detail is None:
2958
  raise err(404, "unknown_connector",
2959
  "this workspace has no connector with that key")
 
2990
  row = ((stage.bucket.get("entries") or {}).get(str(temporary.get("id") or "")) or {})
2991
  if not row.get("enc"):
2992
  raise RuntimeError("the keychain encryptor returned no encrypted payload")
2993
+ payload = {"enc": str(row["enc"]), "preview": str(row.get("preview") or ""),
2994
+ "envelope_version": row["envelope_version"]}
2995
+ if entry_type == "amazon_sp":
2996
+ payload[AMAZON_ROTATION_DEADLINE_FIELD] = row[AMAZON_ROTATION_DEADLINE_FIELD]
2997
+ return payload
2998
 
2999
 
3000
  def _replace_connector_key(connector_key, entry_id, body, session):
3001
  """Replace only one connector entry's declared secrets while preserving its identity.
3002
 
3003
  The existing row remains untouched through validation, decryption, merge and encryption. The
3004
+ final store update compares the complete old row before swapping the prepared envelope;
3005
  a concurrent rename or credential change therefore conflicts instead of being overwritten.
3006
  Scope and owner live in a separate bucket and are never written by this operation.
3007
  """
 
3033
  raise err(404, "no_entry", "no such key for this connector")
3034
 
3035
  secret_specs = _replacement_field_specs(entry_type)
3036
+ secret_keys = [str(field["key"]) for field in secret_specs if field.get("secret") is True]
3037
+ optional_keys = {AMAZON_ROTATION_DEADLINE_FIELD} if entry_type == "amazon_sp" else set()
3038
  request = body if isinstance(body, dict) else {}
3039
  supplied = request.get("fields")
3040
  if set(request) != {"fields"} or not isinstance(supplied, dict):
3041
  raise err(400, "bad_replacement",
3042
  "send only the connector's new secret fields")
3043
+ if not set(secret_keys) <= set(supplied) <= set(secret_keys) | optional_keys:
3044
  raise err(400, "bad_replacement",
3045
+ "send every new secret field, optional rotation metadata, and no account or server settings")
3046
  replacements = {}
3047
  for field in secret_keys:
3048
  value = supplied.get(field)
 
3050
  raise err(400, "bad_replacement", "a replacement secret cannot be blank")
3051
  replacements[field] = value.strip()
3052
 
3053
+ # Snapshot before decryption so a concurrent replacement cannot become our baseline later.
3054
+ from copy import deepcopy
3055
+ raw_bucket = session.runtime.get(kc.KEY) or {}
3056
+ original = deepcopy((raw_bucket.get("entries") or {}).get(str(entry_id)))
3057
+ if not isinstance(original, dict):
3058
+ raise err(409, "credential_changed",
3059
+ "the stored credential changed while replacement was prepared. Reload it.")
3060
  try:
3061
  current_fields = kc.read_fields(session.runtime, entry_id)
3062
+ except kc.KeychainEnvelopeVersionError:
3063
+ raise err(409, "credential_envelope_unsupported",
3064
+ "This credential uses an unsupported encryption envelope version. Nothing was changed.")
3065
  except kc.KeychainLocked as exc:
3066
  raise err(503, "keychain_locked",
3067
  f"the keychain is locked: {exc}. Nothing was changed.")
 
3073
  "the stored credential is incomplete. Nothing was changed.")
3074
 
3075
  merged_fields = {**current_fields, **replacements}
3076
+ if entry_type == "amazon_sp":
3077
+ # The previous secret's deadline does not describe its replacement. Absence is unknown.
3078
+ merged_fields[AMAZON_ROTATION_DEADLINE_FIELD] = supplied.get(AMAZON_ROTATION_DEADLINE_FIELD, "")
 
 
 
3079
  try:
3080
  encrypted = _encrypted_replacement_payload(
3081
  kc, entry.get("label"), entry_type, merged_fields, session.uname)
 
3094
  if not isinstance(stored, dict) or stored != original:
3095
  raise _ReplacementConflict()
3096
  replacement = dict(stored)
3097
+ replacement.update(encrypted)
3098
+ replacement.pop("probe", None)
3099
+ # Copy on write: a store failure after this callback must not mutate its cached old row.
3100
+ return {**cur, "entries": {**entries, str(entry_id): replacement}}
3101
 
3102
  try:
3103
  session.runtime.update(kc.KEY, _swap, flush="sync")
api/routes_security.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deployment posture read-back, not edge provisioning or an independent network probe.
2
+
3
+ Ingress observations describe this request and are reported against every mounted public
4
+ route. TLS termination hides the negotiated version from this process: HTTPS plus an
5
+ explicit minimum declaration is the limited evidence accepted here, only with bounded
6
+ proxy trust. No declaration substitutes for the four missing infrastructure producers.
7
+ """
8
+ from dataclasses import dataclass
9
+ from functools import cached_property
10
+ import ast
11
+ import hmac
12
+ import inspect
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import re
17
+ import time
18
+ from typing import Callable
19
+
20
+ from fastapi import APIRouter, Depends, Request, Response
21
+ from starlette.routing import Mount
22
+ from starlette.staticfiles import StaticFiles
23
+
24
+ import aios_session
25
+ from deps import Session, err
26
+ from core import audit
27
+ from routes_admin import admin_gate
28
+
29
+ router = APIRouter(prefix="/api/v1/security")
30
+ POSTURE_STATES = ("met", "not_met", "unknown")
31
+
32
+
33
+ def _answer(state, evidence):
34
+ return {"state": state, "evidence": evidence}
35
+
36
+
37
+ @dataclass
38
+ class Observation:
39
+ request: object
40
+ tenant: str
41
+
42
+ @cached_property
43
+ def security_events(self):
44
+ # One read per payload, never one read per route and never a process-wide cache.
45
+ if not audit.AUDIT_KINDS:
46
+ return _answer("not_met", "The audit module declares no security event kinds.")
47
+ try:
48
+ audit.read(self.tenant, limit=1)
49
+ except Exception:
50
+ # A store exception can carry secrets; neither its text nor its values escape.
51
+ return _answer("unknown", "The tenant security event document could not be read.")
52
+ return _answer("met", "The audit module declares event kinds and the tenant event document was read.")
53
+
54
+
55
+ def tls_min_version(observation, route):
56
+ """Read scheme plus declared minimum, never claim to observe negotiated TLS version.
57
+
58
+ Uvicorn owns forwarded-header validation. Reading the raw forwarded header ourselves
59
+ would bypass its peer check. An absent, empty or wildcard allow-list takes precedence
60
+ over scheme because even the apparent HTTPS scheme can then be client supplied.
61
+ """
62
+ allowed = os.environ.get("FORWARDED_ALLOW_IPS", "").strip()
63
+ if not allowed or "*" in allowed:
64
+ return _answer("unknown", "The forwarded scheme cannot be trusted under a wildcard allow-list, including an absent or empty declaration.")
65
+ scheme = getattr(getattr(observation.request, "url", None), "scheme", None)
66
+ if scheme in ("http", "ws"):
67
+ return _answer("not_met", "The request scheme reports plain HTTP without TLS.")
68
+ if scheme not in ("https", "wss"):
69
+ return _answer("unknown", "No HTTPS request scheme is available for the TLS control.")
70
+ declared = os.environ.get("AIOS_TLS_MIN_VERSION", "").strip()
71
+ if not re.fullmatch(r"[0-9]+\.[0-9]+", declared):
72
+ return _answer("unknown", "The request reports HTTPS but the minimum TLS version declaration is absent or unrecognised.")
73
+ # Compare integer components, not a float (a minor version need not be one digit).
74
+ minimum = tuple(int(part) for part in declared.split("."))
75
+ if minimum < (1, 2):
76
+ return _answer("not_met", "The declared minimum TLS version is below the required minimum.")
77
+ return _answer("met", "The request reports HTTPS with bounded proxy trust and a declared TLS minimum of at least 1.2; the negotiated version is not observable.")
78
+
79
+
80
+ def origin_bypass_prevented(observation, route):
81
+ declared = os.environ.get("AIOS_ORIGIN_TOKEN", "")
82
+ if not declared.strip():
83
+ return _answer("unknown", "No shared origin token is declared for the origin control.")
84
+ headers = getattr(observation.request, "headers", {})
85
+ supplied = headers.get("x-aios-origin-token", "")
86
+ if not supplied or not hmac.compare_digest(supplied.encode("utf-8"), declared.encode("utf-8")):
87
+ return _answer("not_met", "The request did not carry the declared shared origin token.")
88
+ return _answer("met", "The request carried the declared shared origin token; this is request ingress evidence.")
89
+
90
+
91
+ def waf_in_path(observation, route):
92
+ return _answer("unknown", "A WAF association and request inspection read-back producer is required.")
93
+
94
+
95
+ def firewall_acl(observation, route):
96
+ return _answer("unknown", "A firewall or ACL rule read-back producer for the serving network is required.")
97
+
98
+
99
+ def network_segmentation(observation, route):
100
+ return _answer("unknown", "A network topology and isolation rule read-back producer is required.")
101
+
102
+
103
+ def intrusion_detection_monitored(observation, route):
104
+ return _answer("unknown", "A detection service and active monitoring read-back producer is required.")
105
+
106
+
107
+ def security_events_written(observation, route):
108
+ return observation.security_events
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class Control:
113
+ id: str
114
+ label: str
115
+ producer: Callable
116
+
117
+
118
+ # The module-level seam is injectable without a server, live store or network.
119
+ CONTROL_ROSTER = (
120
+ Control("tls_min_version", "TLS minimum", tls_min_version),
121
+ Control("waf_in_path", "Web application firewall", waf_in_path),
122
+ Control("origin_bypass_prevented", "Origin protection", origin_bypass_prevented),
123
+ Control("firewall_acl", "Firewall rules", firewall_acl),
124
+ Control("network_segmentation", "Network segmentation", network_segmentation),
125
+ Control("intrusion_detection_monitored", "Intrusion monitoring", intrusion_detection_monitored),
126
+ Control("security_events_written", "Security events", security_events_written),
127
+ )
128
+ _CONTROL_IDS = tuple(control.id for control in CONTROL_ROSTER)
129
+
130
+
131
+ def internet_routes(app):
132
+ """Walk original_router recursively, as verify_api._mounted_paths does.
133
+
134
+ Also include direct app routes and mounted apps. FastAPI's include_context carries
135
+ the actual include prefix; the nested router's own prefix is already in its leaf
136
+ paths. Exclude only StaticFiles mounts and the GET/HEAD /api/health liveness route.
137
+ Opaque mounts and routes of uncertain exposure remain in the inventory.
138
+ """
139
+ paths = []
140
+
141
+ def walk(owner, base):
142
+ for route in getattr(owner, "routes", ()):
143
+ nested = getattr(route, "original_router", None)
144
+ if nested is not None:
145
+ context = getattr(route, "include_context", None)
146
+ walk(nested, base + getattr(context, "prefix", ""))
147
+ continue
148
+ path = base + (getattr(route, "path", None) or "")
149
+ if isinstance(route, Mount):
150
+ if isinstance(route.app, StaticFiles):
151
+ continue
152
+ if getattr(route.app, "routes", None):
153
+ walk(route.app, path)
154
+ continue
155
+ path += "/{path:path}"
156
+ methods = sorted(getattr(route, "methods", None) or (
157
+ ["WEBSOCKET"] if "WebSocket" in type(route).__name__ else ["UNKNOWN"]))
158
+ if path == "/api/health" and set(methods) <= {"GET", "HEAD"}:
159
+ continue
160
+ paths.append({"path": path or "/{path:path}", "methods": methods})
161
+
162
+ walk(app, "")
163
+ return paths
164
+
165
+
166
+ def posture_allowed(controls):
167
+ """Unknown, malformed, missing and duplicate controls all refuse the roll-up."""
168
+ return (len(controls) == len(_CONTROL_IDS)
169
+ and {control["id"] for control in controls} == set(_CONTROL_IDS)
170
+ and all(control.get("state") == "met" for control in controls))
171
+
172
+
173
+ def build_posture(request, tenant):
174
+ observation = Observation(request, tenant)
175
+ routes = []
176
+ for route in internet_routes(getattr(request, "app", None)):
177
+ controls = []
178
+ for control in CONTROL_ROSTER:
179
+ try:
180
+ answer = control.producer(observation, route)
181
+ if answer["state"] not in POSTURE_STATES:
182
+ raise ValueError("Unrecognised posture state")
183
+ # Producers return fixed source descriptions, never raw headers or env values.
184
+ audit._string("evidence", answer["evidence"])
185
+ except Exception:
186
+ answer = _answer("unknown", "The control producer did not return usable read-back evidence.")
187
+ controls.append({"id": control.id, "label": control.label,
188
+ "state": answer["state"], "evidence": answer["evidence"]})
189
+ routes.append({**route, "controls": controls, "allowed": posture_allowed(controls)})
190
+ failing = [key for key in _CONTROL_IDS if not routes or any(
191
+ not any(c["id"] == key and c["state"] == "met" for c in route["controls"])
192
+ for route in routes)]
193
+ return {"routes": routes, "allowed": bool(routes) and all(r["allowed"] for r in routes),
194
+ "failing_control_ids": failing,
195
+ "evidence_scope": "Ingress evidence describes this request, not separate probes of every route.",
196
+ "route_evidence": ("The application route tree was read at request time." if routes else
197
+ "No internet-facing route inventory is available; enablement is refused.")}
198
+
199
+
200
+ def _principal(request, tenant):
201
+ if request is None:
202
+ return "system:amazon-posture"
203
+ try:
204
+ claims = aios_session.read(request.cookies.get(aios_session.COOKIE_NAME))
205
+ except (TypeError, ValueError, OverflowError):
206
+ claims = None
207
+ if claims and claims["t"] == tenant:
208
+ return claims["u"]
209
+ return "unresolved:amazon-posture"
210
+
211
+
212
+ def require_amazon_posture(request, tenant) -> None:
213
+ """503 means a deployment precondition is unmet, not bad caller input.
214
+
215
+ Enablement callers must authenticate first. Boot sync may pass request=None, which
216
+ refuses because there is no request ingress or route evidence; never fabricate either.
217
+ Only refused attempts emit an event. The audit writer owns store failures, and only
218
+ AuditRefused is caught here, matching routes_auth's boundary convention.
219
+ """
220
+ posture = build_posture(request, tenant)
221
+ if posture["allowed"]:
222
+ return None
223
+ failing = posture["failing_control_ids"] or list(_CONTROL_IDS)
224
+ try:
225
+ audit.record("config.changed", tenant, _principal(request, tenant),
226
+ {"setting": "amazon_enablement", "allowed": False,
227
+ "failing_controls": ", ".join(failing)})
228
+ except audit.AuditRefused as exc:
229
+ print(f"[aios-api] {exc}")
230
+ raise err(503, "amazon_posture_unmet",
231
+ "Amazon enablement refused: unmet deployment controls: " + ", ".join(failing) + ".")
232
+
233
+
234
+ @router.get("/posture")
235
+ def security_posture(request: Request, session: Session = Depends(admin_gate)):
236
+ return build_posture(request, session.tenant)
237
+
238
+
239
+ COMPLIANCE_STATES = {"met": "Met", "not_met": "Not met", "unproven": "Unproven"}
240
+ _APPROVED_ROLES = (
241
+ ("role-inventory", "Inventory and Order Tracking"),
242
+ ("role-fulfillment", "Amazon Fulfillment"),
243
+ ("role-awd", "Amazon Warehousing and Distribution"),
244
+ ("role-finance", "Finance and Accounting"),
245
+ ("role-pricing", "Pricing"),
246
+ ("role-listing", "Product Listing"),
247
+ ("role-analytics", "Brand Analytics"),
248
+ ("role-insights", "Selling Partner Insights"),
249
+ )
250
+ # RD10 is deliberately unavailable until production access and QI13 verification exist.
251
+ # These are the six CREDENTIAL_RED labels, not imports of a verification executable.
252
+ _PRODUCTION_CHECKS = (
253
+ ("production-stored", "[live] a stored amazon_sp credential resolves for tenant #0"),
254
+ ("production-authentication", "[live] the credential authenticates against marketplaceParticipations"),
255
+ ("production-sync", "[live] every declared table has synced at least once"),
256
+ ("production-roles", "[live] Pricing and AWD role operations completed without refusal"),
257
+ ("production-reconciliation", "[live] validate reconciles each table to Amazon's own summary"),
258
+ ("production-brand", "[live] brand_analytics returns rows for a registered brand (R5's exit condition)"),
259
+ )
260
+
261
+
262
+ def _compliance_read(producer, missing):
263
+ try:
264
+ return producer()
265
+ except audit.AuditRefused:
266
+ # A secret-shaped result refuses the response; it must never become a redacted claim.
267
+ raise
268
+ except Exception:
269
+ # Exception text may contain a connection string or a credential value.
270
+ return _answer("unproven", missing)
271
+
272
+
273
+ def _authentication_control():
274
+ from core import users
275
+ from routes_auth import login
276
+
277
+ policy = (users.PASSWORD_MIN_LENGTH, users.PASSWORD_HISTORY,
278
+ users.PASSWORD_MIN_AGE_DAYS, users.PASSWORD_MAX_AGE_DAYS)
279
+ rules = {rule["rule"] for rule in users.password_rules()}
280
+ function = ast.parse(inspect.getsource(login)).body[0]
281
+ parents = {child: node for node in ast.walk(function) for child in ast.iter_child_nodes(node)}
282
+ # T33's scope predicate: extra role guards, else arms and early cookie mints cannot pass.
283
+ expected = {"users.totp_valid": ["not user.get('qa_runner')"],
284
+ "users.consume_recovery_code": ["not user.get('qa_runner')", "not factor_valid"]}
285
+ factors = []
286
+ covered = True
287
+ for name, guards in expected.items():
288
+ calls = [node for node in ast.walk(function)
289
+ if isinstance(node, ast.Call) and ast.unparse(node.func) == name]
290
+ if len(calls) != 1:
291
+ covered = False
292
+ continue
293
+ factors.extend(calls)
294
+ ancestors, node = [], calls[0]
295
+ while node in parents:
296
+ parent = parents[node]
297
+ if isinstance(parent, ast.If):
298
+ covered = covered and node in parent.body
299
+ ancestors.insert(0, ast.unparse(parent.test))
300
+ node = parent
301
+ covered = covered and ancestors == guards
302
+ first = min((node.lineno for node in factors), default=0)
303
+ covered = covered and not any(getattr(node, "lineno", 0) < first and (
304
+ isinstance(node, ast.Return) or isinstance(node, ast.Call)
305
+ and ast.unparse(node.func) in {"aios_session.mint", "aios_session.set_cookie"})
306
+ for node in ast.walk(function))
307
+ refusals = {ast.unparse(node.test): node for node in ast.walk(function)
308
+ if isinstance(node, ast.If)}
309
+ for guard, code in (("not users.mfa_enrolled(rec)", "mfa_enrolment_required"),
310
+ ("not code", "mfa_required"),
311
+ ("not (factor_valid or recovery_code_used)", "mfa_invalid")):
312
+ block = refusals.get(guard)
313
+ covered = covered and block is not None and any(
314
+ isinstance(node, ast.Raise) and any(isinstance(value, ast.Constant) and value.value == code
315
+ for value in ast.walk(node))
316
+ for node in ast.walk(block))
317
+ met = (policy == (12, 10, 1, 90) and covered and
318
+ rules >= {"length", "uppercase", "lowercase", "digit", "symbol", "identifier"})
319
+ return _answer("met" if met else "not_met", (
320
+ "Runtime policy reads 12 characters, ten prior passwords and 1/90 day age limits; the inspected login block requires a factor for stored accounts with a QA identity exception."
321
+ if met else "The runtime password policy or inspected login factor block does not match the authentication baseline."))
322
+
323
+
324
+ def _telemetry_control(tenant):
325
+ audit.read(tenant, limit=1)
326
+ return _answer("met", "The tenant audit document was read through the security event reader; event contents are excluded.")
327
+
328
+
329
+ def _role_control(role):
330
+ from harness.amazon_client import ROLES_TAKEN
331
+
332
+ for name in ROLES_TAKEN:
333
+ audit._string("role", name)
334
+ exact = (len(ROLES_TAKEN) == len(_APPROVED_ROLES)
335
+ and set(ROLES_TAKEN) == {name for _, name in _APPROVED_ROLES})
336
+ if role not in ROLES_TAKEN:
337
+ return _answer("not_met", "The live connector role allow-list does not include this approved role.")
338
+ if not exact:
339
+ return _answer("not_met", "The live connector role allow-list differs from the eight approved roles.")
340
+ return _answer("met", "The live connector role allow-list includes this role; production authorization is unavailable.")
341
+
342
+
343
+ def _audit_retention_control(tenant):
344
+ seconds = audit.RETENTION_SECONDS
345
+ if type(seconds) is not int or seconds <= 0:
346
+ return _answer("not_met", "The audit reader has no positive retention interval.")
347
+ audit.read(tenant, limit=1)
348
+ return _answer("met", f"The live audit reader filters events older than {seconds} seconds; stored events are pruned on writes, not by an Amazon data retention job.")
349
+
350
+
351
+ def _vulnerability_control():
352
+ # T35 writes an npm dependency inventory, which is not a vulnerability scan result.
353
+ with Path("/deps/web-deps.json").open(encoding="utf-8") as handle:
354
+ inventory = json.load(handle)
355
+ if not isinstance(inventory, dict) or not isinstance(inventory.get("dependencies"), dict):
356
+ return _answer("unproven", "The dependency inventory is unreadable as an inventory and no current vulnerability scan producer is available.")
357
+ return _answer("unproven", "The dependency inventory was read, but no current vulnerability scan producer is available.")
358
+
359
+
360
+ def _posture_compliance_control(posture, control_id):
361
+ routes = posture["routes"]
362
+ answers = [next(control for control in route["controls"] if control["id"] == control_id)
363
+ for route in routes]
364
+ if not answers:
365
+ return _answer("unproven", "No request-time internet route inventory is available for this control.")
366
+ # Keep every child row; an unknown child prevents a green category roll-up.
367
+ states = {answer["state"] for answer in answers}
368
+ state = "unproven" if "unknown" in states else "not_met" if "not_met" in states else "met"
369
+ if not states <= set(POSTURE_STATES):
370
+ raise ValueError("Unrecognised posture state")
371
+ if state == "met" and control_id in posture["failing_control_ids"]:
372
+ return _answer("unproven", "The posture roll-up and route control observations disagree.")
373
+ target = "unknown" if state == "unproven" else state
374
+ evidence = next(answer["evidence"] for answer in answers if answer["state"] == target)
375
+ return _answer(state, evidence)
376
+
377
+
378
+ def read_compliance_controls(request, tenant):
379
+ """Live observations only, with one posture read and isolated producer failures."""
380
+ observations = {
381
+ "q1": _compliance_read(_authentication_control, "The runtime password policy or login factor block could not be read."),
382
+ "q5": _compliance_read(lambda: _telemetry_control(tenant), "The tenant audit document could not be read."),
383
+ "retention-audit": _compliance_read(lambda: _audit_retention_control(tenant), "The audit retention interval or tenant audit document could not be read."),
384
+ "vulnerability": _compliance_read(_vulnerability_control, "The dependency inventory at /deps/web-deps.json could not be read and no current vulnerability scan producer is available."),
385
+ }
386
+ posture = _compliance_read(lambda: build_posture(request, tenant), "The deployment posture could not be read.")
387
+ for control in CONTROL_ROSTER:
388
+ observations["posture-" + control.id] = _compliance_read(
389
+ lambda key=control.id: _posture_compliance_control(posture, key),
390
+ "The request-time posture observation for this control could not be read.")
391
+ for key, role in _APPROVED_ROLES:
392
+ observations[key] = _compliance_read(lambda name=role: _role_control(name),
393
+ "The live connector role allow-list could not be read.")
394
+ return observations
395
+
396
+
397
+ def _check_compliance_strings(claims):
398
+ for claim in claims:
399
+ for key, value in claim.items():
400
+ if isinstance(value, str):
401
+ audit._string("compliance field", value)
402
+ if chr(0x2014) in value or chr(0x2013) in value or "\n" in value or "\r" in value:
403
+ raise audit.AuditRefused("compliance field", "unsupported prose or line break")
404
+ if claim["state"] not in COMPLIANCE_STATES:
405
+ raise ValueError("Unrecognised compliance state")
406
+
407
+
408
+ def compliance_roster(observations):
409
+ """Pure roster assembly; absent observations never default to affirmative evidence."""
410
+ claims = []
411
+
412
+ def add(key, group, claim, source=None, missing="No producing control is available.", answer=None):
413
+ observed = answer if answer is not None else observations.get(key) if source is not None else None
414
+ observed = observed if observed is not None else _answer("unproven", missing)
415
+ evidence = observed["evidence"]
416
+ if group == "Question predicates":
417
+ evidence = evidence.removesuffix(".") + f"; verbatim {key.upper()} text is unavailable to this deployment."
418
+ claims.append({"id": key, "group": group, "claim": claim,
419
+ "state": observed["state"], "evidence": evidence, "source": source})
420
+
421
+ add("q1", "Question predicates", "Q1: Authentication and MFA", "aios-web/api/routes_auth.py:login",
422
+ "The runtime password policy or login factor block could not be read.")
423
+ add("q2", "Question predicates", "Q2: Role and scope",
424
+ missing="No production role authorization and scope read-back producer is available.")
425
+ add("q3", "Question predicates", "Q3: Credential handling",
426
+ missing="No end-to-end credential handling compliance read-back producer is available.")
427
+ add("q4", "Question predicates", "Q4: Information lifecycle",
428
+ missing="No Amazon data retention job or restore-residue observation is available.")
429
+ add("q5", "Question predicates", "Q5: Telemetry", "platform/core/audit.py:read",
430
+ "The tenant audit document could not be read.")
431
+ posture_children = [observations.get("posture-" + key, _answer("unproven", "Missing control."))
432
+ for key in _CONTROL_IDS]
433
+ children = [*posture_children, observations.get("vulnerability", _answer("unproven", "Missing scan."))]
434
+ state = ("unproven" if any(row["state"] not in ("met", "not_met") for row in children)
435
+ else "not_met" if any(row["state"] == "not_met" for row in children) else "met")
436
+ unproven = sum(row["state"] not in ("met", "not_met") for row in children)
437
+ not_met = sum(row["state"] == "not_met" for row in children)
438
+ add("q6", "Question predicates", "Q6: Supply chain and posture", "aios-web/api/routes_security.py:build_posture",
439
+ answer=_answer(state, f"The posture and vulnerability reads leave {unproven} of {len(children)} controls unproven and {not_met} not met; each control is listed below."))
440
+ add("q7", "Question predicates", "Q7: Compliance evidence",
441
+ missing="No authoritative questionnaire or reviewed compliance evidence producer is available.")
442
+ for control_id, label in (("tls_min_version", "TLS minimum"), ("waf_in_path", "Web application firewall"),
443
+ ("origin_bypass_prevented", "Origin protection"), ("firewall_acl", "Firewall rules"),
444
+ ("network_segmentation", "Network segmentation"),
445
+ ("intrusion_detection_monitored", "Intrusion monitoring"),
446
+ ("security_events_written", "Security events")):
447
+ add("posture-" + control_id, "Deployment posture", label,
448
+ "aios-web/api/routes_security.py:" + control_id,
449
+ "The request-time posture observation for this control is unavailable.")
450
+ for key, role in _APPROVED_ROLES:
451
+ add(key, "Approved roles", role, "platform/harness/amazon_client.py:ROLES_TAKEN",
452
+ "The live connector role allow-list could not be read.")
453
+ add("retention-audit", "Information lifecycle", "Audit event retention", "platform/core/audit.py:RETENTION_SECONDS",
454
+ "The audit retention interval or tenant audit document could not be read.")
455
+ add("retention-amazon", "Information lifecycle", "Amazon data retention",
456
+ missing="No Amazon data retention job enforces the declared limit of 30 days after order delivery.")
457
+ add("restore", "Information lifecycle", "Restore residue",
458
+ missing="No restore-residue read-back control is available; purge helpers alone do not prove a clean restore.")
459
+ add("vulnerability", "Operational readiness", "Vulnerability state", "aios-web/api/routes_security.py:_vulnerability_control",
460
+ "No current vulnerability scan producer is available.")
461
+ add("incident", "Operational readiness", "Incident state",
462
+ missing="No incident status read-back producer is available.")
463
+ for key, label in _PRODUCTION_CHECKS:
464
+ add(key, "Production checks", label,
465
+ answer=_answer("unproven", "Unavailable: Amazon production access has not been granted and this live verification is deferred under RD10 and QI13."))
466
+ _check_compliance_strings(claims)
467
+ return claims
468
+
469
+
470
+ def build_compliance(request, tenant):
471
+ return compliance_roster(read_compliance_controls(request, tenant))
472
+
473
+
474
+ def render_compliance_export(claims):
475
+ _check_compliance_strings(claims)
476
+ lines = ["Amazon compliance", ""]
477
+ for claim in claims:
478
+ lines.extend([f"{claim['id']} | {claim['group']} | {COMPLIANCE_STATES[claim['state']]}",
479
+ claim["claim"], claim["evidence"], "Source: " + (claim["source"] or "No producing control"), ""])
480
+ return "\n".join(lines)
481
+
482
+
483
+ @router.get("/compliance")
484
+ def security_compliance(request: Request, response: Response, session: Session = Depends(admin_gate)):
485
+ response.headers["Cache-Control"] = "no-store"
486
+ return {"claims": build_compliance(request, session.tenant), "generated_at": time.time()}
487
+
488
+
489
+ @router.get("/compliance/export")
490
+ def security_compliance_export(request: Request, session: Session = Depends(admin_gate)):
491
+ # Both doors call build_compliance once; the renderer takes that roster, so file and pane cannot drift.
492
+ body = render_compliance_export(build_compliance(request, session.tenant))
493
+ try:
494
+ audit.record("config.changed", session.tenant, session.uname,
495
+ {"setting": "amazon_compliance_export", "action": "download"})
496
+ except audit.AuditRefused as exc:
497
+ print(f"[aios-api] {exc}")
498
+ return Response(body, media_type="text/plain", headers={
499
+ "Content-Disposition": 'attachment; filename="amazon-compliance.txt"',
500
+ "Cache-Control": "no-store",
501
+ })
api/routes_sheet.py CHANGED
@@ -38,6 +38,7 @@ while its surface is a 404.
38
  import hashlib
39
  import json
40
  import os
 
41
  import tempfile
42
  import threading
43
  import uuid
@@ -815,7 +816,8 @@ def _reresolved_for_reader(session: Session, book):
815
  `put_workbook`, and a read path that copied that body would write the READER's numbers into
816
  the OWNER's document: the same leak as serving stale owner values, in the opposite direction,
817
  caused by a GET, and therefore reachable by anybody the workbook was shared with. So this
818
- works on a `copy.deepcopy` and returns it, and nothing here touches the store.
 
819
 
820
  ⭐ THE WALL RUNS ONCE PER DISTINCT DATABASE, exactly as `refresh_sheet` does (R16): a reader
821
  who has lost access to a bound database is refused on every cell of it rather than shown the
@@ -861,6 +863,7 @@ def _reresolved_for_reader(session: Session, book):
861
  if failure is not None:
862
  cell["state"] = "refused"
863
  cell["value"] = None
 
864
  cell["refusal"] = {"code": "database_unreadable",
865
  "message": f"You cannot read {db}."}
866
  cell.pop("limits", None)
@@ -893,6 +896,7 @@ def _reresolved_for_reader(session: Session, book):
893
  info = detail.get("error") if isinstance(detail, dict) else None
894
  cell["state"] = "refused"
895
  cell["value"] = None
 
896
  cell["refusal"] = {
897
  "code": (info or {}).get("code", "sheet_unresolved"),
898
  "message": (info or {}).get("message", "This cell could not be refreshed."),
@@ -1795,6 +1799,123 @@ def _formula_message(code, subject=""):
1795
  }.get(code, "This formula could not be calculated.")
1796
 
1797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1798
  def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=None):
1799
  """Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
1800
 
@@ -1822,14 +1943,13 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
1822
  except sheet_mod.SheetRefusal as exc:
1823
  raise err(400, exc.code, exc.message)
1824
 
1825
- # ⛔ C2's OTHER AGGREGATE ARM IS ANSWERED HERE, NOT LEFT TO FALL THROUGH TO `aggregate_sql`,
1826
- # where it died as `field_unknown` with an empty subject. See `metric_key_refusal`.
1827
- metric_refusal = sheet_mod.metric_key_refusal(binding["aggregate"])
1828
- if metric_refusal is not None:
1829
- raise err(400, metric_refusal.code, metric_refusal.message)
1830
-
1831
  database = _require_database(session, binding["database"])
1832
  window = sheet_mod.period_window(binding.get("period"))
 
 
 
 
 
1833
 
1834
  # ⭐⭐ W54-T36 — THE WALL AND THE SCOPE ARE READ BEFORE THE MIRROR IS OPENED, so the mirror can
1835
  # be built over the columns this cell can possibly read instead of over the whole database.
@@ -1864,9 +1984,8 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
1864
  raise err(409, agg_refusal.code, agg_refusal.message)
1865
  if bound_field and bound_field.get("measure") and not binding.get("period"):
1866
  label = bound_field.get("label") or bound_field.get("key")
1867
- raise err(409, "metric_period_required",
1868
- f"{label} is measured over a period, so this cell needs one. "
1869
- "Open the cell's Period section and choose a period.")
1870
 
1871
  # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
1872
  if wall_nodes:
@@ -1946,8 +2065,8 @@ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
1946
  """Evaluate a C2 binding WITHOUT saving it (contract C1).
1947
 
1948
  ⭐ It takes the binding from the BODY rather than from the stored cell, which is what lets the
1949
- binding editor show a number before anyone commits to it, and what lets this door be exercised
1950
- on a tenant whose store is read-only.
1951
  """
1952
  raw = dict(body or {})
1953
  out = _resolve_binding(session, raw.get("binding"))
 
38
  import hashlib
39
  import json
40
  import os
41
+ import re
42
  import tempfile
43
  import threading
44
  import uuid
 
816
  `put_workbook`, and a read path that copied that body would write the READER's numbers into
817
  the OWNER's document: the same leak as serving stale owner values, in the opposite direction,
818
  caused by a GET, and therefore reachable by anybody the workbook was shared with. So this
819
+ works on a `copy.deepcopy` and returns it without saving the reader's workbook values.
820
+ R10 may create a missing Metric field through the database's ordinary field writer.
821
 
822
  ⭐ THE WALL RUNS ONCE PER DISTINCT DATABASE, exactly as `refresh_sheet` does (R16): a reader
823
  who has lost access to a bound database is refused on every cell of it rather than shown the
 
863
  if failure is not None:
864
  cell["state"] = "refused"
865
  cell["value"] = None
866
+ cell["display"] = ""
867
  cell["refusal"] = {"code": "database_unreadable",
868
  "message": f"You cannot read {db}."}
869
  cell.pop("limits", None)
 
896
  info = detail.get("error") if isinstance(detail, dict) else None
897
  cell["state"] = "refused"
898
  cell["value"] = None
899
+ cell["display"] = ""
900
  cell["refusal"] = {
901
  "code": (info or {}).get("code", "sheet_unresolved"),
902
  "message": (info or {}).get("message", "This cell could not be refreshed."),
 
1799
  }.get(code, "This formula could not be calculated.")
1800
 
1801
 
1802
+ _METRIC_COLUMN_CREATE_LOCK = threading.RLock()
1803
+
1804
+
1805
+ def _forget_sheet_database(session, database):
1806
+ """A field write invalidates both request-local schema and materialised-column memos."""
1807
+ getattr(session, "_sheet_assemblies", {}).pop(database, None)
1808
+ mirrors = getattr(session, "_sheet_mirrors", {})
1809
+ for slot in list(mirrors):
1810
+ if slot[0] == database:
1811
+ mirrors.pop(slot, None)
1812
+
1813
+
1814
+ def _metric_column_aggregate(session, database, aggregate, window):
1815
+ """R10: admit the measure, reuse its column, or create through the ordinary event door.
1816
+
1817
+ The caller has passed the database wall. This writes a field, never a record: a locked
1818
+ connector database still permits adding fields (DESIGN.md section 4). The existing handler
1819
+ owns validation, creator stamps, shared persistence and grant bookkeeping.
1820
+ """
1821
+ import aios_grid
1822
+ from core import grid_events, shared_overlay
1823
+ from harness import measure_filter, semantic, windows
1824
+ from modules import sheet as sheet_mod
1825
+ from routes_grid import _ctx
1826
+
1827
+ key = aggregate["metric_key"]
1828
+
1829
+ def refuse(code, subject=key):
1830
+ exc = sheet_mod.SheetRefusal(code, subject)
1831
+ raise err(409, exc.code, exc.message)
1832
+
1833
+ # These are the two measure-backed registry mirrors. Never fall through to the customer
1834
+ # assembly for another database: that would create a field on the wrong database.
1835
+ if database not in ("customer_data", "product_data"):
1836
+ refuse("measure_not_offered")
1837
+ g = _registry_assembly(session, database)
1838
+ # Customer assembly gates measure_fields(team_id) on may_metrics. Intersect the catalogue
1839
+ # with the served offer too: product has a narrower entity catalogue, and revoked Metric
1840
+ # capability makes the account's offer empty. A browser key can never widen either offer.
1841
+ visible_measures = {m["key"] for m in g.get("measures") or ()}
1842
+ offered = {m["key"]: m for m in measure_filter.measure_fields(g.get("team_id"))
1843
+ if m["key"] in visible_measures}
1844
+ if key not in offered:
1845
+ refuse("measure_not_offered")
1846
+ label = offered[key].get("label") or key
1847
+ try:
1848
+ fold = sheet_mod.metric_key_fold(label, (semantic.metrics().get(key) or {}).get("agg"))
1849
+ except sheet_mod.SheetRefusal as exc:
1850
+ raise err(409, exc.code, exc.message)
1851
+ window = windows.normalize(window)
1852
+ if window is None:
1853
+ # An absent period or unresolved period.ref must never select the column's default.
1854
+ refuse("metric_period_required", label)
1855
+
1856
+ def existing(fields):
1857
+ candidates = [f for f in fields or () if isinstance(f, dict) and f.get("key")
1858
+ and isinstance(f.get("measure"), dict) and f["measure"].get("key") == key]
1859
+ wanted = sheet_mod.measure_column_key(key, window)
1860
+ return next((f for f in candidates if sheet_mod.measure_column_key(
1861
+ key, windows.normalize(f["measure"].get("window"))) == wanted),
1862
+ candidates[0] if candidates else None)
1863
+
1864
+ def column(field):
1865
+ return {"kind": "column", "fn": fold, "field": field["key"]}
1866
+
1867
+ found = existing(g.get("fields"))
1868
+ if found is not None:
1869
+ return column(found)
1870
+
1871
+ # One column per measure, not per cell period. LTM is only the column's declared DEFAULT;
1872
+ # _mirror(metric_window=window) re-resolves it at the period each cell actually names.
1873
+ # Hash the full key so slug truncation does not alias measures, and check occupied keys
1874
+ # before writing so even a hash collision cannot silently redefine an existing field.
1875
+ slug = re.sub(r"[^a-z0-9_]+", "_", key.lower()).strip("_")[:40] or "metric"
1876
+ suffix = hashlib.sha256(key.encode("utf-8")).hexdigest()[:12]
1877
+ raw = {"key": aios_grid.MEASURE_FIELD_PREFIX + slug + "_" + suffix,
1878
+ "label": label, "measure": {"key": key, "window": {"kind": "ltm"}},
1879
+ "permissions": {"edit": "collaborative"}}
1880
+ if aios_grid.clean_measure_field(raw, offered) is None:
1881
+ refuse("measure_not_offered", label)
1882
+
1883
+ # A second request may have assembled before the first write. Serialise automatic creates
1884
+ # in this process and re-read occupied keys through the scoped assembly before reusing one.
1885
+ with _METRIC_COLUMN_CREATE_LOCK:
1886
+ try:
1887
+ ctx = _ctx(session, g["fields"], g["pids"],
1888
+ scope_key="product" if database == "product_data" else "customer",
1889
+ measure_keys=frozenset(offered), measure_offer=tuple(offered.values()))
1890
+ storage_key, _topic = grid_events._field_share_keys(ctx)
1891
+ stored = shared_overlay.fields(storage_key, st=session.runtime)
1892
+ personal = grid_events.table_workspace(
1893
+ ctx, allowed_pids=g["pids"], consume_corrections=False).get("fields") or {}
1894
+ if (raw["key"] in stored or raw["key"] in personal or raw["key"] in ctx.hidden_keys
1895
+ or raw["key"] in {f.get("key") for f in g["fields"]}):
1896
+ _forget_sheet_database(session, database)
1897
+ found = existing(_registry_assembly(session, database).get("fields"))
1898
+ if found is not None:
1899
+ return column(found)
1900
+ refuse("metric_column_conflict", label)
1901
+ try:
1902
+ # Event objects use `type`, not the handler's local variable name `kind`.
1903
+ applied = grid_events.handle_one({"id": "sheet-metric-" + uuid.uuid4().hex,
1904
+ "type": "field_upsert", "field": raw}, ctx)
1905
+ finally:
1906
+ _forget_sheet_database(session, database)
1907
+ except grid_events.StoreUnavailable:
1908
+ exc = sheet_mod.SheetRefusal("metric_column_create_failed", label)
1909
+ raise err(503, exc.code, exc.message)
1910
+ # A True handler result can also mean "repaint the refusal"; inspect both channels.
1911
+ if ctx.out.refusals:
1912
+ failure = ctx.out.refusals[0]
1913
+ raise err(409, failure["code"], failure["message"])
1914
+ if not applied:
1915
+ refuse("metric_column_create_failed", label)
1916
+ return column(raw)
1917
+
1918
+
1919
  def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=None):
1920
  """Evaluate ONE C2 binding and return `{value, limits, sql_columns}`.
1921
 
 
1943
  except sheet_mod.SheetRefusal as exc:
1944
  raise err(400, exc.code, exc.message)
1945
 
 
 
 
 
 
 
1946
  database = _require_database(session, binding["database"])
1947
  window = sheet_mod.period_window(binding.get("period"))
1948
+ # W59-T14 / R10: the per-database wall is contract step 1. A metric key must not be looked
1949
+ # up or acted on before the caller passes it; the ordinary column guards below still apply.
1950
+ if binding["aggregate"].get("metric_key"):
1951
+ binding["aggregate"] = _metric_column_aggregate(
1952
+ session, database, binding["aggregate"], window)
1953
 
1954
  # ⭐⭐ W54-T36 — THE WALL AND THE SCOPE ARE READ BEFORE THE MIRROR IS OPENED, so the mirror can
1955
  # be built over the columns this cell can possibly read instead of over the whole database.
 
1984
  raise err(409, agg_refusal.code, agg_refusal.message)
1985
  if bound_field and bound_field.get("measure") and not binding.get("period"):
1986
  label = bound_field.get("label") or bound_field.get("key")
1987
+ refusal = sheet_mod.SheetRefusal("metric_period_required", label)
1988
+ raise err(409, refusal.code, refusal.message)
 
1989
 
1990
  # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
1991
  if wall_nodes:
 
2065
  """Evaluate a C2 binding WITHOUT saving it (contract C1).
2066
 
2067
  ⭐ It takes the binding from the BODY rather than from the stored cell, which is what lets the
2068
+ binding editor show a number before anyone commits the cell. R10 may create a missing Metric
2069
+ field through the database's ordinary field writer; reusing a column needs no field write.
2070
  """
2071
  raw = dict(body or {})
2072
  out = _resolve_binding(session, raw.get("binding"))
api/routes_templates.py CHANGED
@@ -166,3 +166,93 @@ def apply_template(key: str, body: dict = Body(default=None),
166
  alert_id = None
167
  return {"key": key, "table": body.get("table"), "views": applied,
168
  "alert": alert_id, "alerted": bool(alert_id)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  alert_id = None
167
  return {"key": key, "table": body.get("table"), "views": applied,
168
  "alert": alert_id, "alerted": bool(alert_id)}
169
+
170
+
171
+ def _store(session: Session):
172
+ return session.runtime
173
+
174
+
175
+ @router.get("/sheet-templates")
176
+ def list_sheet_templates(session: Session = Depends(require_session)):
177
+ """The workbook gallery, including sources this tenant has not connected."""
178
+ from core import sheet_templates, user_tables
179
+ from fastapi import HTTPException
180
+ from routes_sheet import _require_database
181
+
182
+ definitions = user_tables.all_defs(_store(session))
183
+ databases = []
184
+ for database_key, definition in definitions.items():
185
+ if sheet_templates.source_of_database(database_key) is None:
186
+ continue
187
+ try:
188
+ _require_database(session, database_key)
189
+ except HTTPException as exc:
190
+ if exc.status_code in (403, 404):
191
+ continue
192
+ raise
193
+ databases.append({"key": database_key, "label": definition.get("label") or database_key})
194
+ return {"templates": [
195
+ {"key": descriptor["key"], "title": descriptor["title"],
196
+ "answers": descriptor["answers"], "source": descriptor["source"],
197
+ "databaseHint": descriptor["database_hint"],
198
+ "databases": [database for database in databases
199
+ if sheet_templates.source_of_database(database["key"]) == descriptor["source"]]}
200
+ for descriptor in sheet_templates.TEMPLATES
201
+ ]}
202
+
203
+
204
+ @router.post("/sheet-templates/{key}/apply")
205
+ def apply_sheet_template(key: str, body: dict = Body(default=None),
206
+ session: Session = Depends(require_session)):
207
+ """Materialise and calculate a workbook through the existing Sheet engine."""
208
+ from core import sheet_templates, sheets, user_tables
209
+ from modules.sheet import SheetRefusal as BindingRefusal
210
+ from routes_sheet import _require_database, refresh_sheet
211
+
212
+ descriptor = sheet_templates.template(key)
213
+ if descriptor is None:
214
+ raise err(404, "unknown_sheet_template", "That sheet template does not exist.")
215
+ body = body if isinstance(body, dict) else {}
216
+ database_key = body.get("database")
217
+ name = body.get("name", "")
218
+ if not isinstance(database_key, str) or not database_key.strip():
219
+ raise err(404, "unknown_database", "That database does not exist.")
220
+ if not isinstance(name, str):
221
+ raise err(400, "bad_request", "The workbook name must be text.")
222
+ database_key = database_key.strip()
223
+ st = _store(session)
224
+ if database_key not in user_tables.all_defs(st):
225
+ raise err(404, "unknown_database", "That database does not exist.")
226
+ _require_database(session, database_key)
227
+ if sheet_templates.source_of_database(database_key) != descriptor["source"]:
228
+ raise err(400, "template_source_mismatch",
229
+ "That database uses a different connector from this template.")
230
+
231
+ book = None
232
+ try:
233
+ book = sheet_templates.apply_template(st, key, database_key, name=name,
234
+ created_by=session.uname)
235
+ # Owners read their persisted values. Use the same permission-scoped
236
+ # refresh as Sheet so the first open already contains computed cells.
237
+ refreshed = refresh_sheet(book["id"], session=session)["workbook"]
238
+ failures = []
239
+ for tab in refreshed["sheets"]:
240
+ for addr, cell in tab["cells"].items():
241
+ if cell.get("state") == "refused" or cell.get("error") or cell.get("refusal"):
242
+ sentence = (cell.get("refusal") or {}).get("message")
243
+ failures.append(tab["name"] + "!" + addr + (": " + sentence if sentence else ""))
244
+ if failures:
245
+ raise sheet_templates.TemplateRefusal(
246
+ "template_cells_refused",
247
+ detail="The template could not calculate cells: " + "; ".join(failures) + ".")
248
+ return {"workbook": refreshed}
249
+ except Exception as exc:
250
+ if book is not None:
251
+ sheets.delete_workbook(st, book["id"])
252
+ if isinstance(exc, sheet_templates.TemplateRefusal):
253
+ status = {"unknown_sheet_template": 404, "unknown_database": 404,
254
+ "template_source_mismatch": 400}.get(exc.code, 409)
255
+ raise err(status, exc.code, exc.sentence()) from exc
256
+ if isinstance(exc, (sheets.SheetRefusal, BindingRefusal)):
257
+ raise err(409, exc.code, exc.message) from exc
258
+ raise
platform/core/audit.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded, tenant-scoped security events. Refuse secrets before attempting any store I/O."""
2
+ from collections.abc import Mapping
3
+ import math
4
+ import re
5
+ import time
6
+
7
+ from harness import runtime
8
+
9
+
10
+ AUDIT_KINDS = frozenset({
11
+ "auth.login", "auth.login_failed", "auth.lockout", "auth.mfa_enrolled",
12
+ "auth.mfa_failed", "auth.logout", "admin.grant", "credential.added",
13
+ "credential.rotated", "credential.revoked", "amazon.sync", "amazon.throttled",
14
+ "amazon.authorization_lost", "data.purge", "data.restore", "config.changed",
15
+ })
16
+ BUCKET = "security_events"
17
+ MAX_EVENTS = 2000
18
+ RETENTION_SECONDS = 400 * 24 * 60 * 60
19
+ _ATTRIBUTION_MAX = 256
20
+ _KEY_MAX = 128
21
+
22
+
23
+ def _key_name(key):
24
+ return "".join(c for c in key.casefold() if c.isalnum())
25
+
26
+
27
+ # Restated from core.keychain._PREVIEW_FIELDS to avoid coupling a log to the keychain.
28
+ # Keep the first six names and that tuple in step; client_secret is also an Amazon secret.
29
+ SECRET_KEYS = frozenset(_key_name(key) for key in (
30
+ "api_key", "access_token", "value", "password", "token", "refresh_token",
31
+ "client_secret", "secret", "private_key", "authorization", "cookie", "session",
32
+ "mfa_secret", "recovery_code", "otpauth", "credential",
33
+ ))
34
+ _BEARER = re.compile(r"\bbearer\s+\S+", re.IGNORECASE)
35
+ _JWT = re.compile(r"\beyJ[A-Za-z0-9_-]*\.")
36
+
37
+
38
+ class AuditRefused(ValueError):
39
+ """A call-site error carrying only the field name and refusal reason, never its value."""
40
+
41
+ def __init__(self, key, reason):
42
+ self.key = key
43
+ self.reason = reason
44
+ # Explaining a refusal with the value would put the secret into its traceback.
45
+ super().__init__(f"audit refused key {key!r}: {reason}")
46
+
47
+
48
+ def _string(key, value):
49
+ if len(value) > 512:
50
+ raise AuditRefused(key, "string exceeds 512 characters")
51
+ if value.startswith("Atzr|"):
52
+ raise AuditRefused(key, "Atzr refresh-token prefix")
53
+ if _BEARER.search(value):
54
+ raise AuditRefused(key, "bearer token shape")
55
+ if _JWT.search(value):
56
+ raise AuditRefused(key, "JWT token shape")
57
+
58
+
59
+ def _attribution(key, value):
60
+ if not isinstance(value, str) or not value.strip():
61
+ raise AuditRefused(key, "attribution requires a non-empty string")
62
+ _string(key, value)
63
+ value = value.strip()
64
+ _string(key, value)
65
+ if len(value) > _ATTRIBUTION_MAX:
66
+ raise AuditRefused(key, "attribution exceeds 256 characters")
67
+ return value.lower() if key == "tenant" else value
68
+
69
+
70
+ def event(kind, tenant, principal, detail=None, *, now=None) -> dict:
71
+ """Validate without I/O; an explicit epoch makes this pure and deterministic for gates."""
72
+ if not isinstance(kind, str) or kind not in AUDIT_KINDS:
73
+ raise AuditRefused("kind", "unknown audit kind")
74
+ tenant = _attribution("tenant", tenant)
75
+ principal = _attribution("principal", principal)
76
+ if detail is None:
77
+ detail = {}
78
+ if not isinstance(detail, Mapping):
79
+ raise AuditRefused("detail", "detail must be a flat mapping")
80
+ clean = {}
81
+ for key, value in detail.items():
82
+ if not isinstance(key, str) or not key.strip():
83
+ raise AuditRefused("detail", "detail keys must be non-empty strings")
84
+ # A malformed key can itself contain a token. Never echo that key in diagnostics.
85
+ _string("detail key", key)
86
+ if len(key) > _KEY_MAX or any(ord(c) < 32 for c in key):
87
+ raise AuditRefused("detail key", "key exceeds 128 characters or contains controls")
88
+ if _key_name(key) in SECRET_KEYS:
89
+ raise AuditRefused(key, "secret key name")
90
+ if isinstance(value, (Mapping, list, tuple, set, frozenset)):
91
+ raise AuditRefused(key, "nested value violates flat detail")
92
+ if type(value) not in (str, int, bool, float):
93
+ raise AuditRefused(key, "unsupported detail value type")
94
+ if isinstance(value, str):
95
+ _string(key, value)
96
+ if isinstance(value, float) and not math.isfinite(value):
97
+ raise AuditRefused(key, "detail number must be finite")
98
+ clean[key] = value
99
+ try:
100
+ ts = float(time.time() if now is None else now)
101
+ except (TypeError, ValueError, OverflowError):
102
+ raise AuditRefused("ts", "timestamp must be finite epoch seconds") from None
103
+ if not math.isfinite(ts):
104
+ raise AuditRefused("ts", "timestamp must be finite epoch seconds")
105
+ return {"ts": ts, "kind": kind, "tenant": tenant, "principal": principal, "detail": clean}
106
+
107
+
108
+ def ordered(doc, tenant, limit=200) -> list[dict]:
109
+ """Return ascending timestamps; a limit retains the most recent rows, still ascending.
110
+
111
+ The stored tenant must match exactly even inside an already scoped runtime. This second
112
+ wall protects readers if a future migration ever puts multiple tenants in one document.
113
+ """
114
+ tenant = _attribution("tenant", tenant)
115
+ limit = max(0, int(limit))
116
+ if not limit or not isinstance(doc, Mapping):
117
+ return []
118
+ rows = doc.get("events")
119
+ if not isinstance(rows, list):
120
+ return []
121
+ retained = []
122
+ for row in rows:
123
+ if not isinstance(row, dict) or row.get("tenant") != tenant:
124
+ continue
125
+ if type(row.get("ts")) not in (int, float):
126
+ # In particular, None must not ask event() for today's clock on a pure read.
127
+ continue
128
+ try:
129
+ # Revalidate persisted rows too, so legacy/corrupt documents cannot leak a secret.
130
+ retained.append(event(row.get("kind"), tenant, row.get("principal"),
131
+ row.get("detail"), now=row["ts"]))
132
+ except (AuditRefused, KeyError):
133
+ continue
134
+ return sorted(retained, key=lambda row: row["ts"])[-limit:]
135
+
136
+
137
+ def record(kind, tenant, principal, detail=None) -> dict | None:
138
+ """Refusals raise before I/O. Store failures lose the event, never the user's sign-in."""
139
+ item = event(kind, tenant, principal, detail)
140
+ tenant = item["tenant"]
141
+
142
+ def _append(doc):
143
+ # Prune and cap INSIDE the atomic update, as users.note_login_failure does.
144
+ rows = ordered(doc, tenant, MAX_EVENTS)
145
+ rows.append(item)
146
+ rows = [row for row in rows if row["ts"] >= item["ts"] - RETENTION_SECONDS]
147
+ return {"events": sorted(rows, key=lambda row: row["ts"])[-MAX_EVENTS:]}
148
+
149
+ try:
150
+ # Bare core.store.update is bound to tenant #0. Always use the tenant-scoped door.
151
+ # ⭐⭐ flush="async" IS DELIBERATE AND IT IS NOT A PERFORMANCE TWEAK. The default
152
+ # flush="sync" is a BLOCKING upload (core/store.py::update says so), and this writer sits
153
+ # on the sign-in path: every login would then wait on a network round trip, and on the hf
154
+ # backend every login would spend one of that repo's 256 commits per hour. The async
155
+ # branch applies the mutation to the in-process cache and a coalescing worker commits it,
156
+ # which is the same posture the table-workspace hot path has used since wave 7.
157
+ # ⚠ THE COST, stated rather than hidden: a container that dies before the worker flushes
158
+ # loses the events still in its cache. That is the same window `record` already accepts by
159
+ # swallowing a store failure, and it is the right side of the trade: an audit log must
160
+ # never be the reason a person cannot sign in.
161
+ runtime.get_runtime(str(tenant)).update(BUCKET, _append, flush="async")
162
+ except Exception as exc:
163
+ # Exception text can contain credentials from a provider or connection string.
164
+ print(f"[aios-api] audit lost {item['kind']} for tenant {tenant!r}: "
165
+ f"store unavailable ({type(exc).__name__}).")
166
+ return None
167
+ return item
168
+
169
+
170
+ def read(tenant, limit=200, now=None) -> list[dict]:
171
+ """Read one tenant's retained events. Read failures propagate instead of claiming no history."""
172
+ tenant = _attribution("tenant", tenant)
173
+ now = time.time() if now is None else float(now)
174
+ doc = runtime.get_runtime(str(tenant)).get(BUCKET)
175
+ rows = ordered(doc, tenant, limit)
176
+ return [row for row in rows if row["ts"] >= now - RETENTION_SECONDS]
platform/core/keychain.py CHANGED
@@ -14,19 +14,26 @@ decrypts and writes are refused — fail closed, never a plaintext fallback.
14
 
15
  SHAPE (bucket `keychain`, per-tenant via the runtime handle):
16
 
17
- {entries: {id: {id, connection_id, slot, label, type, enc, preview, created, createdBy}}}
 
18
 
19
- `enc` = Fernet token over the JSON fields dict. `preview` = a masked hint ("····1234")
 
 
20
  computed ONCE at write from the entry's most secret-looking field — the ONLY part of a
21
  secret that ever leaves this module through a route. `read_fields` exists for the CONNECTOR
22
  LAYER; no route returns its output.
23
  """
24
  import datetime as _dt
 
25
  import json
26
  import os
27
  import secrets as _secrets
28
 
29
  KEY = 'keychain'
 
 
 
30
  #: ⭐ WAVE 23 (C11/R8) — `stripe` and `shopify` joined. They are TOKEN connectors, not OAuth
31
  #: ones, and that is the whole reason they could ship in this wave: both issue a long-lived
32
  #: restricted key / custom-app token an admin pastes in, so they need no OAuth client, no
@@ -69,6 +76,50 @@ class KeychainLocked(Exception):
69
  """Raised when AIOS_KEYCHAIN_KEY is absent/wrong — callers answer 503, never {}."""
70
 
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def _fernet():
73
  key = (os.environ.get('AIOS_KEYCHAIN_KEY') or '').strip()
74
  if not key:
@@ -217,13 +268,25 @@ def add_entry(rt, label, etype, fields, username):
217
  etype = str(etype or '').strip().lower()
218
  if etype not in ENTRY_TYPES:
219
  raise ValueError(f"type must be one of {', '.join(sorted(ENTRY_TYPES))}")
220
- if not isinstance(fields, dict) or not fields:
 
 
221
  raise ValueError('fields must be a non-empty object')
 
 
222
  clean = {}
223
  for k, v in list(fields.items())[:12]:
224
  k = str(k).strip()[:40]
 
 
225
  if k and isinstance(v, (str, int, float, bool)):
226
  clean[k] = str(v)[:MAX_FIELD_LEN]
 
 
 
 
 
 
227
  if not clean:
228
  raise ValueError('no usable fields')
229
  token = _fernet().encrypt(json.dumps(clean, ensure_ascii=False).encode('utf-8'))
@@ -235,9 +298,12 @@ def add_entry(rt, label, etype, fields, username):
235
  label = f'{kind_label(etype)} {slot}'
236
  row = {'id': eid, 'connection_id': eid, 'slot': slot,
237
  'label': label, 'type': etype, 'enc': token.decode('ascii'),
 
238
  'preview': preview,
239
  'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
240
  'createdBy': str(username or '')}
 
 
241
 
242
  def _up(cur):
243
  entries = cur.setdefault('entries', {})
@@ -296,19 +362,20 @@ def read_fields(rt, entry_id):
296
  None when the entry does not exist; KeychainLocked when the key is absent/wrong (a wrong
297
  key must be loud — silently empty creds would read as 'not configured')."""
298
  e = (_bucket(rt).get('entries') or {}).get(str(entry_id))
299
- if not isinstance(e, dict) or not e.get('enc'):
300
  return None
 
 
 
 
 
301
  try:
302
  raw = _fernet().decrypt(str(e['enc']).encode('ascii'))
303
  except KeychainLocked:
304
  raise
305
  except Exception:
306
- raise KeychainLocked('this entry does not decrypt under the configured key')
307
- try:
308
- data = json.loads(raw.decode('utf-8'))
309
- return data if isinstance(data, dict) else None
310
- except Exception:
311
- return None
312
 
313
 
314
  def first_entry_of_type(rt, etype):
@@ -674,11 +741,13 @@ def put_user_secret(rt, username, provider, fields):
674
  raise ValueError('no usable fields')
675
  token = _fernet().encrypt(json.dumps(clean, ensure_ascii=False).encode('utf-8'))
676
  row = {'enc': token.decode('ascii'),
 
677
  'updated': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')}
678
 
679
  def _up(cur):
680
- cur.setdefault('user_secrets', {}).setdefault(username, {})[provider] = row
681
- return cur
 
682
 
683
  rt.update(KEY, _up, flush='sync')
684
  return True
@@ -689,19 +758,20 @@ def read_user_secret(rt, username, provider):
689
  never read as 'not connected')."""
690
  slot = ((_bucket(rt).get('user_secrets') or {}).get(str(username)) or {}).get(
691
  str(provider or '').lower())
692
- if not isinstance(slot, dict) or not slot.get('enc'):
693
  return None
 
 
 
 
 
694
  try:
695
  raw = _fernet().decrypt(str(slot['enc']).encode('ascii'))
696
  except KeychainLocked:
697
  raise
698
  except Exception:
699
- raise KeychainLocked('this slot does not decrypt under the configured key')
700
- try:
701
- data = json.loads(raw.decode('utf-8'))
702
- return data if isinstance(data, dict) else None
703
- except Exception:
704
- return None
705
 
706
 
707
  def drop_user_secret(rt, username, provider):
@@ -747,6 +817,51 @@ def register_prober(etype, fn):
747
  return etype in _PROBES
748
 
749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
750
  def test_entry(rt, entry_id, timeout=8):
751
  """A cheap, READ-ONLY liveness probe. odoo: xmlrpc `common.version()` (no auth, no data);
752
  generic: shape-only. Always answers {ok, message} — an exception here is a result, not a
@@ -755,6 +870,8 @@ def test_entry(rt, entry_id, timeout=8):
755
  e = (_bucket(rt).get('entries') or {}).get(str(entry_id))
756
  if not isinstance(e, dict):
757
  return {'ok': False, 'message': 'no such entry'}
 
 
758
  fields = read_fields(rt, entry_id) or {}
759
  # ⭐ W31 — A REGISTERED PROBER ANSWERS FOR ITS OWN TYPE, if the connector layer filled the
760
  # slot. A shape check says "you pasted something", which is the least useful thing an
 
14
 
15
  SHAPE (bucket `keychain`, per-tenant via the runtime handle):
16
 
17
+ {entries: {id: {id, connection_id, slot, label, type, enc, envelope_version,
18
+ preview, created, createdBy}}}
19
 
20
+ Amazon rows also carry `client_secret_rotation_deadline`, empty when unknown, and may carry
21
+ the ciphertext-bound `probe` proof. `enc` = Fernet token over the JSON fields dict.
22
+ `preview` = a masked hint ("····1234")
23
  computed ONCE at write from the entry's most secret-looking field — the ONLY part of a
24
  secret that ever leaves this module through a route. `read_fields` exists for the CONNECTOR
25
  LAYER; no route returns its output.
26
  """
27
  import datetime as _dt
28
+ import hashlib
29
  import json
30
  import os
31
  import secrets as _secrets
32
 
33
  KEY = 'keychain'
34
+ ORIGINAL_ENVELOPE_VERSION = 1
35
+ ENVELOPE_VERSION = ORIGINAL_ENVELOPE_VERSION
36
+ AMAZON_ROTATION_DEADLINE_FIELD = 'client_secret_rotation_deadline'
37
  #: ⭐ WAVE 23 (C11/R8) — `stripe` and `shopify` joined. They are TOKEN connectors, not OAuth
38
  #: ones, and that is the whole reason they could ship in this wave: both issue a long-lived
39
  #: restricted key / custom-app token an admin pastes in, so they need no OAuth client, no
 
76
  """Raised when AIOS_KEYCHAIN_KEY is absent/wrong — callers answer 503, never {}."""
77
 
78
 
79
+ class KeychainEnvelopeError(ValueError):
80
+ """A stored credential envelope is malformed or unsupported."""
81
+
82
+
83
+ class KeychainEnvelopeVersionError(KeychainEnvelopeError):
84
+ """An unsupported envelope is distinct from an unavailable encryption key."""
85
+
86
+
87
+ def _check_envelope_version(row):
88
+ # Untagged rows use the original Fernet envelope without rewriting storage.
89
+ version = row.get('envelope_version', ORIGINAL_ENVELOPE_VERSION)
90
+ if type(version) is not int or version != ORIGINAL_ENVELOPE_VERSION:
91
+ raise KeychainEnvelopeVersionError('This credential uses an unsupported encryption envelope version.')
92
+
93
+
94
+ def _decoded_fields(raw):
95
+ try:
96
+ data = json.loads(raw.decode('utf-8'))
97
+ except Exception:
98
+ raise KeychainEnvelopeError('The stored credential payload is invalid.') from None
99
+ if not isinstance(data, dict) or not data:
100
+ raise KeychainEnvelopeError('The stored credential payload is invalid.')
101
+ return data
102
+
103
+
104
+ def _amazon_rotation_deadline(value):
105
+ """Validate an Amazon-issued timestamp supplied by the admin, never infer an expiry."""
106
+ if value is None or value == '':
107
+ return ''
108
+ message = 'Enter the Amazon-issued secret rotation deadline as an ISO 8601 timestamp with a timezone.'
109
+ if not isinstance(value, str) or len(value) > 64:
110
+ raise ValueError(message)
111
+ value = value.strip()
112
+ if not value:
113
+ return ''
114
+ try:
115
+ stamp = _dt.datetime.fromisoformat(value.replace('Z', '+00:00'))
116
+ if stamp.tzinfo is None or stamp.utcoffset() is None:
117
+ raise ValueError()
118
+ return stamp.astimezone(_dt.timezone.utc).isoformat().replace('+00:00', 'Z')
119
+ except (ValueError, OverflowError):
120
+ raise ValueError(message) from None
121
+
122
+
123
  def _fernet():
124
  key = (os.environ.get('AIOS_KEYCHAIN_KEY') or '').strip()
125
  if not key:
 
268
  etype = str(etype or '').strip().lower()
269
  if etype not in ENTRY_TYPES:
270
  raise ValueError(f"type must be one of {', '.join(sorted(ENTRY_TYPES))}")
271
+ if etype == 'amazon_sp' and not isinstance(fields, dict):
272
+ fields = {}
273
+ if not isinstance(fields, dict) or (not fields and etype != 'amazon_sp'):
274
  raise ValueError('fields must be a non-empty object')
275
+ deadline = (_amazon_rotation_deadline(fields.get(AMAZON_ROTATION_DEADLINE_FIELD))
276
+ if etype == 'amazon_sp' else '')
277
  clean = {}
278
  for k, v in list(fields.items())[:12]:
279
  k = str(k).strip()[:40]
280
+ if etype == 'amazon_sp' and k == AMAZON_ROTATION_DEADLINE_FIELD:
281
+ continue
282
  if k and isinstance(v, (str, int, float, bool)):
283
  clean[k] = str(v)[:MAX_FIELD_LEN]
284
+ if etype == 'amazon_sp':
285
+ from harness import amazon_client
286
+ missing = [key for key in amazon_client.CREDENTIAL_FIELDS
287
+ if not isinstance(fields.get(key), str) or not clean.get(key, '').strip()]
288
+ if missing:
289
+ raise ValueError('Missing ' + ', '.join(missing) + '. Enter every required field.')
290
  if not clean:
291
  raise ValueError('no usable fields')
292
  token = _fernet().encrypt(json.dumps(clean, ensure_ascii=False).encode('utf-8'))
 
298
  label = f'{kind_label(etype)} {slot}'
299
  row = {'id': eid, 'connection_id': eid, 'slot': slot,
300
  'label': label, 'type': etype, 'enc': token.decode('ascii'),
301
+ 'envelope_version': ENVELOPE_VERSION,
302
  'preview': preview,
303
  'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
304
  'createdBy': str(username or '')}
305
+ if etype == 'amazon_sp':
306
+ row[AMAZON_ROTATION_DEADLINE_FIELD] = deadline
307
 
308
  def _up(cur):
309
  entries = cur.setdefault('entries', {})
 
362
  None when the entry does not exist; KeychainLocked when the key is absent/wrong (a wrong
363
  key must be loud — silently empty creds would read as 'not configured')."""
364
  e = (_bucket(rt).get('entries') or {}).get(str(entry_id))
365
+ if e is None:
366
  return None
367
+ if not isinstance(e, dict):
368
+ raise KeychainEnvelopeError('The stored credential envelope is invalid.')
369
+ _check_envelope_version(e)
370
+ if not e.get('enc'):
371
+ raise KeychainEnvelopeError('The stored credential ciphertext is missing.')
372
  try:
373
  raw = _fernet().decrypt(str(e['enc']).encode('ascii'))
374
  except KeychainLocked:
375
  raise
376
  except Exception:
377
+ raise KeychainLocked('this entry does not decrypt under the configured key') from None
378
+ return _decoded_fields(raw)
 
 
 
 
379
 
380
 
381
  def first_entry_of_type(rt, etype):
 
741
  raise ValueError('no usable fields')
742
  token = _fernet().encrypt(json.dumps(clean, ensure_ascii=False).encode('utf-8'))
743
  row = {'enc': token.decode('ascii'),
744
+ 'envelope_version': ENVELOPE_VERSION,
745
  'updated': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')}
746
 
747
  def _up(cur):
748
+ slots = dict(cur.get('user_secrets') or {})
749
+ slots[username] = {**(slots.get(username) or {}), provider: row}
750
+ return {**cur, 'user_secrets': slots}
751
 
752
  rt.update(KEY, _up, flush='sync')
753
  return True
 
758
  never read as 'not connected')."""
759
  slot = ((_bucket(rt).get('user_secrets') or {}).get(str(username)) or {}).get(
760
  str(provider or '').lower())
761
+ if slot is None:
762
  return None
763
+ if not isinstance(slot, dict):
764
+ raise KeychainEnvelopeError('The stored credential envelope is invalid.')
765
+ _check_envelope_version(slot)
766
+ if not slot.get('enc'):
767
+ raise KeychainEnvelopeError('The stored credential ciphertext is missing.')
768
  try:
769
  raw = _fernet().decrypt(str(slot['enc']).encode('ascii'))
770
  except KeychainLocked:
771
  raise
772
  except Exception:
773
+ raise KeychainLocked('this slot does not decrypt under the configured key') from None
774
+ return _decoded_fields(raw)
 
 
 
 
775
 
776
 
777
  def drop_user_secret(rt, username, provider):
 
817
  return etype in _PROBES
818
 
819
 
820
+ def entry_verified(rt, entry_id):
821
+ """Read proof for the current ciphertext without decrypting or making a network call."""
822
+ entry = (_bucket(rt).get('entries') or {}).get(str(entry_id))
823
+ if not isinstance(entry, dict) or not entry.get('enc'):
824
+ return False
825
+ proof = entry.get('probe')
826
+ return (isinstance(proof, dict) and proof.get('ok') is True
827
+ and proof.get('encrypted_digest') == hashlib.sha256(
828
+ str(entry['enc']).encode('utf-8')).hexdigest())
829
+
830
+
831
+ def _test_amazon_entry(rt, entry_id, entry, timeout):
832
+ """Only an explicit test calls the registered probe; storage and listing stay offline.
833
+
834
+ Bind the result to ciphertext so a replacement cannot inherit a previous credential's proof.
835
+ Neither provider messages nor exception text cross this boundary: both can echo input.
836
+ """
837
+ result = {'ok': False,
838
+ 'message': 'Amazon did not confirm marketplace access. Check the five fields and test again.'}
839
+ try:
840
+ fields = read_fields(rt, entry_id) or {}
841
+ prober = _PROBES.get('amazon_sp')
842
+ got = prober(dict(fields), timeout) if prober is not None else None
843
+ if isinstance(got, dict) and got.get('ok') is True:
844
+ result = {'ok': True, 'message': 'Amazon confirmed marketplace access.'}
845
+ except Exception: # noqa: BLE001
846
+ pass
847
+
848
+ def _record(cur):
849
+ current = (cur.get('entries') or {}).get(str(entry_id))
850
+ if not isinstance(current, dict) or current.get('enc') != entry.get('enc'):
851
+ raise ValueError('The credential changed during the test. Reload and test again.')
852
+ current['probe'] = {
853
+ 'ok': result['ok'],
854
+ 'encrypted_digest': hashlib.sha256(str(entry.get('enc') or '').encode('utf-8')).hexdigest(),
855
+ }
856
+ return cur
857
+
858
+ try:
859
+ rt.update(KEY, _record, flush='sync')
860
+ except Exception: # noqa: BLE001
861
+ return {'ok': False, 'message': 'The test result could not be saved. Reload and test again.'}
862
+ return result
863
+
864
+
865
  def test_entry(rt, entry_id, timeout=8):
866
  """A cheap, READ-ONLY liveness probe. odoo: xmlrpc `common.version()` (no auth, no data);
867
  generic: shape-only. Always answers {ok, message} — an exception here is a result, not a
 
870
  e = (_bucket(rt).get('entries') or {}).get(str(entry_id))
871
  if not isinstance(e, dict):
872
  return {'ok': False, 'message': 'no such entry'}
873
+ if e.get('type') == 'amazon_sp':
874
+ return _test_amazon_entry(rt, entry_id, dict(e), timeout)
875
  fields = read_fields(rt, entry_id) or {}
876
  # ⭐ W31 — A REGISTERED PROBER ANSWERS FOR ITS OWN TYPE, if the connector layer filled the
877
  # slot. A shape check says "you pasted something", which is the least useful thing an
platform/core/sheet_templates.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loopable's prebuilt connector workbooks (W59-T29, contract C4).
2
+
3
+ Descriptors are data; applying them uses the existing workbook persistence engine.
4
+ The API owns permission checks and calculation under the calling user's row scope.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from copy import deepcopy
9
+ from datetime import date, timedelta
10
+ import re
11
+
12
+ from core import sheets, user_tables
13
+
14
+
15
+ # Do not use connector_spec.connector_of: it only covers SPEC'd tables and calls
16
+ # Amazon "amazon", not "amazon_sp" (D-718, owned by lane D). Definition.source is
17
+ # "Automation" and field.source is "overlay"; the spawn prefix carries the source.
18
+ SOURCE_PREFIXES = (("ut_odoo_", "odoo"), ("ut_amzn_", "amazon_sp"))
19
+ _A1 = re.compile(r"[A-Z]+[1-9][0-9]*\Z")
20
+
21
+
22
+ def source_of_database(database_key):
23
+ return next((source for prefix, source in SOURCE_PREFIXES
24
+ if str(database_key or "").startswith(prefix)), None)
25
+
26
+
27
+ def _literal(value):
28
+ return {"kind": "literal", "text": str(value), "value": value}
29
+
30
+
31
+ def _formula(value):
32
+ return {"kind": "formula", "formula": value}
33
+
34
+
35
+ def _month(offset):
36
+ today = date.today()
37
+ year, month = divmod(today.year * 12 + today.month - 1 + offset, 12)
38
+ return date(year, month + 1, 1).isoformat()
39
+
40
+
41
+ def _scope(*conditions):
42
+ return {"filter": [{"colId": field, "op": op, "value": value}
43
+ for field, op, value in conditions]}
44
+
45
+
46
+ # C4 has exactly two additions: answers supplies the gallery's short question
47
+ # summary; semantic_fields lets bindings name concepts such as "revenue" rather
48
+ # than tenant column ids. Tenants can map that concept to different source keys.
49
+ # Calendar labels and filters are pinned together in the descriptor, so refreshing
50
+ # an applied workbook never silently moves a labelled period to another month.
51
+ _AS_OF = date.today()
52
+ TEMPLATES = [
53
+ {
54
+ "key": "odoo_monthly_sales", "title": "Monthly sales", "source": "odoo",
55
+ "database_hint": "ut_odoo_orders",
56
+ "answers": "How did sales change across the last twelve calendar months?",
57
+ "semantic_fields": {"order_date": ("order_date",), "revenue": ("amount_untaxed",)},
58
+ "sheets": [{"name": "Monthly sales", "cells": {
59
+ "A1": _literal("Month"), "B1": _literal("Sales"),
60
+ **{f"A{row}": _literal(_month(row - 13)[:7]) for row in range(2, 14)},
61
+ "A14": _literal("Total"), "B14": _formula("=SUM(B2:B13)"),
62
+ }}],
63
+ "bindings": [{"sheet": 0, "addr": f"B{row}", "field": "revenue", "fn": "sum",
64
+ "scope": _scope(("order_date", "gte", _month(row - 13)),
65
+ ("order_date", "lt", _month(row - 12)))}
66
+ for row in range(2, 14)],
67
+ "formats": [{"sheet": 0, "addr": f"B{row}", "kind": "currency"}
68
+ for row in range(2, 15)],
69
+ },
70
+ {
71
+ "key": "odoo_receivables_aging", "title": "Receivables aging", "source": "odoo",
72
+ "database_hint": "ut_odoo_invoices",
73
+ "answers": "How much remains unpaid in each overdue age band?",
74
+ "semantic_fields": {"due_date": ("due_date",), "open_amount": ("residual",),
75
+ "customer": ("customer",)},
76
+ "sheets": [{"name": "Receivables aging", "cells": {
77
+ "A1": _literal("Age band"), "B1": _literal("Open amount"),
78
+ "A2": _literal("Not yet due"), "A3": _literal("1 to 30 days overdue"),
79
+ "A4": _literal("31 to 60 days overdue"), "A5": _literal("61 to 90 days overdue"),
80
+ "A6": _literal("Over 90 days overdue"), "A7": _literal("No due date"),
81
+ "A8": _literal("Total open"), "B8": _formula("=SUM(B2:B7)"),
82
+ "A10": _literal("Invoices with an open balance"),
83
+ "A12": _literal("Aging date"), "B12": _literal(_AS_OF.isoformat()),
84
+ }}],
85
+ "bindings": [
86
+ {"sheet": 0, "addr": "B2", "field": "open_amount", "fn": "sum",
87
+ "scope": _scope(("due_date", "gte", _AS_OF.isoformat()),
88
+ ("open_amount", "gt", "0"))},
89
+ *[{"sheet": 0, "addr": f"B{row}", "field": "open_amount", "fn": "sum",
90
+ "scope": _scope(("due_date", "gte", (_AS_OF - timedelta(days=end)).isoformat()),
91
+ ("due_date", "lt", (_AS_OF - timedelta(days=start)).isoformat()),
92
+ ("open_amount", "gt", "0"))}
93
+ for row, start, end in ((3, 0, 30), (4, 30, 60), (5, 60, 90))],
94
+ {"sheet": 0, "addr": "B6", "field": "open_amount", "fn": "sum",
95
+ "scope": _scope(("due_date", "lt", (_AS_OF - timedelta(days=90)).isoformat()),
96
+ ("due_date", "isNotEmpty", ""), ("open_amount", "gt", "0"))},
97
+ {"sheet": 0, "addr": "B7", "field": "open_amount", "fn": "sum",
98
+ "scope": _scope(("due_date", "isEmpty", ""), ("open_amount", "gt", "0"))},
99
+ {"sheet": 0, "addr": "B10", "field": "customer", "fn": "count",
100
+ "scope": _scope(("open_amount", "gt", "0"))},
101
+ ],
102
+ "formats": [{"sheet": 0, "addr": f"B{row}", "kind": "currency"}
103
+ for row in range(2, 9)] + [
104
+ {"sheet": 0, "addr": "B10", "kind": "number"},
105
+ {"sheet": 0, "addr": "B12", "kind": "date"}],
106
+ },
107
+ {
108
+ "key": "odoo_margin_by_product", "title": "Margin by product", "source": "odoo",
109
+ "database_hint": "ut_odoo_order_lines",
110
+ "answers": "What revenue and margin do product lines generate?",
111
+ "semantic_fields": {"product": ("product",), "margin": ("margin",),
112
+ "revenue": ("price_subtotal",)},
113
+ "sheets": [{"name": "Product margins", "cells": {
114
+ "A1": _literal("Products"), "B1": _literal("Revenue"),
115
+ "C1": _literal("Margin"), "D1": _literal("Margin rate"),
116
+ "A2": _literal("All products"), "D2": _formula("=IF(B2=0,0,C2/B2)"),
117
+ "A4": _literal("Product lines"),
118
+ }}],
119
+ "bindings": [
120
+ {"sheet": 0, "addr": "B2", "field": "revenue", "fn": "sum"},
121
+ {"sheet": 0, "addr": "C2", "field": "margin", "fn": "sum"},
122
+ {"sheet": 0, "addr": "B4", "field": "product", "fn": "count"},
123
+ ],
124
+ "formats": [{"sheet": 0, "addr": addr, "kind": kind}
125
+ for addr, kind in (("B2", "currency"), ("C2", "currency"),
126
+ ("D2", "percent"), ("B4", "number"))],
127
+ },
128
+ {
129
+ "key": "amazon_settlement_summary", "title": "Settlement summary", "source": "amazon_sp",
130
+ "database_hint": "ut_amzn_settlements",
131
+ "answers": "What net amount and transaction count do settlement lines contain?",
132
+ # V2 flat-file columns are normalized by amazon_store._snake. Sum the
133
+ # line amount, never a repeated settlement-level total_amount header.
134
+ "semantic_fields": {"settlement": ("settlement_id",), "net_amount": ("amount",)},
135
+ "sheets": [{"name": "Settlement summary", "cells": {
136
+ "A1": _literal("Measure"), "B1": _literal("Value"),
137
+ "A2": _literal("Net settlement amount"), "A3": _literal("Settlement lines"),
138
+ "A4": _literal("Average amount per line"), "B4": _formula("=IF(B3=0,0,B2/B3)"),
139
+ }}],
140
+ "bindings": [{"sheet": 0, "addr": "B2", "field": "net_amount", "fn": "sum"},
141
+ {"sheet": 0, "addr": "B3", "field": "settlement", "fn": "count"}],
142
+ "formats": [{"sheet": 0, "addr": addr, "kind": kind}
143
+ for addr, kind in (("B2", "number"), ("B3", "number"), ("B4", "number"))],
144
+ },
145
+ ]
146
+
147
+
148
+ def template(key):
149
+ return next((row for row in TEMPLATES if row["key"] == key), None)
150
+
151
+
152
+ def templates_for_sources(sources):
153
+ allowed = set(sources)
154
+ return [row for row in TEMPLATES if row["source"] in allowed]
155
+
156
+
157
+ class TemplateRefusal(Exception):
158
+ def __init__(self, code, *, missing=(), detail=""):
159
+ self.code = code
160
+ self.missing = tuple(missing)
161
+ self.detail = detail
162
+ super().__init__(self.sentence())
163
+
164
+ def sentence(self):
165
+ if self.code == "template_fields_missing":
166
+ return "This database is missing fields required by the template: " + ", ".join(self.missing) + "."
167
+ return self.detail or "This sheet template could not be applied."
168
+
169
+
170
+ def resolve_fields(template, field_keys):
171
+ available = set(field_keys)
172
+ resolved, missing = {}, []
173
+ for semantic, candidates in template["semantic_fields"].items():
174
+ chosen = next((key for key in candidates if key in available), None)
175
+ if chosen is None:
176
+ missing.append(semantic)
177
+ else:
178
+ resolved[semantic] = chosen
179
+ if missing:
180
+ raise TemplateRefusal("template_fields_missing", missing=missing)
181
+ return resolved
182
+
183
+
184
+ def _resolved_scope(value, resolved):
185
+ if isinstance(value, list):
186
+ return [_resolved_scope(item, resolved) for item in value]
187
+ if isinstance(value, dict):
188
+ return {key: resolved[item] if key == "colId" else _resolved_scope(item, resolved)
189
+ for key, item in value.items()}
190
+ return deepcopy(value)
191
+
192
+
193
+ def build_cells(template, resolved, database_key):
194
+ # The ticket explicitly uses modules.sheet's existing binding normalizer;
195
+ # no API or calculation runtime is imported into this data layer.
196
+ from modules.sheet import clean_binding
197
+
198
+ tabs = [(i, tab["name"], deepcopy(tab["cells"])) for i, tab in enumerate(template["sheets"])]
199
+
200
+ def target(entry):
201
+ index, addr = entry["sheet"], entry["addr"]
202
+ if type(index) is not int or not 0 <= index < len(tabs) or not _A1.fullmatch(addr):
203
+ raise TemplateRefusal("template_invalid", detail="The template names an invalid sheet or cell.")
204
+ return tabs[index][2], addr
205
+
206
+ for entry in template["bindings"]:
207
+ cells, addr = target(entry)
208
+ binding = {"database": database_key,
209
+ "aggregate": {"fn": entry["fn"], "field": resolved[entry["field"]]},
210
+ "scope": _resolved_scope(entry.get("scope", {"filter": []}), resolved)}
211
+ if "period" in entry:
212
+ binding["period"] = deepcopy(entry["period"])
213
+ cells[addr] = {**cells.get(addr, {}), "kind": "bound", "binding": clean_binding(binding)}
214
+ for entry in template["formats"]:
215
+ cells, addr = target(entry)
216
+ cell = cells.setdefault(addr, {"kind": "empty"})
217
+ style = cell.get("style", {})
218
+ cell["style"] = {**style, "format": {**style.get("format", {}), "kind": entry["kind"]}}
219
+ for _, _, cells in tabs:
220
+ for addr, cell in cells.items():
221
+ if not _A1.fullmatch(addr):
222
+ raise TemplateRefusal("template_invalid", detail="The template names an invalid cell: " + addr + ".")
223
+ cells[addr] = sheets.clean_cell(cell, addr)
224
+ return tabs
225
+
226
+
227
+ def apply_template(st, key, database_key, *, name="", created_by=""):
228
+ descriptor = template(key)
229
+ if descriptor is None:
230
+ raise TemplateRefusal("unknown_sheet_template", detail="That sheet template does not exist.")
231
+ definition = user_tables.all_defs(st).get(database_key)
232
+ if definition is None:
233
+ raise TemplateRefusal("unknown_database", detail="That database does not exist.")
234
+ if source_of_database(database_key) != descriptor["source"]:
235
+ raise TemplateRefusal("template_source_mismatch", detail="That database uses a different connector from this template.")
236
+ resolved = resolve_fields(descriptor, (field["key"] for field in definition.get("fields", [])))
237
+ prepared = build_cells(descriptor, resolved, database_key)
238
+ # Validate tab names, extents and every cell before the first store write.
239
+ checked = sheets.migrate_workbook({"sheets": [
240
+ {"name": tab_name, "cells": cells} for _, tab_name, cells in prepared]})
241
+ book = sheets.create_workbook(st, name=name or descriptor["title"], created_by=created_by)
242
+ try:
243
+ tabs = [{**tab, "cells": {}} for tab in checked["sheets"]]
244
+ book = sheets.put_workbook(st, book["id"], {"name": book["name"], "sheets": tabs, "rev": book["rev"]})
245
+ for index, _, cells in prepared:
246
+ result = sheets.patch_cells(st, book["id"], book["sheets"][index]["id"], cells)
247
+ if result.get("refused"):
248
+ addresses = [str(item["addr"]) for item in result["refused"]]
249
+ raise TemplateRefusal("template_cells_refused", detail="The template could not apply cells: " + ", ".join(addresses) + ".")
250
+ return sheets.get_workbook(st, book["id"])
251
+ except Exception:
252
+ sheets.delete_workbook(st, book["id"])
253
+ raise
platform/core/users.py CHANGED
@@ -488,8 +488,8 @@ def note_login_failure(identifier, now=None):
488
 
489
  def _note(doc):
490
  doc = dict(doc) if isinstance(doc, dict) else {}
491
- # Keep the security document bounded under random-identifier abuse. An active lock is
492
- # never pruned, even if a malformed/old ``last_failed_at`` accompanies it.
493
  retained = {}
494
  for stored_key, value in doc.items():
495
  if not isinstance(value, dict):
@@ -520,12 +520,24 @@ def note_login_failure(identifier, now=None):
520
  doc[key] = {'count': count, 'last_failed_at': now, 'locked_until': until}
521
 
522
  if len(doc) > _LOGIN_LOCKOUT_MAX_TRACKED:
523
- # Discard expired/incomplete budgets before active locks. A pathological set of more
524
- # than 2,048 simultaneous active identifiers still evicts oldest-first: the document
525
- # stays bounded rather than becoming an attacker-controlled memory allocation.
526
- oldest = sorted(doc, key=lambda stored_key: (
527
- float((doc.get(stored_key) or {}).get('locked_until') or 0) > now,
528
- float((doc.get(stored_key) or {}).get('last_failed_at') or 0)))
 
 
 
 
 
 
 
 
 
 
 
 
529
  excess = len(doc) - _LOGIN_LOCKOUT_MAX_TRACKED
530
  for stored_key in [candidate for candidate in oldest if candidate != key][:excess]:
531
  doc.pop(stored_key, None)
 
488
 
489
  def _note(doc):
490
  doc = dict(doc) if isinstance(doc, dict) else {}
491
+ # Prune stale budgets under random-identifier abuse. An active lock is never pruned,
492
+ # even if a malformed/old ``last_failed_at`` accompanies it.
493
  retained = {}
494
  for stored_key, value in doc.items():
495
  if not isinstance(value, dict):
 
520
  doc[key] = {'count': count, 'last_failed_at': now, 'locked_until': until}
521
 
522
  if len(doc) > _LOGIN_LOCKOUT_MAX_TRACKED:
523
+ # W59-T33 / instruction 24: the size target cannot shorten a thirty-minute lock.
524
+ # Only expired/incomplete budgets may be evicted. If active locks fill the target,
525
+ # retain them plus this attempt's budget until expiry permits pruning again.
526
+ # ⭐⭐ THIS REVERSES A DELIBERATE EARLIER CHOICE, SO KEEP BOTH REASONS. The previous
527
+ # rule sorted active locks last but still evicted them once the document passed the
528
+ # target, to stop a random-identifier flood becoming an attacker-controlled
529
+ # allocation. The cost of that rule is a BYPASS of the control itself: an attacker
530
+ # who wants to keep guessing one account sprays enough other identifiers to evict
531
+ # that account's lock, and a lock that can be evicted is not the thirty-minute lock
532
+ # Amazon's baseline was told exists. The accepted cost of the new rule is the one the
533
+ # old comment named: while more than 2,048 locks are simultaneously ACTIVE the
534
+ # document grows past its target. That is bounded in practice, because every active
535
+ # lock costs ten failed proofs and each burns a PBKDF2 hash, and it self-corrects
536
+ # within thirty minutes as locks expire and become prunable again.
537
+ oldest = sorted(
538
+ (stored_key for stored_key in doc
539
+ if float((doc.get(stored_key) or {}).get('locked_until') or 0) <= now),
540
+ key=lambda stored_key: float((doc.get(stored_key) or {}).get('last_failed_at') or 0))
541
  excess = len(doc) - _LOGIN_LOCKOUT_MAX_TRACKED
542
  for stored_key in [candidate for candidate in oldest if candidate != key][:excess]:
543
  doc.pop(stored_key, None)
platform/harness/amazon_client.py CHANGED
@@ -298,6 +298,135 @@ ROLES_TAKEN = (
298
  )
299
  ROLES_REFUSED = ("Buyer Communication", "Buyer Solicitation")
300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  _UA = "AIOS-Loopable/1.0 (+read-only)"
302
  _TIMEOUT = 20
303
 
@@ -306,6 +435,14 @@ class AmazonError(RuntimeError):
306
  """Any refusal from LWA or SP-API, already stripped of anything secret."""
307
 
308
 
 
 
 
 
 
 
 
 
309
  class AmazonThrottled(AmazonError):
310
  """An SP-API 429, with an optional Retry-After delay in seconds."""
311
 
@@ -331,6 +468,36 @@ def _safe(url):
331
  return "<url>"
332
 
333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  def _retry(attempt_fn, what, *, sleep=time.sleep, rand=random.random, exhausted_fix=None):
335
  """Retry only SP-API throttling; return successes and propagate other refusals unchanged."""
336
  for n in range(1, RETRY_MAX_ATTEMPTS + 1):
@@ -389,6 +556,8 @@ def _pace_entity(name, interval, *, sleep=time.sleep, now=time.monotonic):
389
 
390
 
391
  def _post_form(url, data, timeout=_TIMEOUT):
 
 
392
  body = urllib.parse.urlencode(data).encode("ascii")
393
  req = urllib.request.Request(url, data=body, method="POST")
394
  req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
@@ -442,6 +611,7 @@ def _request(path, token, region=DEFAULT_REGION, method="GET", timeout=_TIMEOUT,
442
  """
443
  if str(method).upper() != "GET":
444
  raise AmazonError("this connector is read-only: only GET is permitted")
 
445
 
446
  def attempt():
447
  """One raw read-only SP-API attempt, with no retry or pacing policy."""
@@ -500,6 +670,7 @@ def _request(path, token, region=DEFAULT_REGION, method="GET", timeout=_TIMEOUT,
500
  def _competitive_summary_batch(token, asins, marketplace_id, region=DEFAULT_REGION,
501
  timeout=_TIMEOUT, sandbox=False):
502
  """Read one fixed `getCompetitiveSummary` batch. -> its response list."""
 
503
  items = [str(asin or "").strip() for asin in (asins or ()) if str(asin or "").strip()]
504
  if not 1 <= len(items) <= COMPETITIVE_SUMMARY_BATCH_SIZE:
505
  raise AmazonError(
@@ -669,6 +840,8 @@ def _create_report(token, report_type, marketplace_ids, region=DEFAULT_REGION,
669
  ⛔ NO `path` PARAMETER, ON PURPOSE. See `_REPORTS_CREATE_PATH` above: the whole safety argument
670
  is that this function can reach exactly one operation and a caller cannot redirect it.
671
  """
 
 
672
  def attempt():
673
  """One raw attempt at the declared report-creation POST."""
674
  base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
@@ -745,6 +918,8 @@ def report_document(fields, report_type, start=None, end=None, options=None,
745
  `IN_PROGRESS` after `max_wait` raises with the reportId in the message, so the next call can
746
  resume from it rather than paying for the whole build again.
747
  """
 
 
748
  say = log or (lambda *_a, **_k: None)
749
  token = access_token(fields, timeout=timeout)
750
  region = str((fields or {}).get("region") or DEFAULT_REGION)
@@ -801,6 +976,8 @@ def _download_document(url, compression="", timeout=120):
801
  one smart quote. Decoded with replacement, and that is a deliberate lossy choice on a
802
  presentation field rather than on a number.
803
  """
 
 
804
  req = urllib.request.Request(url, method="GET")
805
  req.add_header("User-Agent", _UA)
806
  try:
 
298
  )
299
  ROLES_REFUSED = ("Buyer Communication", "Buyer Solicitation")
300
 
301
+ #: W59-T39: the connector's approved operation scope, not Amazon's entire role catalogue.
302
+ #: Join the report roster rather than maintaining another copy of its role labels. A compound
303
+ #: label describes TWO data legs: inventory uses Fulfillment for its report and AWD for its
304
+ #: entity read; pricing uses Brand Analytics for its report and Pricing for its entity read.
305
+ #: Keep those source labels intact and expose both roles, without granting either entity role
306
+ #: the other role's report access.
307
+ REPORT_ROLES = {
308
+ table: tuple(spec["role"].replace(" / ", " + ").split(" + "))
309
+ for table, spec in REPORT_TYPES.items()
310
+ }
311
+ _REPORT_ROLE_INDEX = {"inventory": 0, "pricing": 1}
312
+ _BULK_REPORT_ROLES = tuple(dict.fromkeys(
313
+ roles[_REPORT_ROLE_INDEX.get(table, 0)] for table, roles in REPORT_ROLES.items()))
314
+ _APPROVED_REPORT_TYPES = tuple(dict.fromkeys(
315
+ spec[key] for spec in REPORT_TYPES.values() for key in ("report", "report_incremental")
316
+ if spec.get(key)))
317
+
318
+ #: Exact method/path pairs. Braced ids match ONE opaque path segment, never a suffix, query,
319
+ #: escaped slash or traversal. The two POSTs only request a report or wrap fixed read-only GETs.
320
+ #: LWA, presigned documents and the schema module's public GitHub refresh are not SP-API
321
+ #: operations. The gate enumerates those transports separately; they confer no operation scope.
322
+ OPERATIONS = {
323
+ "createReport": {
324
+ "name": "createReport", "roles": _BULK_REPORT_ROLES, "method": "POST",
325
+ "path": "reports/2021-06-30/reports", "report_types": _APPROVED_REPORT_TYPES,
326
+ },
327
+ "getReport": {
328
+ "name": "getReport", "roles": _BULK_REPORT_ROLES, "method": "GET",
329
+ "path": "reports/2021-06-30/reports/{reportId}",
330
+ },
331
+ "getReportDocument": {
332
+ "name": "getReportDocument", "roles": _BULK_REPORT_ROLES, "method": "GET",
333
+ "path": "reports/2021-06-30/documents/{documentId}",
334
+ },
335
+ "getMarketplaceParticipations": {
336
+ "name": "getMarketplaceParticipations", "roles": ("Selling Partner Insights",),
337
+ "method": "GET", "path": "sellers/v1/marketplaceParticipations",
338
+ },
339
+ "getCompetitiveSummary": {
340
+ "name": "getCompetitiveSummary", "roles": ("Pricing",), "method": "POST",
341
+ "path": "batches/products/pricing/2022-05-01/items/competitiveSummary",
342
+ },
343
+ "listInventory": {
344
+ "name": "listInventory", "roles": ("Amazon Warehousing and Distribution",),
345
+ "method": "GET", "path": "awd/2024-05-09/inventory",
346
+ },
347
+ }
348
+
349
+ #: Answer "what does this approved role let this connector read?" directly from data.
350
+ #: The report-side roles above are derived from REPORT_TYPES, including its compound labels.
351
+ ROLE_OPERATIONS = {
352
+ role: tuple(name for name, operation in OPERATIONS.items() if role in operation["roles"])
353
+ for role in ROLES_TAKEN
354
+ }
355
+
356
+ # Containment record for the Amazon approval-control series, measured 2026-09-13.
357
+ # Git ancestry is not the record here: a packed wave container carries no source
358
+ # history. The laptop ancestry check lives in intake finding F23 in
359
+ # AutoWiki/research/ideation/wave59-intake.md.
360
+ # Each entry claims what exists, never that the control is correct. `contained`
361
+ # records full containment; False preserves a documented partial contribution.
362
+ # `checkable` means the module can be imported from platform/ without reaching up.
363
+ # False is an honest ownership boundary, not a gap to paper over: platform must
364
+ # not import the web API, and a Dockerfile is not an importable Python module.
365
+ # This is data only; resolving symbols belongs to the checker (W59-T39).
366
+ APPROVAL_CONTROLS = {
367
+ "f1d803d": {
368
+ "carries": "shared persistent login-attempt lockout",
369
+ "module": "platform/core/users.py",
370
+ "symbol": "LOGIN_LOCKOUT_BUCKET",
371
+ "contained": True,
372
+ "checkable": True,
373
+ },
374
+ "be68048": {
375
+ "carries": "password minimum age in the password policy",
376
+ "module": "platform/core/users.py",
377
+ "symbol": "PASSWORD_MIN_AGE_DAYS",
378
+ "contained": True,
379
+ "checkable": True,
380
+ },
381
+ "83bfed7": {
382
+ "carries": "the audited lockfile is the dependency boundary",
383
+ "module": "aios-web/Dockerfile",
384
+ "symbol": None,
385
+ "contained": False,
386
+ "checkable": False,
387
+ "note": (
388
+ "The lockfile COPY at aios-web/Dockerfile:37 stands; the npm ci half "
389
+ "does not: :38 is npm install --no-audit --no-fund --ignore-scripts. "
390
+ "The cause is a Windows-resolved lockfile, booked as HARNESS W-170. "
391
+ "Dockerfile and the lockfile belong to lane F in Wave 59. "
392
+ "This web build control cannot be resolved here because Dockerfile "
393
+ "is not an importable Python module."
394
+ ),
395
+ },
396
+ "849067e": {
397
+ "carries": "Pricing and AWD read operations, and the eight approved roles",
398
+ "module": "platform/harness/amazon_client.py",
399
+ "symbol": "ROLES_TAKEN",
400
+ "contained": True,
401
+ "checkable": True,
402
+ },
403
+ "7e556f8": {
404
+ "carries": "exact-tenant raw-mirror purge",
405
+ "module": "platform/harness/amazon_store.py",
406
+ "symbol": "purge",
407
+ "contained": True,
408
+ "checkable": True,
409
+ },
410
+ "9c9454b": {
411
+ "carries": "origin attribution on materialised Amazon tables",
412
+ "module": "aios-web/api/amazon_relational.py",
413
+ "symbol": "source_attribution",
414
+ "contained": True,
415
+ "checkable": False,
416
+ "note": (
417
+ "Owned by the web API layer, which platform may not import; "
418
+ "source_attribution cannot be resolved from this layer."
419
+ ),
420
+ },
421
+ "df1252b": {
422
+ "carries": "origin attribution on Sheet workbooks and the scope cache",
423
+ "module": "platform/core/sheets.py",
424
+ "symbol": "AMAZON_DATA_ORIGIN_NAME",
425
+ "contained": True,
426
+ "checkable": True,
427
+ },
428
+ }
429
+
430
  _UA = "AIOS-Loopable/1.0 (+read-only)"
431
  _TIMEOUT = 20
432
 
 
435
  """Any refusal from LWA or SP-API, already stripped of anything secret."""
436
 
437
 
438
+ class AmazonOperationRefused(AmazonError):
439
+ """A local scope refusal, never a throttle and never eligible for throttling retries."""
440
+
441
+ def __init__(self, operation):
442
+ super().__init__(
443
+ f"Refused {_safe(operation)}: this connector is limited to the approved read-only set")
444
+
445
+
446
  class AmazonThrottled(AmazonError):
447
  """An SP-API 429, with an optional Retry-After delay in seconds."""
448
 
 
468
  return "<url>"
469
 
470
 
471
+ def operation_for(method, path):
472
+ """Resolve an exact approved operation, or None. Query parameters belong in **params."""
473
+ parts = str(path).lstrip("/").split("/")
474
+ for operation in OPERATIONS.values():
475
+ template = operation["path"].split("/")
476
+ if str(method).upper() != operation["method"] or len(parts) != len(template):
477
+ continue
478
+ if all(
479
+ (bool(part) and part not in (".", "..")
480
+ and all(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."
481
+ for c in part))
482
+ if segment.startswith("{") and segment.endswith("}") else part == segment
483
+ for part, segment in zip(parts, template)
484
+ ):
485
+ return operation
486
+ return None
487
+
488
+
489
+ def require_operation(method, path, *, report_type=None):
490
+ """Fail closed before constructing any URL or touching a transport."""
491
+ operation = operation_for(method, path)
492
+ if operation is None:
493
+ raise AmazonOperationRefused(f"{str(method).upper()} {_safe(path)}")
494
+ # A Reports URL alone is insufficient: restricted report families use this same POST.
495
+ # Admit only the bulk flavors joined from the seven declared tables, including incrementals.
496
+ if report_type is not None and str(report_type) not in operation.get("report_types", ()):
497
+ raise AmazonOperationRefused(f"{operation['name']} report {report_type}")
498
+ return operation
499
+
500
+
501
  def _retry(attempt_fn, what, *, sleep=time.sleep, rand=random.random, exhausted_fix=None):
502
  """Retry only SP-API throttling; return successes and propagate other refusals unchanged."""
503
  for n in range(1, RETRY_MAX_ATTEMPTS + 1):
 
556
 
557
 
558
  def _post_form(url, data, timeout=_TIMEOUT):
559
+ # LWA exchanges credentials at api.amazon.com, not an SP-API operation. Its sole caller fixes
560
+ # LWA_TOKEN_URL; the connector-wide gate checks that call separately from OPERATIONS.
561
  body = urllib.parse.urlencode(data).encode("ascii")
562
  req = urllib.request.Request(url, data=body, method="POST")
563
  req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
 
611
  """
612
  if str(method).upper() != "GET":
613
  raise AmazonError("this connector is read-only: only GET is permitted")
614
+ require_operation(method, path)
615
 
616
  def attempt():
617
  """One raw read-only SP-API attempt, with no retry or pacing policy."""
 
670
  def _competitive_summary_batch(token, asins, marketplace_id, region=DEFAULT_REGION,
671
  timeout=_TIMEOUT, sandbox=False):
672
  """Read one fixed `getCompetitiveSummary` batch. -> its response list."""
673
+ require_operation("POST", _COMPETITIVE_SUMMARY_BATCH_PATH)
674
  items = [str(asin or "").strip() for asin in (asins or ()) if str(asin or "").strip()]
675
  if not 1 <= len(items) <= COMPETITIVE_SUMMARY_BATCH_SIZE:
676
  raise AmazonError(
 
840
  ⛔ NO `path` PARAMETER, ON PURPOSE. See `_REPORTS_CREATE_PATH` above: the whole safety argument
841
  is that this function can reach exactly one operation and a caller cannot redirect it.
842
  """
843
+ require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
844
+
845
  def attempt():
846
  """One raw attempt at the declared report-creation POST."""
847
  base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
 
918
  `IN_PROGRESS` after `max_wait` raises with the reportId in the message, so the next call can
919
  resume from it rather than paying for the whole build again.
920
  """
921
+ # Refuse an undeclared report even before its LWA exchange; _create_report guards its own door.
922
+ require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
923
  say = log or (lambda *_a, **_k: None)
924
  token = access_token(fields, timeout=timeout)
925
  region = str((fields or {}).get("region") or DEFAULT_REGION)
 
976
  one smart quote. Decoded with replacement, and that is a deliberate lossy choice on a
977
  presentation field rather than on a number.
978
  """
979
+ # This is the presigned URL returned by getReportDocument, not an SP-API operation. Do not
980
+ # apply OPERATIONS here: its host and signature belong to Amazon's document download service.
981
  req = urllib.request.Request(url, method="GET")
982
  req.add_header("User-Agent", _UA)
983
  try:
platform/harness/amazon_schema.py CHANGED
@@ -265,6 +265,120 @@ def columns_for(table):
265
  return [(c["name"], c.get("type") or "VARCHAR") for c in (spec.get("columns") or [])]
266
 
267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  def disclosure():
269
  """What the onboarding screen shows: one row per table, with its provenance and sync date.
270
 
 
265
  return [(c["name"], c.get("type") or "VARCHAR") for c in (spec.get("columns") or [])]
266
 
267
 
268
+ # --------------------------------------------------------------------------- contract C1
269
+
270
+ #: The one translation from C1's short report keys to the authored database namespace.
271
+ #: A-C1-KEYS preserves stored enablement keys and route paths while lane D adopts this map.
272
+ DATABASE_PREFIX = "ut_amzn_"
273
+
274
+
275
+ def _table_spec(table, identity, relationships=(), *, grain="entity", line_discriminator=None):
276
+ """Build the common descriptor fields from the LOCAL pin, never a vendor call."""
277
+ return {
278
+ "columns": [{"name": name, "type": kind} for name, kind in columns_for(table)],
279
+ "columns_source": {
280
+ "path": "platform/harness/proto/amazon-report-schemas.json",
281
+ "reader": "amazon_schema.columns_for",
282
+ "provenance": PROVENANCE[table],
283
+ "assumption": (
284
+ "A-QI14: This wave declares from REPORT_TYPES and the pinned artifacts. "
285
+ "The five measured_at_sync tables' columns are re-measured against the first "
286
+ "production sync during the deferred QI13 hotfix (intake RDA6)."),
287
+ },
288
+ "row_identity": identity,
289
+ "row_identity_mode": "composite",
290
+ "row_identity_missing": "require_all",
291
+ "row_identity_alternatives": (),
292
+ "row_identity_status": "declared_pending_first_production_sync",
293
+ "grain": grain,
294
+ "line_discriminator": line_discriminator,
295
+ "line_discriminator_source": ({
296
+ "kind": "declared_mirror_metadata",
297
+ "document_column": "_report_document_id",
298
+ "note": (
299
+ "Sync must retain the report document ID and the one-based parsed row position "
300
+ "before filtering or deduplication, including identical repeated lines. These "
301
+ "are proposed mirror metadata, not measured Amazon header columns. Replaying "
302
+ "one document keeps its positions; reconciling overlapping documents is a "
303
+ "separate sync responsibility. Never fall back to the order or settlement ID."),
304
+ } if line_discriminator else None),
305
+ "relationships": relationships,
306
+ "provenance": PROVENANCE[table],
307
+ "read_through": True,
308
+ "row_cap": None,
309
+ "read_through_status": "declared_pending_consumer_wiring",
310
+ "read_through_reason": (
311
+ "Standing rule 1: these are connector records with records_mutable=False. "
312
+ "Serve history read-through from the mirror without a record cap."),
313
+ }
314
+
315
+
316
+ #: ⭐⭐ TABLE_SPECS IS CONTRACT C1'S SINGLE SOURCE OF TRUTH. One entry per REPORT_TYPES key,
317
+ #: checked strictly by verify_amazon. Columns and types come ONLY through columns_for's pinned
318
+ #: catalogue; the five measured_at_sync lists remain EMPTY. columns_source carries A-QI14 in the
319
+ #: descriptor itself, so a consumer cannot mistake this wave's declaration for production evidence.
320
+ #:
321
+ #: ⛔ IDENTITIES ARE COMPOSITES, NEVER FALLING PREFERENCES. Every component participates and no
322
+ #: proper subset is an alternative identity FOR THAT TABLE. orders is the deduplicated header
323
+ #: (_dedupe_orders), while order_items and settlements retain source lines. An order item ID is
324
+ #: not guaranteed in the flat-file header, and even identical settlement charges must survive:
325
+ #: both line tables therefore declare document + position lineage beside their parent ID. The
326
+ #: lineage columns are proposed MIRROR METADATA, not invented vendor columns in the catalogue.
327
+ #:
328
+ #: ⚠ Identity uniqueness, line metadata and relationship column spellings await the first real
329
+ #: sync. All identities say so, including the two tables with published COLUMN artifacts. Nine
330
+ #: relationships retain BOTH join-column names and short target keys; the gate compares them to
331
+ #: connector_spec.tables_for("amazon"), which amazon_relational still renders. Read-through is a
332
+ #: REQUIRED POLICY, not a claim that the existing materialisation consumer already implements it.
333
+ TABLE_SPECS = {
334
+ "orders": _table_spec("orders", ("amazon_order_id",), (
335
+ ("sku", "listings", "seller_sku", "many_to_one"),
336
+ ), grain="order"),
337
+ "order_items": _table_spec("order_items", (
338
+ "amazon_order_id", "_report_document_id", "_report_row_number",
339
+ ), (
340
+ ("amazon_order_id", "orders", "amazon_order_id", "many_to_one"),
341
+ ("sku", "listings", "seller_sku", "many_to_one"),
342
+ ), grain="line", line_discriminator="_report_row_number"),
343
+ "listings": _table_spec("listings", ("seller_sku",)),
344
+ "settlements": _table_spec("settlements", (
345
+ "settlement_id", "_report_document_id", "_report_row_number",
346
+ ), (
347
+ ("amazon_order_id", "orders", "amazon_order_id", "many_to_one"),
348
+ ("sku", "listings", "seller_sku", "many_to_one"),
349
+ ), grain="line", line_discriminator="_report_row_number"),
350
+ "inventory": _table_spec("inventory", ("asin", "fnsku", "msku"), (
351
+ ("msku", "listings", "seller_sku", "many_to_one"),
352
+ ("asin", "listings", "asin1", "many_to_one"),
353
+ )),
354
+ "pricing": _table_spec("pricing", ("parent_asin", "child_asin", "sku"), (
355
+ ("child_asin", "listings", "asin1", "many_to_one"),
356
+ ("sku", "listings", "seller_sku", "many_to_one"),
357
+ )),
358
+ "brand_analytics": _table_spec("brand_analytics", (
359
+ "department_name", "search_term", "clicked_asin", "click_share_rank",
360
+ )),
361
+ }
362
+
363
+
364
+ def row_identity_for(table, row):
365
+ """Evaluate the declared full composite. Missing lineage is an error, never a parent ID.
366
+
367
+ This is a descriptor evaluator, not a production uniqueness measurement or a sync adapter.
368
+ Return a tuple so delimiters inside values cannot merge two different component sequences.
369
+ """
370
+ spec = TABLE_SPECS[table]
371
+ if spec["row_identity_mode"] != "composite" or spec["row_identity_missing"] != "require_all":
372
+ raise ValueError(f"{table}: unsupported row identity policy")
373
+ identity = spec["row_identity"]
374
+ if not identity or spec["row_identity_alternatives"]:
375
+ raise ValueError(f"{table}: exactly one complete row identity is required")
376
+ missing = [name for name in identity if row.get(name) in (None, "")]
377
+ if missing:
378
+ raise ValueError(f"{table}: missing declared row identity components: {', '.join(missing)}")
379
+ return tuple(row[name] for name in identity)
380
+
381
+
382
  def disclosure():
383
  """What the onboarding screen shows: one row per table, with its provenance and sync date.
384
 
platform/harness/amazon_store.py CHANGED
@@ -45,8 +45,12 @@ import csv
45
  import io
46
  import json
47
  import os
 
48
  import sys
 
49
  import time
 
 
50
  from datetime import datetime, timedelta, timezone
51
  from pathlib import Path
52
 
@@ -66,6 +70,63 @@ PREFIX = "amzn_"
66
  TABLES = ("orders", "order_items", "listings", "settlements", "inventory",
67
  "pricing", "brand_analytics")
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  #: Durable proof that the two non-report role operations actually ran. A report-backed table can
70
  #: contain rows while one of these role grants is still missing, so table presence alone is not
71
  #: evidence that Pricing or AWD was authorized.
@@ -91,6 +152,21 @@ DEFAULT_BACKFILL_DAYS = int(os.environ.get("AMAZON_BACKFILL_DAYS") or 730)
91
  #: ⚠ AMAZON'S OWN CEILING, NOT OURS, and it is why a backfill is many reports rather than one.
92
  MAX_WINDOW_DAYS = 30
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  #: Columns that must be text whatever they look like. An Amazon order id is `111-1234567-1234567`
95
  #: and an ASIN is `B0…`; a settlement id is a long decimal that exceeds 2^53. Same ruling as Meta's
96
  #: ids and `ig_id` before it, for the same reason: a float path corrupts them silently.
@@ -140,7 +216,7 @@ def _dedupe(cols):
140
  return out
141
 
142
 
143
- def parse_flat_file(text):
144
  """One Amazon flat-file report document -> `(columns, rows)`, columns MEASURED from its header.
145
 
146
  ⭐ THIS FUNCTION IS WHY NO ORDER, LISTING OR SETTLEMENT COLUMN IS TRANSCRIBED ANYWHERE. Line 1
@@ -163,16 +239,20 @@ def parse_flat_file(text):
163
  cols = _dedupe([_snake(h) for h in header])
164
  width = len(cols)
165
  rows = []
166
- for raw in reader:
 
 
 
 
167
  if not raw or (len(raw) == 1 and not str(raw[0]).strip()):
168
  continue
169
  vals = list(raw[:width]) + [None] * max(0, width - len(raw))
170
- rows.append({c: (v if (v is None or str(v) != "") else None)
171
- for c, v in zip(cols, vals)})
172
- return cols, rows
173
 
174
 
175
- def parse_json_report(text, root):
176
  """One JSON report document -> `(columns, rows)` flattened onto the pinned artifact's names.
177
 
178
  ⚠ THE COLUMN LIST IS THE PINNED SCHEMA'S, NOT THE PAYLOAD'S. Amazon omits null fields from a
@@ -188,8 +268,10 @@ def parse_json_report(text, root):
188
  if isinstance(body, dict):
189
  body = [body]
190
  rows = []
191
- for item in body:
192
- rows.append(_flatten_row(item or {}))
 
 
193
  return sorted({k for r in rows for k in r}), rows
194
 
195
 
@@ -205,11 +287,12 @@ def _flatten_row(obj, prefix=""):
205
  path = f"{prefix}.{k}" if prefix else k
206
  if isinstance(v, dict):
207
  out.update(_flatten_row(v, path))
208
- elif isinstance(v, list):
209
- out[amazon_schema._snake(path)] = json.dumps(v, separators=(",", ":"),
210
- ensure_ascii=False)
211
  else:
212
- out[amazon_schema._snake(path)] = v
 
 
 
 
213
  return out
214
 
215
 
@@ -227,13 +310,16 @@ def _competitive_rows(responses):
227
  return out
228
 
229
 
230
- def _awd_rows(inventory):
231
  """AWD inventory summaries -> flattened rows that remain distinguishable from FBA ledger."""
232
  rows = []
233
- for item in inventory or ():
 
 
 
234
  row = _flatten_row(item or {})
235
  row["inventory_source"] = "AWD"
236
- rows.append(row)
237
  return rows
238
 
239
 
@@ -309,6 +395,8 @@ def _coltype(name, rows=None):
309
  column that is numeric for 500 rows and then carries `N/A` must not make the insert fail after
310
  five tables are already written — the exact failure `meta_store._coltype` was rewritten for.
311
  """
 
 
312
  if name in _FORCE_TEXT:
313
  return "VARCHAR"
314
  if not rows:
@@ -405,15 +493,14 @@ def _ensure(con, table, cols, rows=None, declared=None):
405
 
406
 
407
  def _replace(con, table, cols, types, rows):
408
- """Delete-then-insert for one report window. -> rows written.
409
-
410
- ⚠ A REPORT DOCUMENT IS THE TRUTH FOR ITS WINDOW, so the window is replaced wholesale rather
411
- than merged row by row. That is what makes a re-sync idempotent when Amazon RESTATES a row
412
- (refunds, cancellations and settlement adjustments all arrive as changes to old rows), and it
413
- is why `orders` syncs incrementally by LAST UPDATE rather than by order date.
414
- """
415
  if not rows:
416
  return 0
 
 
 
 
 
417
  ph = ", ".join("?" for _ in cols)
418
  con.executemany(
419
  f'INSERT INTO {table} ({", ".join(chr(34) + c + chr(34) for c in cols)}) VALUES ({ph})',
@@ -453,9 +540,18 @@ def credential(tenant_key="royal-imports", rt=None):
453
  before pasting it. Serving it here would hand one tenant another's Amazon seller account, which
454
  is precisely the elevation `keychain.TENANT_WIDE_TYPES` was written to stop.
455
  """
 
 
 
 
 
 
 
 
 
456
  try:
457
  import core.keychain as kc
458
- return kc.amazon_creds(rt if rt is not None else _runtime_for(tenant_key))
459
  except Exception: # noqa: BLE001
460
  return None
461
 
@@ -524,6 +620,151 @@ def _quoted_identifier(value):
524
  return '"' + str(value).replace('"', '""') + '"'
525
 
526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527
  def _amazon_objects(con):
528
  """Every live mirror object reserved to Amazon by the `amzn_` naming contract."""
529
  rows = con.execute(
@@ -532,7 +773,7 @@ def _amazon_objects(con):
532
  out = []
533
  for name, kind in rows:
534
  name = str(name)
535
- if not name.startswith(PREFIX):
536
  continue
537
  out.append((name, str(kind or "BASE TABLE").upper()))
538
  return sorted(out, key=lambda row: ("VIEW" not in row[1], row[0]))
@@ -545,18 +786,30 @@ def _sync_state_rows(con):
545
  "FROM _sync_state ORDER BY entity").fetchall()]
546
 
547
 
548
- def _purge_mirror(con):
 
 
 
 
 
 
 
 
 
 
549
  """Transactionally delete every `amzn_` mirror object and state marker, then read it back.
550
 
551
  The prefix is the connector's reserved namespace, so this also catches a future Amazon table
552
  that has not yet been added to `TABLES`. Non-Amazon tables and sync markers are snapshotted and
553
  compared inside the transaction and again after commit. No caller supplies a table name.
554
  """
 
555
  objects = _amazon_objects(con)
556
  before_tables = {str(row[0]) for row in con.execute(
557
  "SELECT table_name FROM information_schema.tables "
558
  "WHERE table_schema='main'").fetchall()}
559
- before_other_tables = sorted(name for name in before_tables if not name.startswith(PREFIX))
 
560
  before_state = _sync_state_rows(con)
561
  amazon_state = [str(row[0]) for row in before_state if str(row[0]).startswith(PREFIX)]
562
  other_state = [row for row in before_state if not str(row[0]).startswith(PREFIX)]
@@ -577,12 +830,14 @@ def _purge_mirror(con):
577
  raise RuntimeError("Amazon mirror objects remain inside the purge transaction")
578
  inside_other_tables = sorted(str(row[0]) for row in con.execute(
579
  "SELECT table_name FROM information_schema.tables WHERE table_schema='main'").fetchall()
580
- if not str(row[0]).startswith(PREFIX))
581
  if inside_other_tables != before_other_tables:
582
  raise RuntimeError("a non-Amazon mirror object changed during the purge")
583
  inside_state = _sync_state_rows(con)
584
  if inside_state != other_state:
585
  raise RuntimeError("a non-Amazon sync marker changed during the purge")
 
 
586
  con.execute("COMMIT")
587
  except Exception:
588
  try:
@@ -596,13 +851,14 @@ def _purge_mirror(con):
596
  if str(row[0]).startswith(PREFIX)]
597
  after_other_tables = sorted(str(row[0]) for row in con.execute(
598
  "SELECT table_name FROM information_schema.tables WHERE table_schema='main'").fetchall()
599
- if not str(row[0]).startswith(PREFIX))
600
  after_other_state = [row for row in _sync_state_rows(con)
601
  if not str(row[0]).startswith(PREFIX)]
602
  if residue_objects or residue_state:
603
  raise RuntimeError(
604
  "Amazon mirror purge committed but independent readback found residue")
605
- if after_other_tables != before_other_tables or after_other_state != other_state:
 
606
  raise RuntimeError(
607
  "Amazon mirror purge committed but independent readback found collateral change")
608
  return {
@@ -614,7 +870,56 @@ def _purge_mirror(con):
614
  }
615
 
616
 
617
- def purge(tenant_key, confirmation, rt=None, log=print):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618
  """Permanently remove one tenant's live Amazon mirror after credential revocation.
619
 
620
  This is an operator-only lifecycle control. It never revokes a credential itself and refuses
@@ -631,17 +936,102 @@ def purge(tenant_key, confirmation, rt=None, log=print):
631
  raise RuntimeError(
632
  f"tenant {key!r} has no existing mirror file; refusing to create one as purge proof")
633
  _assert_amazon_credential_revoked(rt)
634
- con, bound_path = _connect_tenant_mirror(key, rt)
635
  try:
636
- result = _purge_mirror(con)
 
 
 
 
 
 
 
 
 
 
 
 
 
637
  finally:
638
- con.close()
639
- report = {"tenant": key, "database": bound_path.name, **result}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640
  log(f" tenant {key}: permanently deleted {result['rows']:,} Amazon mirror rows from "
641
  f"{len(result['tables']):,} tables and {result['syncMarkers']:,} sync markers")
642
  return report
643
 
644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
645
  def _client():
646
  """The SP-API transport, from the DATA LAYER.
647
 
@@ -681,8 +1071,44 @@ def _read_state(con, key):
681
  return {"state": row[0], "rows": row[1], "updated_at": row[2], "detail": row[3]}
682
 
683
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
684
  def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None,
685
- max_wait=900):
686
  """Pull every declared table into the tenant's mirror. -> a report dict.
687
 
688
  Idempotent: a re-sync replaces each window rather than appending. Refuses, loudly and with the
@@ -714,11 +1140,44 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
714
  "reach a grid (standing rule 8, and R3's reconciliation). Use it to prove the client "
715
  "(`connectors_amazon.py --check`) and sync only a PRODUCTION credential.")
716
 
717
- want = [t for t in (tables or TABLES) if t in TABLES]
718
  end = datetime.now(timezone.utc)
719
  start = since or (end - timedelta(days=DEFAULT_BACKFILL_DAYS))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
  con, _path = _connect_tenant_mirror(tenant_key, rt)
721
- report = {"tenant": tenant_key, "tables": {}, "started": _iso(end)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722
 
723
  for table in want:
724
  spec = cx.REPORT_TYPES.get(table) or {}
@@ -731,13 +1190,22 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
731
  prov = amazon_schema.PROVENANCE.get(table, "measured_at_sync")
732
  root = (amazon_schema.ARTIFACTS.get(table) or (None, None))[1]
733
  try:
 
 
734
  written, cols, cleared = 0, [], False
735
  pricing_asins = []
736
  for w0, w1 in _windows(start, end):
 
 
 
 
 
737
  text, meta = cx.report_document(
738
- fields, rtype, start=_iso(w0), end=_iso(w1), max_wait=max_wait, log=log)
 
739
  if prov == "schema_artifact" and root:
740
- parsed_cols, rows = parse_json_report(text, root)
 
741
  pinned = [c for c, _t in amazon_schema.columns_for(table)]
742
  # ⛔⛔ THE UNION, NOT THE PIN, AND AMAZON'S OWN ARTIFACT IS WHY.
743
  #
@@ -765,7 +1233,8 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
765
  # ⚠ NO DECLARED TYPES HERE ON PURPOSE: a flat-file report publishes no schema,
766
  # so sniffing the data is the ONLY evidence there is. That is the whole
767
  # provenance split, arriving one layer down.
768
- cols, rows = parse_flat_file(text)
 
769
  declared = {}
770
  if not cols:
771
  continue
@@ -796,6 +1265,9 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
796
  log(" pricing: getCompetitiveSummary UNPROVEN, no ASIN was returned")
797
  else:
798
  try:
 
 
 
799
  responses = cx.competitive_summaries(fields, pricing_asins)
800
  response_rows, updated = _apply_competitive(con, mirror, responses)
801
  _record_state(con, state_key, "done", response_rows)
@@ -805,15 +1277,16 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
805
  log(f" pricing: getCompetitiveSummary {response_rows:,} ASIN responses, "
806
  f"{updated:,} mirror rows enriched")
807
  except Exception as e: # noqa: BLE001
808
- detail = f"{type(e).__name__}: {str(e)[:160]}"
809
- _record_state(con, state_key, "refused", 0, detail)
810
- operations["getCompetitiveSummary"] = {
811
- "state": "refused", "reason": detail}
812
- log(f" pricing: getCompetitiveSummary REFUSED: {str(e)[:160]}")
813
 
814
  if table == "inventory":
815
  state_key = ENTITY_STATE_KEYS[table]
816
  try:
 
 
817
  inventory = cx.awd_inventory(fields)
818
  awd_rows = _awd_rows(inventory)
819
  if awd_rows:
@@ -828,10 +1301,9 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
828
  "state": "done", "rows": len(awd_rows)}
829
  log(f" inventory: AWD listInventory {len(awd_rows):,} rows")
830
  except Exception as e: # noqa: BLE001
831
- detail = f"{type(e).__name__}: {str(e)[:160]}"
832
- _record_state(con, state_key, "refused", 0, detail)
833
- operations["listInventory"] = {"state": "refused", "reason": detail}
834
- log(f" inventory: AWD listInventory REFUSED: {str(e)[:160]}")
835
 
836
  try:
837
  column_count = len(con.execute(f"PRAGMA table_info('{mirror}')").fetchall())
@@ -842,13 +1314,21 @@ def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None
842
  "rows": total_rows, "columns": column_count, "provenance": prov,
843
  "report": rtype, "operations": operations}
844
  _record_state(con, key, "done", total_rows)
 
 
 
 
 
845
  log(f" {table:<16} {total_rows:>7,} rows {column_count:>3} cols {prov}")
846
  except Exception as e: # noqa: BLE001
847
  # ⚠ ONE TABLE'S REFUSAL IS NOT THE SYNC'S. A 403 on brand_analytics is R5's UNPROVEN
848
  # ticket answering itself, and it must not cost the six tables that did work.
849
- report["tables"][table] = {"rows": 0, "state": f"{type(e).__name__}: {str(e)[:160]}"}
850
- log(f" {table:<16} REFUSED: {str(e)[:160]}")
 
 
851
  report["finished"] = _iso(datetime.now(timezone.utc))
 
852
  return report
853
 
854
 
@@ -991,9 +1471,11 @@ def selftest(log=print):
991
  tsv = ("amazon-order-id\tpurchase-date\tItem Price\t2nd Ref\tsku\n"
992
  "111-2223334-4445556\t2026-08-01T00:00:00Z\t27.30\tx\tRI-001\n"
993
  "111-2223334-4445557\t2026-08-02T00:00:00Z\t14.00\ty\tRI-002\n")
994
- cols, rows = parse_flat_file(tsv)
 
995
  ck("NC-AZ1 flat-file columns are measured from the header",
996
- cols == ["amazon_order_id", "purchase_date", "item_price", "c_2nd_ref", "sku"], cols)
 
997
  # ⚠ ASSERTED AGAINST THE SANITIZER, NOT AGAINST A DEAD `.replace`. The first version of this
998
  # check asked "is there a BOM left in the output", which is true no matter what the code does
999
  # once every non-alphanumeric becomes `_`. It survived its own perturbation. It now asserts
@@ -1012,13 +1494,14 @@ def selftest(log=print):
1012
  # quoting then treats the rest of the document as one quoted string and silently returns a
1013
  # single merged row. That is the real Amazon case, a title like `"Special" Vase`.
1014
  q = 'sku\ttitle\nRI-9\t"12 inch Vase\nRI-10\tPlain\n'
1015
- qc, qr = parse_flat_file(q)
1016
  ck("NC-AZ4 a field opening with a quote does not swallow the rows after it",
1017
  len(qr) == 2 and qr[0]["title"] == '"12 inch Vase' and qr[1]["sku"] == "RI-10", qr)
1018
 
1019
  # NC-AZ5 — a duplicate header cell must not collide.
1020
- dc, _ = parse_flat_file("sku\tsku\tqty\nA\tB\t1\n")
1021
- ck("NC-AZ5 duplicate headers are disambiguated", dc == ["sku", "sku_2", "qty"], dc)
 
1022
 
1023
  # NC-AZ6..7 — typing sniffs the DATA, and ids stay text however numeric they look.
1024
  numeric = [{"qty": "3", "price": "27.30", "settlement_id": "9007199254740993"}]
@@ -1038,7 +1521,7 @@ def selftest(log=print):
1038
  {"parentAsin": "B01", "salesByAsin": {"unitsOrdered": 3,
1039
  "orderedProductSales": {"amount": 27.3}},
1040
  "trafficByAsin": {"buyBoxPercentage": 91.2}}]})
1041
- jc, jr = parse_json_report(doc, "salesAndTrafficByAsin")
1042
  ck("NC-AZ9 nested JSON flattens to the pinned column spelling",
1043
  jr and jr[0].get("sales_by_asin_ordered_product_sales_amount") == 27.3
1044
  and jr[0].get("traffic_by_asin_buy_box_percentage") == 91.2, jr[:1])
@@ -1074,7 +1557,8 @@ def selftest(log=print):
1074
 
1075
  # NC-AZ15 — an empty parse is empty, never a phantom row.
1076
  ck("NC-AZ15 an empty document yields no columns and no rows",
1077
- parse_flat_file("") == ([], []) and parse_json_report("", "x") == ([], []))
 
1078
 
1079
  # NC-AZ16..18 - both role-specific payloads keep their complete source shape and source label.
1080
  price_input = [
@@ -1131,7 +1615,7 @@ def selftest(log=print):
1131
  mem.execute("INSERT INTO keep_unrelated VALUES (99)")
1132
  _record_state(mem, "amzn_orders", "done", 2)
1133
  _record_state(mem, "odoo_orders", "live", 11)
1134
- purged = _purge_mirror(mem)
1135
  ck("NC-AZ21 purge removes every amzn_ table, including a future one",
1136
  purged["tables"] == ["amzn_future_table", "amzn_orders", "amzn_pricing"]
1137
  and purged["rows"] == 5, purged)
@@ -1144,7 +1628,7 @@ def selftest(log=print):
1144
  "SELECT phase, rows FROM _sync_state WHERE entity='odoo_orders'").fetchone()
1145
  ck("NC-AZ23 purge preserves unrelated tables and sync markers byte for byte",
1146
  kept == [(99,)] and kept_state == ("live", 11), (kept, kept_state))
1147
- second = _purge_mirror(mem)
1148
  ck("NC-AZ24 purge readback is residue-free and a retry is idempotent",
1149
  second == {"tables": [], "rows": 0, "syncMarkers": 0,
1150
  "residueTables": [], "residueSyncMarkers": []}, second)
@@ -1199,12 +1683,34 @@ def selftest(log=print):
1199
  key = "qa-purge"
1200
  datastore_path = purge_path
1201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1202
  def assert_datastore_matches(self):
1203
  if Path(datastore.DB_PATH).resolve() != purge_path.resolve():
1204
  raise RuntimeError("wrong test mirror")
1205
 
1206
- public_detail = purge(
1207
- "qa-purge", "qa-purge", rt=_PurgeRuntime({}), log=lambda *_a: None)
 
 
 
 
 
 
 
1208
  datastore.use_path(prior_path)
1209
  readback = duckdb.connect(str(purge_path), read_only=True)
1210
  tables_after = sorted(str(row[0]) for row in readback.execute("SHOW TABLES").fetchall())
@@ -1213,7 +1719,8 @@ def selftest(log=print):
1213
  public_ok = (public_detail["tenant"] == "qa-purge"
1214
  and public_detail["database"] == "qa-purge.duckdb"
1215
  and public_detail["rows"] == 1
1216
- and tables_after == ["_sync_state"] and state_after == [])
 
1217
  finally:
1218
  datastore.use_path(prior_path)
1219
  ck("NC-AZ27 the public purge wrapper deletes and reads back an isolated tenant file",
@@ -1230,12 +1737,35 @@ def main(argv=None):
1230
  ap.add_argument("--validate", action="store_true")
1231
  ap.add_argument("--purge", action="store_true",
1232
  help="permanently delete every Amazon mirror table after credential revocation")
 
 
 
 
 
1233
  ap.add_argument("--selftest", action="store_true")
1234
  ap.add_argument("--tenant", default=None)
1235
  ap.add_argument("--confirm-tenant", default=None,
1236
- help="for --purge, repeat the exact tenant slug")
1237
  ap.add_argument("--table", action="append", help="limit to one table (repeatable)")
1238
  a = ap.parse_args(argv)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1239
  tenant = a.tenant or "royal-imports"
1240
  if a.purge:
1241
  if not a.tenant:
 
45
  import io
46
  import json
47
  import os
48
+ import shutil
49
  import sys
50
+ import tempfile
51
  import time
52
+ import uuid
53
+ from contextlib import closing
54
  from datetime import datetime, timedelta, timezone
55
  from pathlib import Path
56
 
 
70
  TABLES = ("orders", "order_items", "listings", "settlements", "inventory",
71
  "pricing", "brand_analytics")
72
 
73
+ # C1 is a tenant-store document, not an API dependency. verify_amazon gates reader parity.
74
+ ENABLEMENT_KEY = "amazon_connector_enablement"
75
+ # Settlements are issued roughly fortnightly; spending a report on every hourly tick adds nothing.
76
+ SETTLEMENT_SYNC_SECONDS = 14 * 24 * 60 * 60
77
+
78
+
79
+ def read_database_enablement(rt):
80
+ """Read C1 without importing the web layer; malformed/unreadable state fails closed."""
81
+ keys = tuple(amazon_schema.DATABASE_PREFIX + table for table in TABLES)
82
+ unavailable = {"available": False, "databases": dict.fromkeys(keys, False)}
83
+ try:
84
+ current = rt.get(ENABLEMENT_KEY) if rt is not None else None
85
+ except Exception:
86
+ return unavailable
87
+ if current is None or current == {}:
88
+ return {"available": True, "databases": dict.fromkeys(keys, True)}
89
+ if not isinstance(current, dict) or not isinstance(current.get("databases"), dict):
90
+ return unavailable
91
+ stored = current["databases"]
92
+ if set(stored) - set(keys) or any(type(value) is not bool for value in stored.values()):
93
+ return unavailable
94
+ return {"available": True, "databases": {key: stored.get(key, True) for key in keys}}
95
+
96
+
97
+ def sync_plan(states, tables=None, *, now=None):
98
+ """Pure cadence decision: one oldest due table per tick, with no stagger sleep.
99
+
100
+ Attempt markers live in this tenant's mirror, so a replacement mirror starts fresh. Failed
101
+ tables rotate behind their peers and retry on a later tick, including failed settlements.
102
+ The client still owns pacing/retries within a table; this spreads tables across caller ticks.
103
+ """
104
+ from harness.amazon_client import REPORT_STAGGER_SECONDS
105
+ now = _utc(now)
106
+ want = list(TABLES if tables is None else tables)
107
+ stamps = {table: _utc(state["updated_at"]) for table, state in states.items() if state}
108
+ deferred = {}
109
+ due = []
110
+ for table in want:
111
+ stamp = stamps.get(table)
112
+ if (table == "settlements" and stamp is not None
113
+ and states[table]["state"] == "done"
114
+ and (now - stamp).total_seconds() < SETTLEMENT_SYNC_SECONDS):
115
+ deferred[table] = "settlements are on a 14-day cycle; next due " + _iso(
116
+ stamp + timedelta(seconds=SETTLEMENT_SYNC_SECONDS))
117
+ else:
118
+ due.append(table)
119
+ # Boot and the resident first pass can be adjacent. Report the delay instead of sleeping.
120
+ recent = max(stamps.values()) if stamps else None
121
+ ready = recent is None or (now - recent).total_seconds() >= REPORT_STAGGER_SECONDS
122
+ selected = min(due, key=lambda table: stamps.get(
123
+ table, datetime.min.replace(tzinfo=timezone.utc))) if due and ready else None
124
+ for table in due:
125
+ if table != selected:
126
+ deferred[table] = ("table stagger: waiting for a later cadence tick; "
127
+ f"minimum spacing {REPORT_STAGGER_SECONDS:g}s")
128
+ return {"tables": [selected] if selected else [], "deferred": deferred}
129
+
130
  #: Durable proof that the two non-report role operations actually ran. A report-backed table can
131
  #: contain rows while one of these role grants is still missing, so table presence alone is not
132
  #: evidence that Pricing or AWD was authorized.
 
152
  #: ⚠ AMAZON'S OWN CEILING, NOT OURS, and it is why a backfill is many reports rather than one.
153
  MAX_WINDOW_DAYS = 30
154
 
155
+ # Connector metadata, NOT measured Amazon fields. TSV normalization strips leading underscores;
156
+ # JSON flattening rejects these exact reserved keys. Neither path can overwrite metadata.
157
+ _ORIGIN_TYPES = {"_report_document_id": "VARCHAR", "_report_row_number": "BIGINT",
158
+ "_data_origin": "VARCHAR", "_report_type": "VARCHAR"}
159
+ DELETION_DAYS = 30
160
+ DELETION_TRIGGERS = ("revocation", "authorization_loss", "termination", "notice")
161
+
162
+
163
+ def _origin(row, document_id, row_number, report_type):
164
+ if not document_id or not report_type:
165
+ raise ValueError("Amazon row origin requires a document ID and report type")
166
+ row.update({"_report_document_id": str(document_id), "_report_row_number": row_number,
167
+ "_data_origin": "Amazon Services API", "_report_type": str(report_type)})
168
+ return row
169
+
170
  #: Columns that must be text whatever they look like. An Amazon order id is `111-1234567-1234567`
171
  #: and an ASIN is `B0…`; a settlement id is a long decimal that exceeds 2^53. Same ruling as Meta's
172
  #: ids and `ig_id` before it, for the same reason: a float path corrupts them silently.
 
216
  return out
217
 
218
 
219
+ def parse_flat_file(text, *, document_id=None, report_type=None):
220
  """One Amazon flat-file report document -> `(columns, rows)`, columns MEASURED from its header.
221
 
222
  ⭐ THIS FUNCTION IS WHY NO ORDER, LISTING OR SETTLEMENT COLUMN IS TRANSCRIBED ANYWHERE. Line 1
 
239
  cols = _dedupe([_snake(h) for h in header])
240
  width = len(cols)
241
  rows = []
242
+ # The read-only connectors_amazon report probe measures headers without capture metadata.
243
+ # Preserve that parse-only API; _replace refuses its unattributed rows. Sync always supplies
244
+ # BOTH keywords, and a missing document ID with a report type is an error, never a fallback.
245
+ attributed = document_id is not None or report_type is not None
246
+ for row_number, raw in enumerate(reader, 1):
247
  if not raw or (len(raw) == 1 and not str(raw[0]).strip()):
248
  continue
249
  vals = list(raw[:width]) + [None] * max(0, width - len(raw))
250
+ row = {c: (v if (v is None or str(v) != "") else None) for c, v in zip(cols, vals)}
251
+ rows.append(_origin(row, document_id, row_number, report_type) if attributed else row)
252
+ return cols + (list(_ORIGIN_TYPES) if attributed else []), rows
253
 
254
 
255
+ def parse_json_report(text, root, *, document_id=None, report_type=None):
256
  """One JSON report document -> `(columns, rows)` flattened onto the pinned artifact's names.
257
 
258
  ⚠ THE COLUMN LIST IS THE PINNED SCHEMA'S, NOT THE PAYLOAD'S. Amazon omits null fields from a
 
268
  if isinstance(body, dict):
269
  body = [body]
270
  rows = []
271
+ attributed = document_id is not None or report_type is not None
272
+ for row_number, item in enumerate(body, 1):
273
+ row = _flatten_row(item or {})
274
+ rows.append(_origin(row, document_id, row_number, report_type) if attributed else row)
275
  return sorted({k for r in rows for k in r}), rows
276
 
277
 
 
287
  path = f"{prefix}.{k}" if prefix else k
288
  if isinstance(v, dict):
289
  out.update(_flatten_row(v, path))
 
 
 
290
  else:
291
+ name = amazon_schema._snake(path)
292
+ if name in _ORIGIN_TYPES:
293
+ raise ValueError("Amazon JSON field collides with reserved origin metadata")
294
+ out[name] = json.dumps(v, separators=(",", ":"), ensure_ascii=False) if isinstance(
295
+ v, list) else v
296
  return out
297
 
298
 
 
310
  return out
311
 
312
 
313
+ def _awd_rows(inventory, operation_id=None):
314
  """AWD inventory summaries -> flattened rows that remain distinguishable from FBA ledger."""
315
  rows = []
316
+ # AWD is a paginated operation, not a report. Retain its full response-list position and
317
+ # an explicitly operation-prefixed capture ID instead of inventing an Amazon document ID.
318
+ operation_id = operation_id or "operation:" + uuid.uuid4().hex
319
+ for row_number, item in enumerate(inventory or (), 1):
320
  row = _flatten_row(item or {})
321
  row["inventory_source"] = "AWD"
322
+ rows.append(_origin(row, operation_id, row_number, "listInventory"))
323
  return rows
324
 
325
 
 
395
  column that is numeric for 500 rows and then carries `N/A` must not make the insert fail after
396
  five tables are already written — the exact failure `meta_store._coltype` was rewritten for.
397
  """
398
+ if name in _ORIGIN_TYPES:
399
+ return _ORIGIN_TYPES[name]
400
  if name in _FORCE_TEXT:
401
  return "VARCHAR"
402
  if not rows:
 
493
 
494
 
495
  def _replace(con, table, cols, types, rows):
496
+ """Insert one window. The sync caller clears the table ONCE before its first window."""
 
 
 
 
 
 
497
  if not rows:
498
  return 0
499
+ if not set(_ORIGIN_TYPES).issubset(cols) or any(
500
+ any(r.get(c) in (None, "") for c in _ORIGIN_TYPES)
501
+ or type(r.get("_report_row_number")) is not int
502
+ or r["_report_row_number"] < 1 for r in rows):
503
+ raise ValueError("refusing Amazon rows without complete source attribution")
504
  ph = ", ".join("?" for _ in cols)
505
  con.executemany(
506
  f'INSERT INTO {table} ({", ".join(chr(34) + c + chr(34) for c in cols)}) VALUES ({ph})',
 
540
  before pasting it. Serving it here would hand one tenant another's Amazon seller account, which
541
  is precisely the elevation `keychain.TENANT_WIDE_TYPES` was written to stop.
542
  """
543
+ key = _tenant_key(tenant_key)
544
+ runtime = rt if rt is not None else _runtime_for(key)
545
+ # Keep identity failures OUTSIDE the optional-keychain try: fail closed with the diagnosis,
546
+ # not a silent "no credential". A resolved runtime must match too, not only an explicit one.
547
+ if runtime is not None:
548
+ runtime_key = str(getattr(runtime, "key", "") or "").strip().lower()
549
+ if runtime_key != key:
550
+ raise RuntimeError(
551
+ f"runtime tenant {runtime_key!r} does not match requested tenant {key!r}")
552
  try:
553
  import core.keychain as kc
554
+ return kc.amazon_creds(runtime)
555
  except Exception: # noqa: BLE001
556
  return None
557
 
 
620
  return '"' + str(value).replace('"', '""') + '"'
621
 
622
 
623
+ class AmazonRetentionOverdue(RuntimeError):
624
+ """A dated deletion obligation is overdue, not a throttle or operation refusal."""
625
+
626
+
627
+ class AmazonAuditUnavailable(RuntimeError):
628
+ """The mandatory C2 event failed; its failure is durable in the lifecycle ledger."""
629
+
630
+
631
+ def _utc(value=None):
632
+ value = value or datetime.now(timezone.utc)
633
+ if isinstance(value, str):
634
+ value = datetime.fromisoformat(value.replace("Z", "+00:00"))
635
+ if value.tzinfo is None or value.utcoffset() is None:
636
+ raise ValueError("a timezone-aware deletion timestamp is required")
637
+ return value.astimezone(timezone.utc)
638
+
639
+
640
+ def _control_stamp(value=None):
641
+ # Preserve subsecond ordering: a notice arriving AFTER a purge in the same second is new
642
+ # work. Report-request windows keep their existing second-precision _iso contract.
643
+ return _utc(value).isoformat(timespec="microseconds").replace("+00:00", "Z")
644
+
645
+
646
+ LIFECYCLE_KEY = "amazon_lifecycle"
647
+
648
+
649
+ def _ledger_runtime(tenant_key, rt=None):
650
+ """Resolve the ONE tenant store; an unavailable obligation ledger must fail loudly."""
651
+ key = _tenant_key(tenant_key)
652
+ rt = rt if rt is not None else _runtime_for(key)
653
+ if rt is None:
654
+ raise RuntimeError("Amazon lifecycle ledger requires a resolved tenant runtime")
655
+ runtime_key = str(getattr(rt, "key", "") or "").strip().lower()
656
+ if runtime_key != key:
657
+ raise RuntimeError(
658
+ f"runtime tenant {runtime_key!r} does not match requested tenant {key!r}")
659
+ return rt
660
+
661
+
662
+ def _ledger(tenant_key, rt=None):
663
+ # The tenant-store document SURVIVES purge and mirror restore: neither touches this key.
664
+ # Only tenant slug, event kind, UTC dates and booleans. No Amazon rows, document IDs,
665
+ # report IDs or credentials. It is not an amzn_ object or a _sync_state row, so the mirror's
666
+ # collateral snapshot stays exact. Fresh reads cannot hide another process's obligation.
667
+ rt = _ledger_runtime(tenant_key, rt)
668
+ return rt.get(LIFECYCLE_KEY, fresh=True) or {
669
+ "triggers": [], "checks": [], "audit_failures": []}
670
+
671
+
672
+ def _append_ledger(tenant_key, rt, section, row):
673
+ rt = _ledger_runtime(tenant_key, rt)
674
+
675
+ def append(doc):
676
+ for part in ("triggers", "checks", "audit_failures"):
677
+ doc.setdefault(part, [])
678
+ # Preserve INSERT OR IGNORE's exact-event idempotency for triggers only.
679
+ if section != "triggers" or row not in doc[section]:
680
+ doc[section].append(row)
681
+
682
+ # Commit through the tenant's bound backend before returning; never buffer an obligation.
683
+ rt.update(LIFECYCLE_KEY, append, flush="sync")
684
+
685
+
686
+ def _c2_event(kind, tenant, principal, detail, rt=None):
687
+ try:
688
+ # C2 is declared by lane F. Missing or failing audit is NEVER a successful emission.
689
+ from importlib import import_module
690
+ audit = import_module("core.audit")
691
+ audit.record(kind, tenant, principal, detail)
692
+ except Exception as exc:
693
+ _append_ledger(tenant, rt, "audit_failures",
694
+ {"tenant": tenant, "kind": kind, "checked_at": _control_stamp()})
695
+ raise AmazonAuditUnavailable(
696
+ f"mandatory C2 event {kind} failed; recorded in the lifecycle ledger") from exc
697
+
698
+
699
+ def record_deletion_trigger(tenant_key, trigger, *, occurred_at=None, rt=None,
700
+ principal="system"):
701
+ """Record the real event time; calling this schedules an obligation, never deletes data.
702
+
703
+ Credential-revocation, termination and notice owners must call this at their event boundary.
704
+ Authorization-loss owners use the same door, which also emits C2. Current keychain absence
705
+ alone is NOT evidence of when revocation occurred.
706
+ """
707
+ key = _tenant_key(tenant_key)
708
+ if trigger not in DELETION_TRIGGERS:
709
+ raise ValueError("unknown Amazon deletion trigger")
710
+ when = _utc(occurred_at)
711
+ if when > _utc():
712
+ raise ValueError("a deletion trigger cannot be dated in the future")
713
+ rt = _ledger_runtime(key, rt)
714
+ _append_ledger(key, rt, "triggers",
715
+ {"tenant": key, "kind": trigger, "occurred_at": _control_stamp(when)})
716
+ if trigger == "authorization_loss":
717
+ _c2_event("amazon.authorization_lost", key, principal,
718
+ {"trigger": trigger, "occurred_at": _control_stamp(when)}, rt)
719
+ return retention_check(key, rt=rt)
720
+
721
+
722
+ def retention_check(tenant_key, *, rt=None, checked_at=None, scope="all", raise_overdue=False):
723
+ """Dated obligation check. Only a real readback can complete the covered mirror scope.
724
+
725
+ Full-service completion remains unproven until workbook/export/backup owners wire deletion.
726
+ A local purge must not move their deadline or turn this default all-scope check green.
727
+ """
728
+ key, now = _tenant_key(tenant_key), _utc(checked_at)
729
+ if scope not in ("all", "mirror"):
730
+ raise ValueError("deletion scope must be all or mirror")
731
+ ledger = _ledger(key, rt)
732
+ triggers = sorted(r["occurred_at"] for r in ledger["triggers"] if r["tenant"] == key)
733
+ checks = sorted(r["checked_at"] for r in ledger["checks"]
734
+ if r["tenant"] == key and r["kind"] == "purge" and r["success"])
735
+ # A check in the future cannot prove deletion at the requested historical observation time.
736
+ checks = [v for v in checks if _utc(v) <= now]
737
+ triggers = [v for v in triggers if _utc(v) <= now]
738
+ outstanding = [v for v in triggers if not (
739
+ scope == "mirror" and any(c >= v for c in checks))]
740
+ earliest = outstanding[0] if outstanding else None
741
+ deadline = _utc(earliest) + timedelta(days=DELETION_DAYS) if earliest else None
742
+ state = ("OVERDUE" if now > deadline else "DUE") if deadline else "NO_TRIGGER"
743
+ if not outstanding and triggers and scope == "mirror" and checks:
744
+ # Historical late deletion stays late, even after a later successful retry.
745
+ state = "COMPLETED_LATE" if any(
746
+ _utc(next(c for c in checks if c >= t)) > _utc(t) + timedelta(days=DELETION_DAYS)
747
+ for t in triggers if _utc(t) <= now) else "COMPLETED_ON_TIME"
748
+ result = {"tenant": key, "scope": scope, "state": state, "checkedAt": _control_stamp(now),
749
+ "earliestTriggerAt": earliest,
750
+ "deadlineAt": _control_stamp(deadline) if deadline else None,
751
+ "mirrorDeletedAt": checks[-1] if checks else None}
752
+ if state == "OVERDUE" and raise_overdue:
753
+ raise AmazonRetentionOverdue("Amazon deletion deadline has passed; see the dated check")
754
+ return result
755
+
756
+
757
+ def _record_deletion_check(key, rt, kind, success):
758
+ stamp = _control_stamp()
759
+ _append_ledger(key, rt, "checks",
760
+ {"tenant": key, "kind": kind, "checked_at": stamp, "success": bool(success)})
761
+ return stamp
762
+
763
+
764
+ def _is_amazon_object(name):
765
+ return str(name).startswith((PREFIX, "ut_amzn_"))
766
+
767
+
768
  def _amazon_objects(con):
769
  """Every live mirror object reserved to Amazon by the `amzn_` naming contract."""
770
  rows = con.execute(
 
773
  out = []
774
  for name, kind in rows:
775
  name = str(name)
776
+ if not name.startswith(PREFIX) and not name.startswith("ut_amzn_"):
777
  continue
778
  out.append((name, str(kind or "BASE TABLE").upper()))
779
  return sorted(out, key=lambda row: ("VIEW" not in row[1], row[0]))
 
786
  "FROM _sync_state ORDER BY entity").fetchall()]
787
 
788
 
789
+ def _collateral_rows(con):
790
+ """Compare complete non-Amazon row multisets, including duplicate counts, not just names."""
791
+ from collections import Counter
792
+ names = [str(r[0]) for r in con.execute(
793
+ "SELECT table_name FROM information_schema.tables WHERE table_schema='main'").fetchall()
794
+ if not _is_amazon_object(r[0]) and r[0] != "_sync_state"]
795
+ return {name: Counter(repr(tuple(row)) for row in con.execute(
796
+ f"SELECT * FROM {_quoted_identifier(name)}").fetchall()) for name in names}
797
+
798
+
799
+ def _purge_mirror(con, tenant_key, confirmation):
800
  """Transactionally delete every `amzn_` mirror object and state marker, then read it back.
801
 
802
  The prefix is the connector's reserved namespace, so this also catches a future Amazon table
803
  that has not yet been added to `TABLES`. Non-Amazon tables and sync markers are snapshotted and
804
  compared inside the transaction and again after commit. No caller supplies a table name.
805
  """
806
+ _require_purge_confirmation(tenant_key, confirmation)
807
  objects = _amazon_objects(con)
808
  before_tables = {str(row[0]) for row in con.execute(
809
  "SELECT table_name FROM information_schema.tables "
810
  "WHERE table_schema='main'").fetchall()}
811
+ before_other_tables = sorted(name for name in before_tables if not _is_amazon_object(name))
812
+ before_other_rows = _collateral_rows(con)
813
  before_state = _sync_state_rows(con)
814
  amazon_state = [str(row[0]) for row in before_state if str(row[0]).startswith(PREFIX)]
815
  other_state = [row for row in before_state if not str(row[0]).startswith(PREFIX)]
 
830
  raise RuntimeError("Amazon mirror objects remain inside the purge transaction")
831
  inside_other_tables = sorted(str(row[0]) for row in con.execute(
832
  "SELECT table_name FROM information_schema.tables WHERE table_schema='main'").fetchall()
833
+ if not _is_amazon_object(row[0]))
834
  if inside_other_tables != before_other_tables:
835
  raise RuntimeError("a non-Amazon mirror object changed during the purge")
836
  inside_state = _sync_state_rows(con)
837
  if inside_state != other_state:
838
  raise RuntimeError("a non-Amazon sync marker changed during the purge")
839
+ if _collateral_rows(con) != before_other_rows:
840
+ raise RuntimeError("non-Amazon rows changed during the purge")
841
  con.execute("COMMIT")
842
  except Exception:
843
  try:
 
851
  if str(row[0]).startswith(PREFIX)]
852
  after_other_tables = sorted(str(row[0]) for row in con.execute(
853
  "SELECT table_name FROM information_schema.tables WHERE table_schema='main'").fetchall()
854
+ if not _is_amazon_object(row[0]))
855
  after_other_state = [row for row in _sync_state_rows(con)
856
  if not str(row[0]).startswith(PREFIX)]
857
  if residue_objects or residue_state:
858
  raise RuntimeError(
859
  "Amazon mirror purge committed but independent readback found residue")
860
+ if (after_other_tables != before_other_tables or after_other_state != other_state
861
+ or _collateral_rows(con) != before_other_rows):
862
  raise RuntimeError(
863
  "Amazon mirror purge committed but independent readback found collateral change")
864
  return {
 
870
  }
871
 
872
 
873
+ def _purge_materialized(rt, tenant_key, confirmation):
874
+ """Extend the operator purge through the existing tenant-bound authorship store seam."""
875
+ _require_purge_confirmation(tenant_key, confirmation)
876
+ _tenant_mirror_path(tenant_key, rt)
877
+ if not callable(getattr(rt, "update", None)):
878
+ return {"materializedVerified": False, "materializedTables": 0, "materializedRows": 0}
879
+ from copy import deepcopy
880
+ removed, kept = {}, {}
881
+
882
+ def remove(doc):
883
+ removed.clear()
884
+ kept.clear()
885
+ for name, value in doc.items():
886
+ if str(name).startswith("ut_amzn_"):
887
+ removed[name] = len((value or {}).get("rows") or [])
888
+ else:
889
+ kept[name] = deepcopy(value)
890
+ for name in removed:
891
+ del doc[name]
892
+
893
+ rt.update("user_tables", remove, flush="sync")
894
+ readback = rt.get("user_tables", fresh=True) or {}
895
+ if any(str(name).startswith("ut_amzn_") for name in readback) or readback != kept:
896
+ raise RuntimeError("materialized Amazon purge readback found residue or collateral change")
897
+ return {"materializedVerified": True, "materializedTables": len(removed),
898
+ "materializedRows": sum(removed.values())}
899
+
900
+
901
+ def _amazon_cache_key(value):
902
+ if isinstance(value, (tuple, list)):
903
+ return any(_amazon_cache_key(item) for item in value)
904
+ return isinstance(value, str) and _is_amazon_object(value)
905
+
906
+
907
+ def _purge_runtime_caches(rt, tenant_key, confirmation):
908
+ _require_purge_confirmation(tenant_key, confirmation)
909
+ _tenant_mirror_path(tenant_key, rt)
910
+ count = 0
911
+ for attr in ("pool_cache", "measure_memo", "mset_memo", "series_memo"):
912
+ cache = getattr(rt, attr, {})
913
+ for key in list(cache):
914
+ if _amazon_cache_key(key):
915
+ del cache[key]
916
+ count += 1
917
+ if any(_amazon_cache_key(key) for key in cache):
918
+ raise RuntimeError("Amazon runtime cache residue remains")
919
+ return count
920
+
921
+
922
+ def purge(tenant_key, confirmation, rt=None, log=print, *, principal="operator"):
923
  """Permanently remove one tenant's live Amazon mirror after credential revocation.
924
 
925
  This is an operator-only lifecycle control. It never revokes a credential itself and refuses
 
936
  raise RuntimeError(
937
  f"tenant {key!r} has no existing mirror file; refusing to create one as purge proof")
938
  _assert_amazon_credential_revoked(rt)
939
+ success, result = False, {}
940
  try:
941
+ con, bound_path = _connect_tenant_mirror(key, rt)
942
+ try:
943
+ result = _purge_mirror(con, key, confirmation)
944
+ finally:
945
+ con.close()
946
+ result.update(_purge_materialized(rt, key, confirmation))
947
+ result["runtimeCacheEntries"] = _purge_runtime_caches(rt, key, confirmation)
948
+ # Keep the existing post-commit query and add a fresh, independently opened cursor.
949
+ import duckdb
950
+ with closing(duckdb.connect(str(bound_path))) as readback:
951
+ if _amazon_objects(readback) or any(
952
+ str(r[0]).startswith(PREFIX) for r in _sync_state_rows(readback)):
953
+ raise RuntimeError("independent mirror file readback found Amazon residue")
954
+ success = True
955
  finally:
956
+ stamp = _record_deletion_check(key, rt, "purge", success)
957
+ # Counts only. Even database-discovered table names could contain customer data, so
958
+ # never send them (or exception strings) to C2's flat, secret-refusing detail object.
959
+ _c2_event("data.purge", key, principal,
960
+ {"success": success, "checked_at": stamp, "scope": "local",
961
+ "rows": result.get("rows", 0), "tables": len(result.get("tables", [])),
962
+ "known_tables": ",".join(table_name(t) for t in TABLES
963
+ if table_name(t) in result.get("tables", [])),
964
+ "materialized_tables": result.get("materializedTables", 0),
965
+ "materialized_rows": result.get("materializedRows", 0)}, rt)
966
+ report = {"tenant": key, "database": bound_path.name, **result, "checkedAt": stamp,
967
+ "complete": False,
968
+ "unverifiedScopes": ["workbooks", "service_retained_exports", "backups",
969
+ "other_process_and_unattributed_caches"],
970
+ "retention": retention_check(key, rt=rt)}
971
+ if not result.get("materializedVerified"):
972
+ report["unverifiedScopes"].append("materialized_store")
973
  log(f" tenant {key}: permanently deleted {result['rows']:,} Amazon mirror rows from "
974
  f"{len(result['tables']):,} tables and {result['syncMarkers']:,} sync markers")
975
  return report
976
 
977
 
978
+ def _restore_readback(path):
979
+ import duckdb
980
+ with closing(duckdb.connect(str(path), read_only=True)) as con:
981
+ objects = _amazon_objects(con)
982
+ state = [r for r in _sync_state_rows(con) if str(r[0]).startswith(PREFIX)]
983
+ if objects or state:
984
+ raise RuntimeError("restored Amazon mirror contains purged residue")
985
+ return _collateral_rows(con)
986
+
987
+
988
+ def restore(tenant_key, confirmation, backup_path, destination, *, rt=None,
989
+ principal="operator"):
990
+ """Restore a real backup to a NEW local copy, read it back before publishing that copy.
991
+
992
+ This never activates a service store or rewrites the live mirror. A dirty pre-purge backup
993
+ is refused, not silently sanitized by a second purge implementation. The authoritative
994
+ lifecycle ledger must stay outside the backup being restored.
995
+ """
996
+ key = _require_purge_confirmation(tenant_key, confirmation)
997
+ rt = rt if rt is not None else _runtime_for(key)
998
+ if rt is None:
999
+ raise RuntimeError("restore requires a resolved tenant runtime")
1000
+ live_path = _tenant_mirror_path(key, rt).resolve()
1001
+ _assert_amazon_credential_revoked(rt)
1002
+ source, target = Path(backup_path).resolve(), Path(destination).resolve()
1003
+ if target.parent != live_path.parent or target == live_path or target.exists():
1004
+ raise RuntimeError("restore requires a new copy beside this tenant's mirror")
1005
+ if not source.is_file():
1006
+ raise RuntimeError("restore requires an existing backup file")
1007
+ proof = any(r["tenant"] == key and r["kind"] == "purge" and r["success"]
1008
+ for r in _ledger(key, rt)["checks"])
1009
+ if not proof:
1010
+ raise RuntimeError("restore requires a recorded real purge readback")
1011
+ success, temporary = False, None
1012
+ try:
1013
+ fd, name = tempfile.mkstemp(prefix=".amazon-restore-", suffix=".duckdb", dir=target.parent)
1014
+ os.close(fd)
1015
+ temporary = Path(name)
1016
+ shutil.copyfile(source, temporary)
1017
+ before = _restore_readback(source)
1018
+ if _restore_readback(temporary) != before:
1019
+ raise RuntimeError("restored non-Amazon rows differ from the backup")
1020
+ # Hard-link publication refuses an existing target, including a concurrent creator.
1021
+ os.link(temporary, target)
1022
+ if _restore_readback(target) != before:
1023
+ raise RuntimeError("published restore readback differs from the backup")
1024
+ success = True
1025
+ finally:
1026
+ if temporary is not None:
1027
+ temporary.unlink(missing_ok=True)
1028
+ stamp = _record_deletion_check(key, rt, "restore", success)
1029
+ _c2_event("data.restore", key, principal,
1030
+ {"success": success, "checked_at": stamp, "scope": "mirror_copy"}, rt)
1031
+ return {"tenant": key, "checkedAt": stamp, "residueTables": [],
1032
+ "residueSyncMarkers": [], "scope": "mirror_copy", "success": success}
1033
+
1034
+
1035
  def _client():
1036
  """The SP-API transport, from the DATA LAYER.
1037
 
 
1071
  return {"state": row[0], "rows": row[1], "updated_at": row[2], "detail": row[3]}
1072
 
1073
 
1074
+ def _sync_event(kind, tenant, table, detail, rt, report, log):
1075
+ """Sync is nondestructive: preserve C2's loud failure, but continue the data pull."""
1076
+ try:
1077
+ _c2_event(kind, tenant, "system", {"table": table, **detail}, rt=rt)
1078
+ except Exception as exc:
1079
+ # The emitter records the failure in the lifecycle ledger before raising. If that store
1080
+ # also fails, the report/log remains the fallback; never claim an event was delivered.
1081
+ message = (f"{table}: {kind} AUDIT UNAVAILABLE ({type(exc).__name__}); "
1082
+ "restore core.audit and the tenant lifecycle store; sync continues")
1083
+ report["audit_problems"].append(message)
1084
+ log(message)
1085
+
1086
+
1087
+ def _sync_problem(exc, table, operation, tenant, rt, report, log):
1088
+ from harness.amazon_client import AmazonThrottled, AmazonOperationRefused
1089
+ cause = f"{type(exc).__name__}: {exc}"
1090
+ if isinstance(exc, AmazonThrottled):
1091
+ retry = exc.retry_after
1092
+ state = "throttled"
1093
+ fix = (f"retry_after={retry if retry is not None else 'unspecified'}; "
1094
+ "retry after the vendor delay, widen report windows or reduce sync frequency")
1095
+ _sync_event("amazon.throttled", tenant, table,
1096
+ {"operation": operation, "retry_after": str(retry), "cause": "HTTP 429"},
1097
+ rt, report, log)
1098
+ elif isinstance(exc, AmazonOperationRefused):
1099
+ state = "refused"
1100
+ fix = "use an operation in the approved read-only scope; check the connector operation mapping"
1101
+ else:
1102
+ state = "refused"
1103
+ fix = "check the report and operation's required roles, credential and vendor response; retry"
1104
+ message = f"{table}: {operation} {state.upper()}: {cause}; fix: {fix}"
1105
+ report["problems"].append(message)
1106
+ log(message)
1107
+ return {"state": state, "reason": message}
1108
+
1109
+
1110
  def sync(tenant_key="royal-imports", tables=None, since=None, log=print, rt=None,
1111
+ max_wait=900, *, scheduled=False):
1112
  """Pull every declared table into the tenant's mirror. -> a report dict.
1113
 
1114
  Idempotent: a re-sync replaces each window rather than appending. Refuses, loudly and with the
 
1140
  "reach a grid (standing rule 8, and R3's reconciliation). Use it to prove the client "
1141
  "(`connectors_amazon.py --check`) and sync only a PRODUCTION credential.")
1142
 
1143
+ want = [t for t in (TABLES if tables is None else tables) if t in TABLES]
1144
  end = datetime.now(timezone.utc)
1145
  start = since or (end - timedelta(days=DEFAULT_BACKFILL_DAYS))
1146
+ report = {"tenant": tenant_key, "tables": {}, "started": _iso(end),
1147
+ "problems": [], "audit_problems": []}
1148
+ enablement = read_database_enablement(rt)
1149
+ report["available"] = enablement["available"]
1150
+ for table in want:
1151
+ if not enablement["databases"][amazon_schema.DATABASE_PREFIX + table]:
1152
+ reason = ("database disabled; re-enable it in Settings, Connectors to resume; existing data preserved"
1153
+ if enablement["available"] else
1154
+ "enablement document malformed or unreadable; capability unavailable; "
1155
+ "repair amazon_connector_enablement with known database keys and boolean values "
1156
+ "and restore tenant-store access; existing data preserved")
1157
+ report["tables"][table] = {"state": "disabled", "reason": reason}
1158
+ log(f"{table}: SKIPPED: {reason}")
1159
+ if not enablement["available"]:
1160
+ report["problems"].append(f"{table}: {reason}")
1161
+ want = [table for table in want if table not in report["tables"]]
1162
+ if not want:
1163
+ report["finished"] = _iso(datetime.now(timezone.utc))
1164
+ return report
1165
  con, _path = _connect_tenant_mirror(tenant_key, rt)
1166
+ try:
1167
+ obligation = retention_check(tenant_key, rt=rt, raise_overdue=True)
1168
+ except Exception:
1169
+ con.close()
1170
+ raise
1171
+ if obligation["earliestTriggerAt"]:
1172
+ con.close()
1173
+ raise RuntimeError("Amazon deletion is outstanding; sync cannot repopulate purged data")
1174
+ if scheduled:
1175
+ plan = sync_plan({table: _read_state(con, entity_key("sync_tick_" + table))
1176
+ for table in TABLES}, want, now=end)
1177
+ want = plan["tables"]
1178
+ for table, reason in plan["deferred"].items():
1179
+ report["tables"][table] = {"state": "deferred", "reason": reason}
1180
+ log(f"{table}: DEFERRED: {reason}")
1181
 
1182
  for table in want:
1183
  spec = cx.REPORT_TYPES.get(table) or {}
 
1190
  prov = amazon_schema.PROVENANCE.get(table, "measured_at_sync")
1191
  root = (amazon_schema.ARTIFACTS.get(table) or (None, None))[1]
1192
  try:
1193
+ # Attempt first, so a refusal or process interruption cannot starve the other tables.
1194
+ _record_state(con, entity_key("sync_tick_" + table), "attempted")
1195
  written, cols, cleared = 0, [], False
1196
  pricing_asins = []
1197
  for w0, w1 in _windows(start, end):
1198
+ # W59-T43 / C2 has no amazon.access kind. Record each credential-backed
1199
+ # vendor attempt as a sync ACCESS phase, distinct from the completion event.
1200
+ # Lane F/combine own the vocabulary decision; no credential or row enters C2.
1201
+ _sync_event("amazon.sync", tenant_key, table,
1202
+ {"state": "access", "operation": "report_document"}, rt, report, log)
1203
  text, meta = cx.report_document(
1204
+ fields, rtype, start=_iso(w0), end=_iso(w1), max_wait=max_wait,
1205
+ log=lambda message: log(f"{table}: {message}"))
1206
  if prov == "schema_artifact" and root:
1207
+ parsed_cols, rows = parse_json_report(
1208
+ text, root, document_id=meta.get("reportDocumentId"), report_type=rtype)
1209
  pinned = [c for c, _t in amazon_schema.columns_for(table)]
1210
  # ⛔⛔ THE UNION, NOT THE PIN, AND AMAZON'S OWN ARTIFACT IS WHY.
1211
  #
 
1233
  # ⚠ NO DECLARED TYPES HERE ON PURPOSE: a flat-file report publishes no schema,
1234
  # so sniffing the data is the ONLY evidence there is. That is the whole
1235
  # provenance split, arriving one layer down.
1236
+ cols, rows = parse_flat_file(
1237
+ text, document_id=meta.get("reportDocumentId"), report_type=rtype)
1238
  declared = {}
1239
  if not cols:
1240
  continue
 
1265
  log(" pricing: getCompetitiveSummary UNPROVEN, no ASIN was returned")
1266
  else:
1267
  try:
1268
+ _sync_event("amazon.sync", tenant_key, table,
1269
+ {"state": "access", "operation": "getCompetitiveSummary"},
1270
+ rt, report, log)
1271
  responses = cx.competitive_summaries(fields, pricing_asins)
1272
  response_rows, updated = _apply_competitive(con, mirror, responses)
1273
  _record_state(con, state_key, "done", response_rows)
 
1277
  log(f" pricing: getCompetitiveSummary {response_rows:,} ASIN responses, "
1278
  f"{updated:,} mirror rows enriched")
1279
  except Exception as e: # noqa: BLE001
1280
+ problem = _sync_problem(e, table, "getCompetitiveSummary", tenant_key,
1281
+ rt, report, log)
1282
+ _record_state(con, state_key, problem["state"], 0, problem["reason"])
1283
+ operations["getCompetitiveSummary"] = problem
 
1284
 
1285
  if table == "inventory":
1286
  state_key = ENTITY_STATE_KEYS[table]
1287
  try:
1288
+ _sync_event("amazon.sync", tenant_key, table,
1289
+ {"state": "access", "operation": "listInventory"}, rt, report, log)
1290
  inventory = cx.awd_inventory(fields)
1291
  awd_rows = _awd_rows(inventory)
1292
  if awd_rows:
 
1301
  "state": "done", "rows": len(awd_rows)}
1302
  log(f" inventory: AWD listInventory {len(awd_rows):,} rows")
1303
  except Exception as e: # noqa: BLE001
1304
+ problem = _sync_problem(e, table, "listInventory", tenant_key, rt, report, log)
1305
+ _record_state(con, state_key, problem["state"], 0, problem["reason"])
1306
+ operations["listInventory"] = problem
 
1307
 
1308
  try:
1309
  column_count = len(con.execute(f"PRAGMA table_info('{mirror}')").fetchall())
 
1314
  "rows": total_rows, "columns": column_count, "provenance": prov,
1315
  "report": rtype, "operations": operations}
1316
  _record_state(con, key, "done", total_rows)
1317
+ _record_state(con, entity_key("sync_tick_" + table), "done", total_rows)
1318
+ _sync_event("amazon.sync", tenant_key, table,
1319
+ {"state": "done", "rows": total_rows,
1320
+ "operations_ok": all(v["state"] == "done" for v in operations.values())},
1321
+ rt, report, log)
1322
  log(f" {table:<16} {total_rows:>7,} rows {column_count:>3} cols {prov}")
1323
  except Exception as e: # noqa: BLE001
1324
  # ⚠ ONE TABLE'S REFUSAL IS NOT THE SYNC'S. A 403 on brand_analytics is R5's UNPROVEN
1325
  # ticket answering itself, and it must not cost the six tables that did work.
1326
+ problem = _sync_problem(e, table, "report_document", tenant_key, rt, report, log)
1327
+ report["tables"][table] = {"rows": 0, **problem}
1328
+ _sync_event("amazon.sync", tenant_key, table,
1329
+ {"state": problem["state"], "rows": 0}, rt, report, log)
1330
  report["finished"] = _iso(datetime.now(timezone.utc))
1331
+ con.close()
1332
  return report
1333
 
1334
 
 
1471
  tsv = ("amazon-order-id\tpurchase-date\tItem Price\t2nd Ref\tsku\n"
1472
  "111-2223334-4445556\t2026-08-01T00:00:00Z\t27.30\tx\tRI-001\n"
1473
  "111-2223334-4445557\t2026-08-02T00:00:00Z\t14.00\ty\tRI-002\n")
1474
+ origin = {"document_id": "selftest-document", "report_type": "selftest-report"}
1475
+ cols, rows = parse_flat_file(tsv, **origin)
1476
  ck("NC-AZ1 flat-file columns are measured from the header",
1477
+ cols == ["amazon_order_id", "purchase_date", "item_price", "c_2nd_ref", "sku"]
1478
+ + list(_ORIGIN_TYPES), cols)
1479
  # ⚠ ASSERTED AGAINST THE SANITIZER, NOT AGAINST A DEAD `.replace`. The first version of this
1480
  # check asked "is there a BOM left in the output", which is true no matter what the code does
1481
  # once every non-alphanumeric becomes `_`. It survived its own perturbation. It now asserts
 
1494
  # quoting then treats the rest of the document as one quoted string and silently returns a
1495
  # single merged row. That is the real Amazon case, a title like `"Special" Vase`.
1496
  q = 'sku\ttitle\nRI-9\t"12 inch Vase\nRI-10\tPlain\n'
1497
+ qc, qr = parse_flat_file(q, **origin)
1498
  ck("NC-AZ4 a field opening with a quote does not swallow the rows after it",
1499
  len(qr) == 2 and qr[0]["title"] == '"12 inch Vase' and qr[1]["sku"] == "RI-10", qr)
1500
 
1501
  # NC-AZ5 — a duplicate header cell must not collide.
1502
+ dc, _ = parse_flat_file("sku\tsku\tqty\nA\tB\t1\n", **origin)
1503
+ ck("NC-AZ5 duplicate headers are disambiguated",
1504
+ dc == ["sku", "sku_2", "qty"] + list(_ORIGIN_TYPES), dc)
1505
 
1506
  # NC-AZ6..7 — typing sniffs the DATA, and ids stay text however numeric they look.
1507
  numeric = [{"qty": "3", "price": "27.30", "settlement_id": "9007199254740993"}]
 
1521
  {"parentAsin": "B01", "salesByAsin": {"unitsOrdered": 3,
1522
  "orderedProductSales": {"amount": 27.3}},
1523
  "trafficByAsin": {"buyBoxPercentage": 91.2}}]})
1524
+ jc, jr = parse_json_report(doc, "salesAndTrafficByAsin", **origin)
1525
  ck("NC-AZ9 nested JSON flattens to the pinned column spelling",
1526
  jr and jr[0].get("sales_by_asin_ordered_product_sales_amount") == 27.3
1527
  and jr[0].get("traffic_by_asin_buy_box_percentage") == 91.2, jr[:1])
 
1557
 
1558
  # NC-AZ15 — an empty parse is empty, never a phantom row.
1559
  ck("NC-AZ15 an empty document yields no columns and no rows",
1560
+ parse_flat_file("", **origin) == ([], [])
1561
+ and parse_json_report("", "x", **origin) == ([], []))
1562
 
1563
  # NC-AZ16..18 - both role-specific payloads keep their complete source shape and source label.
1564
  price_input = [
 
1615
  mem.execute("INSERT INTO keep_unrelated VALUES (99)")
1616
  _record_state(mem, "amzn_orders", "done", 2)
1617
  _record_state(mem, "odoo_orders", "live", 11)
1618
+ purged = _purge_mirror(mem, "fixture", "fixture")
1619
  ck("NC-AZ21 purge removes every amzn_ table, including a future one",
1620
  purged["tables"] == ["amzn_future_table", "amzn_orders", "amzn_pricing"]
1621
  and purged["rows"] == 5, purged)
 
1628
  "SELECT phase, rows FROM _sync_state WHERE entity='odoo_orders'").fetchone()
1629
  ck("NC-AZ23 purge preserves unrelated tables and sync markers byte for byte",
1630
  kept == [(99,)] and kept_state == ("live", 11), (kept, kept_state))
1631
+ second = _purge_mirror(mem, "fixture", "fixture")
1632
  ck("NC-AZ24 purge readback is residue-free and a retry is idempotent",
1633
  second == {"tables": [], "rows": 0, "syncMarkers": 0,
1634
  "residueTables": [], "residueSyncMarkers": []}, second)
 
1683
  key = "qa-purge"
1684
  datastore_path = purge_path
1685
 
1686
+ def __init__(self, entries):
1687
+ super().__init__(entries)
1688
+ self.docs = {}
1689
+
1690
+ def get(self, name, fresh=False):
1691
+ from copy import deepcopy
1692
+ return deepcopy(self.docs[name]) if name in self.docs else super().get(name)
1693
+
1694
+ def update(self, name, fn, flush="sync"):
1695
+ from copy import deepcopy
1696
+ assert flush == "sync"
1697
+ doc = deepcopy(self.docs.get(name) or {})
1698
+ fn(doc)
1699
+ self.docs[name] = doc
1700
+
1701
  def assert_datastore_matches(self):
1702
  if Path(datastore.DB_PATH).resolve() != purge_path.resolve():
1703
  raise RuntimeError("wrong test mirror")
1704
 
1705
+ # A C2 shim is confined to this offline fixture; product paths never substitute it.
1706
+ from types import ModuleType
1707
+ from unittest.mock import patch
1708
+ audit_fixture = ModuleType("core.audit")
1709
+ events = []
1710
+ audit_fixture.record = lambda *args: events.append(args)
1711
+ with patch.dict(sys.modules, {"core.audit": audit_fixture}):
1712
+ public_detail = purge(
1713
+ "qa-purge", "qa-purge", rt=_PurgeRuntime({}), log=lambda *_a: None)
1714
  datastore.use_path(prior_path)
1715
  readback = duckdb.connect(str(purge_path), read_only=True)
1716
  tables_after = sorted(str(row[0]) for row in readback.execute("SHOW TABLES").fetchall())
 
1719
  public_ok = (public_detail["tenant"] == "qa-purge"
1720
  and public_detail["database"] == "qa-purge.duckdb"
1721
  and public_detail["rows"] == 1
1722
+ and tables_after == ["_sync_state"] and state_after == []
1723
+ and len(events) == 1 and events[0][0] == "data.purge")
1724
  finally:
1725
  datastore.use_path(prior_path)
1726
  ck("NC-AZ27 the public purge wrapper deletes and reads back an isolated tenant file",
 
1737
  ap.add_argument("--validate", action="store_true")
1738
  ap.add_argument("--purge", action="store_true",
1739
  help="permanently delete every Amazon mirror table after credential revocation")
1740
+ ap.add_argument("--deletion-trigger", choices=DELETION_TRIGGERS)
1741
+ ap.add_argument("--trigger-at", help="original event timestamp with UTC offset")
1742
+ ap.add_argument("--retention-check", action="store_true")
1743
+ ap.add_argument("--restore-from", help="existing backup file to restore as a checked copy")
1744
+ ap.add_argument("--restore-to", help="new copy beside the tenant mirror, never the live file")
1745
  ap.add_argument("--selftest", action="store_true")
1746
  ap.add_argument("--tenant", default=None)
1747
  ap.add_argument("--confirm-tenant", default=None,
1748
+ help="for --purge or --restore-from, repeat the exact tenant slug")
1749
  ap.add_argument("--table", action="append", help="limit to one table (repeatable)")
1750
  a = ap.parse_args(argv)
1751
+ if sum(bool(v) for v in (a.sync, a.status, a.validate, a.purge, a.selftest,
1752
+ a.deletion_trigger, a.retention_check, a.restore_from)) > 1:
1753
+ ap.error("choose exactly one action")
1754
+ if a.trigger_at and not a.deletion_trigger:
1755
+ ap.error("--trigger-at requires --deletion-trigger")
1756
+ if bool(a.restore_from) != bool(a.restore_to):
1757
+ ap.error("--restore-from and --restore-to are required together")
1758
+ if a.deletion_trigger or a.retention_check or a.restore_from:
1759
+ if not a.tenant or a.table:
1760
+ ap.error("lifecycle actions require an explicit --tenant and no --table")
1761
+ if a.deletion_trigger:
1762
+ rep = record_deletion_trigger(a.tenant, a.deletion_trigger, occurred_at=a.trigger_at)
1763
+ elif a.restore_from:
1764
+ rep = restore(a.tenant, a.confirm_tenant, a.restore_from, a.restore_to)
1765
+ else:
1766
+ rep = retention_check(a.tenant)
1767
+ print(json.dumps(rep, indent=2))
1768
+ return 1 if rep.get("state") == "OVERDUE" else 0
1769
  tenant = a.tenant or "royal-imports"
1770
  if a.purge:
1771
  if not a.tenant:
platform/modules/sheet.py CHANGED
@@ -34,8 +34,8 @@ from __future__ import annotations
34
  import datetime
35
  import re
36
 
37
- #: C2's aggregate vocabulary. `metric_key` is the other arm of that union, and W53-T13 answers it
38
- #: by NAME rather than leaving it dead: see `metric_key_refusal` and its refusal's own note.
39
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
40
 
41
  #: ⭐ R9's PERIOD (wave 51, W51-T21). The three units a bound cell can be pinned to, and the month
@@ -46,6 +46,9 @@ PERIOD_UNITS = ("month", "quarter", "year")
46
  #: named by the month they open on, and one spelling means a copied cell cannot mean two things.
47
  _PERIOD_START = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
48
 
 
 
 
49
  #: A `period.ref` points at a cell that holds the period, so it is a plain A1 address with no `$`,
50
  #: exactly as `core/sheets.py::_ADDR` spells one.
51
  _PERIOD_REF = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
@@ -83,15 +86,26 @@ REFUSALS = {
83
  # column somebody asked to sum), and computing it in one place is what stops three doors
84
  # wording the same fact three ways ([[one-question-two-normalizers]]).
85
  "field_not_aggregable": "{subject} cannot be totalled on this database, because {detail}",
86
- # ⭐ C2's OTHER aggregate arm. `{metric_key}` names a number measured over a whole SET, and a
87
- # set measure is not additive: summing a per-record average or a percentage over the rows this
88
- # cell scopes produces a confident wrong number. The Metric COLUMN path answers the same
89
- # question honestly, per database and per period, which is exactly ruling R7, so the sentence
90
- # sends the reader there rather than stopping at "no".
91
  "metric_key_unsupported": "{subject} is measured over a whole set of records rather than "
92
  "stored on each one, so this cell cannot total it directly. Add a "
93
  "Metric column for it on this database, then point this cell at "
94
  "that column.",
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  # ── C5's two sharing refusals (wave 51, W51-T25) ──────────────────────────────────────────
96
  #
97
  # ⭐⭐ THEY LIVE HERE, WITH C2's, BECAUSE THIS DICT IS THE ONE PLACE A SHEET REFUSAL IS
@@ -130,7 +144,10 @@ class SheetRefusal(Exception):
130
 
131
 
132
  def clean_period(raw):
133
- """R9's period, or None. `{unit, start, locked, ref?}`, with `{ref}` / `{window}` still read.
 
 
 
134
 
135
  ⛔ AN UNKNOWN UNIT OR A MALFORMED START IS REFUSED BY NAME, and that is not the same call as
136
  the cosmetic keys next door. A period decides WHICH ROWS ARE COUNTED. Dropping `unit: "week"`
@@ -148,9 +165,10 @@ def clean_period(raw):
148
  fills the missing start with TODAY'S MONTH and shows it as a chosen period. The next save then
149
  stamps `{unit: "month", start: <this month>}` over a cell nobody meant to narrow: an all-time
150
  total silently becomes this month's, which is exactly what D-660 names. So a period must name a
151
- window - a `start`, the legacy `window`, or R14's `ref` - or it is dropped and the cell stays
152
- all time. ⚠ THE ORDER MATTERS: an unknown unit or a malformed start is still REFUSED BY NAME
153
- above, because a wrong period and an absent one are different answers.
 
154
  """
155
  if not isinstance(raw, dict):
156
  return None
@@ -168,6 +186,21 @@ def clean_period(raw):
168
  raise SheetRefusal("period_invalid", start)
169
  out["start"] = start
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  if raw.get("locked") is True:
172
  out["locked"] = True
173
 
@@ -175,17 +208,20 @@ def clean_period(raw):
175
  if ref:
176
  if not _PERIOD_REF.match(ref):
177
  raise SheetRefusal("period_invalid", ref)
178
- out["ref"] = ref
 
179
 
180
  #: ⚠ The wave-49 spelling, kept so a binding written before R9 still round trips. It is not a
181
  #: second dialect for the same thing: `window` is a raw relative window, `unit` + `start` is a
182
  #: named calendar period, and a document carrying the old one is not rewritten on read.
183
- if raw.get("window") is not None and "unit" not in out and "start" not in out:
 
184
  out["window"] = raw["window"]
185
 
186
  #: ⛔ D-660: see the docstring. A unit on its own, a lock on its own, or the empty dict names no
187
- #: window, so it is not a period and the cell keeps its all-time answer.
188
- if not ({"start", "window", "ref"} & set(out)):
 
189
  return None
190
  return out
191
 
@@ -218,6 +254,9 @@ def period_window(period):
218
  the following month into a monthly cell. It is computed as "the day before the month after the
219
  period", never as a 28/30/31 table, so February and a leap year need no special case.
220
 
 
 
 
221
  ⚠ A `{window}` PERIOD (the wave-49 spelling `clean_period` still round trips) IS RETURNED AS
222
  IT STANDS. It already IS a window spec; normalising it here would be this module's second
223
  opinion about a vocabulary `harness/windows.py` owns, and `normalize` refuses anything it does
@@ -231,6 +270,8 @@ def period_window(period):
231
  """
232
  if not isinstance(period, dict):
233
  return None
 
 
234
  if period.get("window") is not None:
235
  return period["window"]
236
  start = str(period.get("start") or "").strip()
@@ -353,29 +394,38 @@ def aggregate_refusal(aggregate, field):
353
  return None
354
 
355
 
356
- def metric_key_refusal(aggregate):
357
- """The named refusal for C2's `{metric_key}` arm, or None when the binding is not that arm.
358
-
359
- ⛔⛔ IT IS ANSWERED RATHER THAN LEFT TO FALL THROUGH, and that is the whole of W53-T13's (d).
360
- `clean_binding` accepts `{metric_key}` and nothing downstream ever resolved it, so it reached
361
- `aggregate_sql` with no `fn` and no `field` and died as `field_unknown` with an EMPTY subject:
362
- "That column is not a column on this database." Measured on the running app for
363
- `{"metric_key": "revenue"}`. That sentence names nothing and is not even true.
364
-
365
- ⭐ WHY IT REFUSES RATHER THAN RESOLVES, and this is standing rule 9 read forwards. A metric is
366
- measured over a SET: `harness/measure_filter.py::resolve_series`' own docstring records the
367
- additivity law it obeys, that a non-additive measure (an average, a percentage) is computed at
368
- POOL grain and never folded from per-record answers. A bare metric key carries no aggregate
369
- and no window, so resolving it here would mean choosing both, and choosing `sum` would print a
370
- wrong number for every ratio metric in the catalogue with nothing to notice. The Metric COLUMN
371
- path answers the same question with the aggregate and the window both DECLARED, per database,
372
- which is precisely what R7 asked for, so the sentence sends the reader one step sideways
373
- rather than stopping them.
374
  """
375
- key = str((aggregate or {}).get("metric_key") or "").strip()
376
- if not key:
377
- return None
378
- return SheetRefusal("metric_key_unsupported", key)
 
 
 
 
 
 
 
 
 
 
 
 
 
379
 
380
 
381
  def period_limits(period, aggregate, field, bounded_keys=(), depends=()):
@@ -482,7 +532,8 @@ def clean_binding(raw):
482
 
483
  `Binding = {database, aggregate:{fn, field?} | {metric_key},
484
  scope:{view_id} | {filter} (+ adoptedFrom?),
485
- period?: {unit, start, locked, ref?} | {window}, onDrag?: {across, down}}`
 
486
  """
487
  if not isinstance(raw, dict):
488
  raise SheetRefusal("binding_invalid")
 
34
  import datetime
35
  import re
36
 
37
+ #: C2's aggregate vocabulary. W59-T14 resolves the `metric_key` arm through a Metric column,
38
+ #: using only the catalogue's declared fold: see `metric_key_fold` and its additivity guard.
39
  AGGREGATE_FNS = ("sum", "count", "avg", "min", "max")
40
 
41
  #: ⭐ R9's PERIOD (wave 51, W51-T21). The three units a bound cell can be pinned to, and the month
 
46
  #: named by the month they open on, and one spelling means a copied cell cannot mean two things.
47
  _PERIOD_START = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
48
 
49
+ #: Literal inclusive endpoints of a frozen calendar period, spelled `YYYY-MM-DD`.
50
+ _PERIOD_DAY = re.compile(r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$")
51
+
52
  #: A `period.ref` points at a cell that holds the period, so it is a plain A1 address with no `$`,
53
  #: exactly as `core/sheets.py::_ADDR` spells one.
54
  _PERIOD_REF = re.compile(r"^[A-Z]{1,3}[1-9][0-9]{0,6}$")
 
86
  # column somebody asked to sum), and computing it in one place is what stops three doors
87
  # wording the same fact three ways ([[one-question-two-normalizers]]).
88
  "field_not_aggregable": "{subject} cannot be totalled on this database, because {detail}",
89
+ # W59-T14 / R10: now unreachable. The route creates or reuses the Metric column after
90
+ # admission and the declared-aggregate check, resolving the missing-column condition.
91
+ # Keep the code declared for the refusal vocabulary contract.
 
 
92
  "metric_key_unsupported": "{subject} is measured over a whole set of records rather than "
93
  "stored on each one, so this cell cannot total it directly. Add a "
94
  "Metric column for it on this database, then point this cell at "
95
  "that column.",
96
+ "metric_not_additive": "{subject} cannot be totalled from per-record values. Choose a sum "
97
+ "or count measure in the cell's Metric section instead.",
98
+ "metric_column_conflict": "A column already uses the key for {subject}. Open this "
99
+ "database's Fields and bind the cell to a visible Metric column "
100
+ "for that measure.",
101
+ "metric_period_required": "{subject} is measured over a period, so this cell needs one. "
102
+ "Open the cell's Period section and choose a period.",
103
+ "measure_not_offered": "{subject} is not an available Metric on this database. Choose a "
104
+ "Metric offered here or select a database that offers it.",
105
+ "metric_column_unavailable": "{subject} cannot be materialised as a Metric column with a "
106
+ "supported aggregate. Choose another Metric or use a numeric field.",
107
+ "metric_column_create_failed": "The Metric column for {subject} could not be saved. Try "
108
+ "binding the cell again or add it from the database's Fields panel.",
109
  # ── C5's two sharing refusals (wave 51, W51-T25) ──────────────────────────────────────────
110
  #
111
  # ⭐⭐ THEY LIVE HERE, WITH C2's, BECAUSE THIS DICT IS THE ONE PLACE A SHEET REFUSAL IS
 
144
 
145
 
146
  def clean_period(raw):
147
+ """R9's period, or None. `{unit, start, locked?, ref?}`, with `{ref}` / `{window}` still read.
148
+
149
+ A frozen period is `{unit, start, locked?, frozen: true, from, to}`. `frozen` stores only
150
+ True so freezing and unfreezing returns to the identical rolling period already stored.
151
 
152
  ⛔ AN UNKNOWN UNIT OR A MALFORMED START IS REFUSED BY NAME, and that is not the same call as
153
  the cosmetic keys next door. A period decides WHICH ROWS ARE COUNTED. Dropping `unit: "week"`
 
165
  fills the missing start with TODAY'S MONTH and shows it as a chosen period. The next save then
166
  stamps `{unit: "month", start: <this month>}` over a cell nobody meant to narrow: an all-time
167
  total silently becomes this month's, which is exactly what D-660 names. So a period must name a
168
+ window - a `start`, validated frozen dates, the legacy `window`, or R14's `ref` - or it is
169
+ dropped and the cell stays all time. ⚠ THE ORDER MATTERS: an unknown unit or a malformed
170
+ start is still REFUSED BY NAME above, as are missing or malformed frozen dates, because a
171
+ wrong period and an absent one are different answers.
172
  """
173
  if not isinstance(raw, dict):
174
  return None
 
186
  raise SheetRefusal("period_invalid", start)
187
  out["start"] = start
188
 
189
+ if raw.get("frozen") is True:
190
+ dates = {}
191
+ for key in ("from", "to"):
192
+ value = str(raw.get(key) or "").strip()
193
+ # ⚠ `value or key` because a MISSING date has no value to name, and a refusal with an
194
+ # empty subject reads as " is not a period this cell can use" - the same blank-subject
195
+ # defect the Metric binding originally exposed.
196
+ if not _PERIOD_DAY.fullmatch(value):
197
+ raise SheetRefusal("period_invalid", value or key)
198
+ dates[key] = value
199
+ # ISO days have fixed-width year/month/day parts, so string order is date order.
200
+ if dates["to"] < dates["from"]:
201
+ raise SheetRefusal("period_invalid", dates["to"])
202
+ out.update({"frozen": True, **dates})
203
+
204
  if raw.get("locked") is True:
205
  out["locked"] = True
206
 
 
208
  if ref:
209
  if not _PERIOD_REF.match(ref):
210
  raise SheetRefusal("period_invalid", ref)
211
+ if not out.get("frozen"):
212
+ out["ref"] = ref
213
 
214
  #: ⚠ The wave-49 spelling, kept so a binding written before R9 still round trips. It is not a
215
  #: second dialect for the same thing: `window` is a raw relative window, `unit` + `start` is a
216
  #: named calendar period, and a document carrying the old one is not rewritten on read.
217
+ if (raw.get("window") is not None and "unit" not in out and "start" not in out
218
+ and not out.get("frozen")):
219
  out["window"] = raw["window"]
220
 
221
  #: ⛔ D-660: see the docstring. A unit on its own, a lock on its own, or the empty dict names no
222
+ #: window, so it is not a period and the cell keeps its all-time answer. A frozen period
223
+ #: names its window through the two literal dates already validated above.
224
+ if not ({"start", "window", "ref", "frozen"} & set(out)):
225
  return None
226
  return out
227
 
 
254
  the following month into a monthly cell. It is computed as "the day before the month after the
255
  period", never as a 28/30/31 table, so February and a leap year need no special case.
256
 
257
+ A frozen period returns the person's own two dates and ignores `unit` / `start`, which is
258
+ why unfreezing restores their derived range.
259
+
260
  ⚠ A `{window}` PERIOD (the wave-49 spelling `clean_period` still round trips) IS RETURNED AS
261
  IT STANDS. It already IS a window spec; normalising it here would be this module's second
262
  opinion about a vocabulary `harness/windows.py` owns, and `normalize` refuses anything it does
 
270
  """
271
  if not isinstance(period, dict):
272
  return None
273
+ if period.get("frozen") is True and period.get("from") and period.get("to"):
274
+ return {"kind": "custom", "from": period["from"], "to": period["to"]}
275
  if period.get("window") is not None:
276
  return period["window"]
277
  start = str(period.get("start") or "").strip()
 
394
  return None
395
 
396
 
397
+ def metric_key_fold(measure_key, declared_agg):
398
+ """The column fold for a declared additive measure; otherwise a named refusal.
399
+
400
+ W53-T13's original refusal answered a bare key rather than letting it die as field_unknown
401
+ with an empty subject. Its hazard remains: a metric is measured over a SET, and
402
+ `harness/measure_filter.py::resolve_series` computes non-additive measures at POOL grain,
403
+ never by folding per-record answers. A bare metric key carries no aggregate and no window,
404
+ so resolving it here would mean choosing both, and choosing `sum` would print a wrong
405
+ number for every ratio metric in the catalogue with nothing to notice.
406
+
407
+ R10 resolves only `sum` and `count`: both add across entities, so their per-record answers
408
+ fold with SUM, never COUNT of the column. Ratio, derived and distinct-count declarations
409
+ still refuse. The route reads `semantic.metrics()[key]['agg']` and requires the cell's
410
+ declared period before creating a column; this pure module guesses neither one.
 
 
 
 
411
  """
412
+ if declared_agg in ("sum", "count"):
413
+ return "sum"
414
+ raise SheetRefusal("metric_not_additive", measure_key)
415
+
416
+
417
+ def measure_column_key(measure_key, window):
418
+ """Identity of a measure at an already normalised window, without a second window cleaner.
419
+
420
+ Mirrors `customer-grid/types.ts::windowKey` (`kind|n|from|to`) and `measureColumnIndex`.
421
+ Callers normalise through `harness.windows.normalize`, just as the client calls
422
+ `normalizeWindow`. The route prefers this exact identity but reuses any column of the same
423
+ measure when no window matches, because the cell re-resolves it at its own period.
424
+ """
425
+ w = window if isinstance(window, dict) else {}
426
+ parts = [str(w.get(k)) if w.get(k) is not None else ""
427
+ for k in ("kind", "n", "from", "to")]
428
+ return str(measure_key) + "|" + ("|".join(parts) if w else "")
429
 
430
 
431
  def period_limits(period, aggregate, field, bounded_keys=(), depends=()):
 
532
 
533
  `Binding = {database, aggregate:{fn, field?} | {metric_key},
534
  scope:{view_id} | {filter} (+ adoptedFrom?),
535
+ period?: {unit, start, locked?, ref?} | {unit, start, locked?, frozen: true, from, to}
536
+ | {window}, onDrag?: {across, down}}`
537
  """
538
  if not isinstance(raw, dict):
539
  raise SheetRefusal("binding_invalid")
web/package-lock.json CHANGED
@@ -26,6 +26,10 @@
26
  "typescript": "~6.0.2",
27
  "vite": "^8.1.1",
28
  "vite-plugin-singlefile": "^2.3.3"
 
 
 
 
29
  }
30
  },
31
  "node_modules/@babel/code-frame": {
@@ -56,7 +60,6 @@
56
  "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
57
  "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
58
  "license": "MIT",
59
- "peer": true,
60
  "dependencies": {
61
  "@babel/code-frame": "^7.29.7",
62
  "@babel/generator": "^7.29.7",
@@ -326,6 +329,7 @@
326
  "dev": true,
327
  "license": "MIT",
328
  "optional": true,
 
329
  "dependencies": {
330
  "@emnapi/wasi-threads": "1.2.3",
331
  "tslib": "^2.4.0"
@@ -338,6 +342,19 @@
338
  "dev": true,
339
  "license": "MIT",
340
  "optional": true,
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  "dependencies": {
342
  "tslib": "^2.4.0"
343
  }
@@ -1184,7 +1201,6 @@
1184
  "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
1185
  "dev": true,
1186
  "license": "MIT",
1187
- "peer": true,
1188
  "dependencies": {
1189
  "undici-types": "~7.18.0"
1190
  }
@@ -1202,7 +1218,6 @@
1202
  "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
1203
  "dev": true,
1204
  "license": "MIT",
1205
- "peer": true,
1206
  "dependencies": {
1207
  "@types/prop-types": "*",
1208
  "csstype": "^3.2.2"
@@ -1341,7 +1356,6 @@
1341
  }
1342
  ],
1343
  "license": "MIT",
1344
- "peer": true,
1345
  "dependencies": {
1346
  "baseline-browser-mapping": "^2.10.44",
1347
  "caniuse-lite": "^1.0.30001806",
@@ -1386,7 +1400,8 @@
1386
  "version": "2.5.1",
1387
  "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
1388
  "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
1389
- "license": "MIT"
 
1390
  },
1391
  "node_modules/cliui": {
1392
  "version": "9.0.1",
@@ -2210,8 +2225,7 @@
2210
  "version": "4.18.1",
2211
  "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
2212
  "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
2213
- "license": "MIT",
2214
- "peer": true
2215
  },
2216
  "node_modules/loose-envify": {
2217
  "version": "1.4.0",
@@ -2239,7 +2253,6 @@
2239
  "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz",
2240
  "integrity": "sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==",
2241
  "license": "MIT",
2242
- "peer": true,
2243
  "bin": {
2244
  "marked": "bin/marked.js"
2245
  },
@@ -2328,6 +2341,7 @@
2328
  "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
2329
  "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
2330
  "license": "MIT",
 
2331
  "engines": {
2332
  "node": ">=0.10.0"
2333
  }
@@ -2444,7 +2458,6 @@
2444
  "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
2445
  "dev": true,
2446
  "license": "MIT",
2447
- "peer": true,
2448
  "engines": {
2449
  "node": ">=12"
2450
  },
@@ -2486,6 +2499,7 @@
2486
  "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
2487
  "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
2488
  "license": "MIT",
 
2489
  "dependencies": {
2490
  "loose-envify": "^1.4.0",
2491
  "object-assign": "^4.1.1",
@@ -2497,7 +2511,6 @@
2497
  "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
2498
  "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
2499
  "license": "MIT",
2500
- "peer": true,
2501
  "dependencies": {
2502
  "loose-envify": "^1.1.0"
2503
  },
@@ -2510,7 +2523,6 @@
2510
  "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
2511
  "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
2512
  "license": "MIT",
2513
- "peer": true,
2514
  "dependencies": {
2515
  "loose-envify": "^1.1.0",
2516
  "scheduler": "^0.23.2"
@@ -2524,6 +2536,7 @@
2524
  "resolved": "https://registry.npmjs.org/react-easy-swipe/-/react-easy-swipe-0.0.21.tgz",
2525
  "integrity": "sha512-OeR2jAxdoqUMHIn/nS9fgreI5hSpgGoL5ezdal4+oO7YSSgJR8ga+PkYGJrSrJ9MKlPcQjMQXnketrD7WNmNsg==",
2526
  "license": "MIT",
 
2527
  "dependencies": {
2528
  "prop-types": "^15.5.8"
2529
  },
@@ -2544,7 +2557,8 @@
2544
  "version": "16.13.1",
2545
  "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
2546
  "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
2547
- "license": "MIT"
 
2548
  },
2549
  "node_modules/react-number-format": {
2550
  "version": "5.4.5",
@@ -2804,7 +2818,6 @@
2804
  "resolved": "https://registry.npmjs.org/vega/-/vega-6.3.1.tgz",
2805
  "integrity": "sha512-mX5tvY3ISCSiPPmunuZyQfccq0XlUvJd2t5oyc6SNS0N0TwnPNoklx0mVod5n+qbzuUoiuxl7Ve/SvoRqH4RzA==",
2806
  "license": "BSD-3-Clause",
2807
- "peer": true,
2808
  "dependencies": {
2809
  "vega-crossfilter": "~5.1.2",
2810
  "vega-dataflow": "~6.1.2",
@@ -3026,7 +3039,6 @@
3026
  "resolved": "https://registry.npmjs.org/vega-lite/-/vega-lite-6.4.3.tgz",
3027
  "integrity": "sha512-d/7hPjfz560UERaQuTmGgIVfXAe3g2hJWeC+igDeaGohUdEoNrHLXgR/yTOBT8vV/lIuuKnw+0/xWWblkDwkMQ==",
3028
  "license": "BSD-3-Clause",
3029
- "peer": true,
3030
  "dependencies": {
3031
  "json-stringify-pretty-compact": "~4.0.0",
3032
  "tslib": "~2.8.1",
@@ -3297,7 +3309,6 @@
3297
  "integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==",
3298
  "dev": true,
3299
  "license": "MIT",
3300
- "peer": true,
3301
  "dependencies": {
3302
  "lightningcss": "^1.32.0",
3303
  "picomatch": "^4.0.5",
 
26
  "typescript": "~6.0.2",
27
  "vite": "^8.1.1",
28
  "vite-plugin-singlefile": "^2.3.3"
29
+ },
30
+ "engines": {
31
+ "node": "22.x",
32
+ "npm": "10.x"
33
  }
34
  },
35
  "node_modules/@babel/code-frame": {
 
60
  "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
61
  "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
62
  "license": "MIT",
 
63
  "dependencies": {
64
  "@babel/code-frame": "^7.29.7",
65
  "@babel/generator": "^7.29.7",
 
329
  "dev": true,
330
  "license": "MIT",
331
  "optional": true,
332
+ "peer": true,
333
  "dependencies": {
334
  "@emnapi/wasi-threads": "1.2.3",
335
  "tslib": "^2.4.0"
 
342
  "dev": true,
343
  "license": "MIT",
344
  "optional": true,
345
+ "peer": true,
346
+ "dependencies": {
347
+ "tslib": "^2.4.0"
348
+ }
349
+ },
350
+ "node_modules/@emnapi/runtime": {
351
+ "version": "1.11.3",
352
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
353
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
354
+ "dev": true,
355
+ "license": "MIT",
356
+ "optional": true,
357
+ "peer": true,
358
  "dependencies": {
359
  "tslib": "^2.4.0"
360
  }
 
1201
  "integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
1202
  "dev": true,
1203
  "license": "MIT",
 
1204
  "dependencies": {
1205
  "undici-types": "~7.18.0"
1206
  }
 
1218
  "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
1219
  "dev": true,
1220
  "license": "MIT",
 
1221
  "dependencies": {
1222
  "@types/prop-types": "*",
1223
  "csstype": "^3.2.2"
 
1356
  }
1357
  ],
1358
  "license": "MIT",
 
1359
  "dependencies": {
1360
  "baseline-browser-mapping": "^2.10.44",
1361
  "caniuse-lite": "^1.0.30001806",
 
1400
  "version": "2.5.1",
1401
  "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
1402
  "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
1403
+ "license": "MIT",
1404
+ "peer": true
1405
  },
1406
  "node_modules/cliui": {
1407
  "version": "9.0.1",
 
2225
  "version": "4.18.1",
2226
  "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
2227
  "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
2228
+ "license": "MIT"
 
2229
  },
2230
  "node_modules/loose-envify": {
2231
  "version": "1.4.0",
 
2253
  "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz",
2254
  "integrity": "sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==",
2255
  "license": "MIT",
 
2256
  "bin": {
2257
  "marked": "bin/marked.js"
2258
  },
 
2341
  "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
2342
  "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
2343
  "license": "MIT",
2344
+ "peer": true,
2345
  "engines": {
2346
  "node": ">=0.10.0"
2347
  }
 
2458
  "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
2459
  "dev": true,
2460
  "license": "MIT",
 
2461
  "engines": {
2462
  "node": ">=12"
2463
  },
 
2499
  "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
2500
  "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
2501
  "license": "MIT",
2502
+ "peer": true,
2503
  "dependencies": {
2504
  "loose-envify": "^1.4.0",
2505
  "object-assign": "^4.1.1",
 
2511
  "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
2512
  "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
2513
  "license": "MIT",
 
2514
  "dependencies": {
2515
  "loose-envify": "^1.1.0"
2516
  },
 
2523
  "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
2524
  "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
2525
  "license": "MIT",
 
2526
  "dependencies": {
2527
  "loose-envify": "^1.1.0",
2528
  "scheduler": "^0.23.2"
 
2536
  "resolved": "https://registry.npmjs.org/react-easy-swipe/-/react-easy-swipe-0.0.21.tgz",
2537
  "integrity": "sha512-OeR2jAxdoqUMHIn/nS9fgreI5hSpgGoL5ezdal4+oO7YSSgJR8ga+PkYGJrSrJ9MKlPcQjMQXnketrD7WNmNsg==",
2538
  "license": "MIT",
2539
+ "peer": true,
2540
  "dependencies": {
2541
  "prop-types": "^15.5.8"
2542
  },
 
2557
  "version": "16.13.1",
2558
  "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
2559
  "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
2560
+ "license": "MIT",
2561
+ "peer": true
2562
  },
2563
  "node_modules/react-number-format": {
2564
  "version": "5.4.5",
 
2818
  "resolved": "https://registry.npmjs.org/vega/-/vega-6.3.1.tgz",
2819
  "integrity": "sha512-mX5tvY3ISCSiPPmunuZyQfccq0XlUvJd2t5oyc6SNS0N0TwnPNoklx0mVod5n+qbzuUoiuxl7Ve/SvoRqH4RzA==",
2820
  "license": "BSD-3-Clause",
 
2821
  "dependencies": {
2822
  "vega-crossfilter": "~5.1.2",
2823
  "vega-dataflow": "~6.1.2",
 
3039
  "resolved": "https://registry.npmjs.org/vega-lite/-/vega-lite-6.4.3.tgz",
3040
  "integrity": "sha512-d/7hPjfz560UERaQuTmGgIVfXAe3g2hJWeC+igDeaGohUdEoNrHLXgR/yTOBT8vV/lIuuKnw+0/xWWblkDwkMQ==",
3041
  "license": "BSD-3-Clause",
 
3042
  "dependencies": {
3043
  "json-stringify-pretty-compact": "~4.0.0",
3044
  "tslib": "~2.8.1",
 
3309
  "integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==",
3310
  "dev": true,
3311
  "license": "MIT",
 
3312
  "dependencies": {
3313
  "lightningcss": "^1.32.0",
3314
  "picomatch": "^4.0.5",
web/package.json CHANGED
@@ -3,6 +3,10 @@
3
  "private": true,
4
  "version": "0.0.0",
5
  "type": "module",
 
 
 
 
6
  "scripts": {
7
  "dev": "vite",
8
  "build": "tsc -b && vite build",
 
3
  "private": true,
4
  "version": "0.0.0",
5
  "type": "module",
6
+ "engines": {
7
+ "node": "22.x",
8
+ "npm": "10.x"
9
+ },
10
  "scripts": {
11
  "dev": "vite",
12
  "build": "tsc -b && vite build",
web/src/connectors/ConnectorModal.tsx CHANGED
@@ -45,7 +45,7 @@
45
  // ---------------------------------------------------------------------------
46
 
47
  import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
48
- import { API_V1, CREDENTIALS } from "../apiContract";
49
  import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
50
  import { ConfirmDialog } from "../ui/ConfirmDialog";
51
  import { brandForConnector } from "./brandMarks";
@@ -53,7 +53,7 @@ import DatabasesTab from "./DatabasesTab";
53
  import type { MaterializationCapability } from "./materializationJobs";
54
  import "../styles/wave58/connectors.css";
55
  import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab";
56
- import KeychainTab from "./KeychainTab";
57
  import MonidRunDialog from "./MonidRunDialog";
58
  import { SyncCadenceTab } from "./OdooConfig";
59
  import RelationshipDiagram from "./RelationshipDiagram";
@@ -68,6 +68,7 @@ import { parseRelationshipGraph } from "./ConnectorsPage";
68
  import "../styles/wave49/connectors.css";
69
  import "../styles/wave52/connectors.css";
70
  import "../styles/wave55/connectors.css";
 
71
 
72
  /** R26's original four, plus "cadence" (W52-T04, the done-when's "sync cadence" section). */
73
  export type ConnectorTab = "overview" | "keychain" | "databases" | "relationships" | "cadence";
@@ -133,6 +134,8 @@ export interface ConnectorKeychainEntry {
133
  testable: boolean;
134
  /** Server-owned admin permission for the write-only replacement flow. */
135
  replaceable: boolean;
 
 
136
  }
137
 
138
  /**
@@ -148,6 +151,7 @@ export interface ConnectorConnectField {
148
  label: string;
149
  /** Renders as a password box, and is never echoed back. */
150
  secret: boolean;
 
151
  }
152
 
153
  export interface ConnectorConnectSpec {
@@ -300,6 +304,7 @@ function parseKeychainHalf(raw: unknown): ConnectorKeychainHalf {
300
  scope: str(entry.scope).trim(),
301
  testable: entry.testable === true,
302
  replaceable: entry.replaceable === true,
 
303
  });
304
  }
305
  return {
@@ -327,7 +332,9 @@ export function parseConnectSpec(raw: unknown): ConnectorConnectSpec | null {
327
  const field = obj(item);
328
  const key = str(field.key).trim();
329
  if (!key) continue;
330
- fields.push({ key, label: str(field.label).trim() || key, secret: field.secret === true });
 
 
331
  }
332
  if (!fields.length) return null;
333
  const scopes = parseStrings(source.scopes);
@@ -729,6 +736,22 @@ type Load =
729
  | { phase: "ready"; detail: ConnectorDetail }
730
  | { phase: "error"; message: string };
731
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732
  type PendingLeave = { kind: "close" } | { kind: "tab"; tab: ConnectorTab } | null;
733
 
734
  /**
@@ -759,9 +782,13 @@ export default function ConnectorModal({
759
  */
760
  onOpenDatabases?: () => void;
761
  }) {
 
762
  const panelRef = useRef<HTMLDivElement>(null);
763
  const [tab, setTab] = useState<ConnectorTab>(initialTab);
764
- const [load, setLoad] = useState<Load>({ phase: "loading" });
 
 
 
765
  const databasesRef = useRef<DatabasesTabHandle>(null);
766
  const [databasePendingCount, setDatabasePendingCount] = useState(0);
767
  const [databaseTabBusy, setDatabaseTabBusy] = useState(false);
@@ -776,9 +803,11 @@ export default function ConnectorModal({
776
  const [reads, setReads] = useState(0);
777
  const [databaseReveal, setDatabaseReveal] = useState<DatabaseReveal | null>(null);
778
  const reread = useCallback((reveal?: DatabaseReveal) => {
 
 
779
  if (reveal) setDatabaseReveal(reveal);
780
  setReads((n) => n + 1);
781
- }, []);
782
  /**
783
  * ⭐⭐ W49-T19 · R31 — THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB.
784
  * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps
@@ -861,46 +890,83 @@ export default function ConnectorModal({
861
  restoreFocus: true,
862
  });
863
 
864
- const connectorKey = row.key;
865
  useEffect(() => {
866
  let dead = false;
867
- setLoad((current) => reads > 0 && current.phase === "ready" ? current : { phase: "loading" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868
  void (async () => {
869
  try {
870
  const res = await fetch(
871
- `${API_V1}/connectors/${encodeURIComponent(connectorKey)}/detail`,
872
- { credentials: CREDENTIALS }
873
  );
 
874
  const body = (await res.json().catch(() => null)) as
875
- | { error?: { message?: string } }
876
  | null;
877
  if (dead) return;
 
878
  if (!res.ok) {
879
- setLoad({
880
- phase: "error",
881
- message: body?.error?.message || `The server answered ${res.status}.`,
882
- });
883
- return;
884
  }
885
  const detail = parseConnectorDetail(body, connectorKey);
886
  if (!detail) {
 
 
 
 
 
 
 
 
 
887
  setLoad({
888
  phase: "error",
889
- message:
890
- "This connector's details were refused because the answer described a different connection.",
891
  });
892
- return;
893
  }
894
- setLoad({ phase: "ready", detail });
895
- } catch {
896
- if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
897
  }
898
  })();
899
  return () => {
900
  dead = true;
 
 
901
  };
 
902
  }, [connectorKey, reads]);
903
 
 
 
 
 
 
 
 
 
 
 
904
  const renderTab = useCallback(() => {
905
  // ⛔ THE KEYCHAIN TAB IS BELOW THE LOAD GUARD, and the placeholder it replaces was above it.
906
  // C4 serves the credential rows on the SAME payload as the overview, so a keychain tab that
@@ -915,9 +981,12 @@ export default function ConnectorModal({
915
  }
916
  if (load.phase === "error") {
917
  return (
918
- <p className="conn-modal-note" role="alert">
919
- {load.message}
920
- </p>
 
 
 
921
  );
922
  }
923
  if (tab === "keychain") {
@@ -982,12 +1051,21 @@ export default function ConnectorModal({
982
  );
983
  }
984
  return (
 
 
 
 
 
 
 
 
985
  <ConnectorOverviewPanel
986
  detail={load.detail}
987
  onPullReviews={canPull ? () => setPulling(true) : undefined}
988
  />
 
989
  );
990
- }, [canPull, databaseReveal, load, onOpenDatabases, reread, row, tab]);
991
 
992
  const saveDatabaseChanges = useCallback(async () => {
993
  if (!databasePendingCount || !databasesRef.current) return;
@@ -1013,7 +1091,8 @@ export default function ConnectorModal({
1013
  else setTab(destination.tab);
1014
  }, [discardDatabaseChanges, onClose, pendingLeave]);
1015
 
1016
- const status = load.phase === "ready" ? load.detail.overview.status : row.state;
 
1017
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
1018
 
1019
  return (
@@ -1036,7 +1115,10 @@ export default function ConnectorModal({
1036
  card to read a state off, so until `/detail` lands there is nothing to say and an
1037
  empty pill would be a coloured hole in the header. */}
1038
  {status ? (
1039
- <span className={"conn-modal-pill" + stateTone(status)}>{status}</span>
 
 
 
1040
  ) : null}
1041
  {tab === "databases" ? (
1042
  <div className="conn-modal-save-actions">
 
45
  // ---------------------------------------------------------------------------
46
 
47
  import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
48
+ import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT } from "../apiContract";
49
  import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
50
  import { ConfirmDialog } from "../ui/ConfirmDialog";
51
  import { brandForConnector } from "./brandMarks";
 
53
  import type { MaterializationCapability } from "./materializationJobs";
54
  import "../styles/wave58/connectors.css";
55
  import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab";
56
+ import KeychainTab, { amazonRotationNotice, RotationNotice, useRotationClock } from "./KeychainTab";
57
  import MonidRunDialog from "./MonidRunDialog";
58
  import { SyncCadenceTab } from "./OdooConfig";
59
  import RelationshipDiagram from "./RelationshipDiagram";
 
68
  import "../styles/wave49/connectors.css";
69
  import "../styles/wave52/connectors.css";
70
  import "../styles/wave55/connectors.css";
71
+ import "../styles/wave59/connectors.css";
72
 
73
  /** R26's original four, plus "cadence" (W52-T04, the done-when's "sync cadence" section). */
74
  export type ConnectorTab = "overview" | "keychain" | "databases" | "relationships" | "cadence";
 
134
  testable: boolean;
135
  /** Server-owned admin permission for the write-only replacement flow. */
136
  replaceable: boolean;
137
+ /** Public Amazon-issued timestamp, empty or absent when unknown. Never a credential field. */
138
+ client_secret_rotation_deadline?: string;
139
  }
140
 
141
  /**
 
151
  label: string;
152
  /** Renders as a password box, and is never echoed back. */
153
  secret: boolean;
154
+ default?: string;
155
  }
156
 
157
  export interface ConnectorConnectSpec {
 
304
  scope: str(entry.scope).trim(),
305
  testable: entry.testable === true,
306
  replaceable: entry.replaceable === true,
307
+ client_secret_rotation_deadline: str(entry.client_secret_rotation_deadline).trim(),
308
  });
309
  }
310
  return {
 
332
  const field = obj(item);
333
  const key = str(field.key).trim();
334
  if (!key) continue;
335
+ const parsed: ConnectorConnectField = { key, label: str(field.label).trim() || key, secret: field.secret === true };
336
+ if (typeof field.default === "string" && field.default.trim()) parsed.default = field.default;
337
+ fields.push(parsed);
338
  }
339
  if (!fields.length) return null;
340
  const scopes = parseStrings(source.scopes);
 
736
  | { phase: "ready"; detail: ConnectorDetail }
737
  | { phase: "error"; message: string };
738
 
739
+ const CONNECTOR_DETAIL_FRESHNESS_MS = 60_000;
740
+ // Measured reads take 1.34 s cold and 0.01 s warm, with a boot contended read above 8 s. Twenty seconds caps the wait a person sees.
741
+ // This is deliberately shorter than the server's thirty seconds so this component shows its own readable sentence before a bare 504.
742
+ const CONNECTOR_DETAIL_DEADLINE_MS = 20_000;
743
+ // Closing the modal unmounts it; keep the last successful read for the next open.
744
+ const connectorDetailCache = new Map<string, { detail: ConnectorDetail; at: number }>();
745
+
746
+ // Shell.tsx::signOut should call this beside clearCustomersCache when its lane can wire it.
747
+ export function clearConnectorDetailCache(): void {
748
+ connectorDetailCache.clear();
749
+ }
750
+
751
+ if (typeof window !== "undefined") {
752
+ window.addEventListener(UNAUTHORIZED_EVENT, clearConnectorDetailCache);
753
+ }
754
+
755
  type PendingLeave = { kind: "close" } | { kind: "tab"; tab: ConnectorTab } | null;
756
 
757
  /**
 
782
  */
783
  onOpenDatabases?: () => void;
784
  }) {
785
+ const connectorKey = row.key;
786
  const panelRef = useRef<HTMLDivElement>(null);
787
  const [tab, setTab] = useState<ConnectorTab>(initialTab);
788
+ const [load, setLoad] = useState<Load>(() => {
789
+ const cached = connectorDetailCache.get(connectorKey);
790
+ return cached ? { phase: "ready", detail: cached.detail } : { phase: "loading" };
791
+ });
792
  const databasesRef = useRef<DatabasesTabHandle>(null);
793
  const [databasePendingCount, setDatabasePendingCount] = useState(0);
794
  const [databaseTabBusy, setDatabaseTabBusy] = useState(false);
 
803
  const [reads, setReads] = useState(0);
804
  const [databaseReveal, setDatabaseReveal] = useState<DatabaseReveal | null>(null);
805
  const reread = useCallback((reveal?: DatabaseReveal) => {
806
+ // Evict immediately so closing just after a write cannot reuse the previous read.
807
+ connectorDetailCache.delete(connectorKey);
808
  if (reveal) setDatabaseReveal(reveal);
809
  setReads((n) => n + 1);
810
+ }, [connectorKey]);
811
  /**
812
  * ⭐⭐ W49-T19 · R31 — THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB.
813
  * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps
 
890
  restoreFocus: true,
891
  });
892
 
 
893
  useEffect(() => {
894
  let dead = false;
895
+ const cached = reads === 0 ? connectorDetailCache.get(connectorKey) : undefined;
896
+ if (reads > 0) {
897
+ connectorDetailCache.delete(connectorKey);
898
+ setLoad((current) => current.phase === "ready" ? current : { phase: "loading" });
899
+ } else if (cached) {
900
+ setLoad({ phase: "ready", detail: cached.detail });
901
+ if (Date.now() - cached.at < CONNECTOR_DETAIL_FRESHNESS_MS) return;
902
+ } else {
903
+ setLoad({ phase: "loading" });
904
+ }
905
+
906
+ const controller = new AbortController();
907
+ let timedOut = false;
908
+ const timeoutMessage = `Reading ${row.label} stopped after ${CONNECTOR_DETAIL_DEADLINE_MS / 1000} seconds because the server did not answer.`;
909
+ const timeout = setTimeout(() => {
910
+ timedOut = true;
911
+ controller.abort();
912
+ if (!dead && !cached) setLoad({ phase: "error", message: timeoutMessage });
913
+ }, CONNECTOR_DETAIL_DEADLINE_MS);
914
  void (async () => {
915
  try {
916
  const res = await fetch(
917
+ `${API_V1}/connectors/${encodeURIComponent(connectorKey)}/detail${cached ? "?revalidate=1" : ""}`,
918
+ { credentials: CREDENTIALS, signal: controller.signal }
919
  );
920
+ if (res.status === 401 || res.status === 403) clearConnectorDetailCache();
921
  const body = (await res.json().catch(() => null)) as
922
+ | { error?: { message?: string }; detail?: { error?: { message?: string } } }
923
  | null;
924
  if (dead) return;
925
+ if (timedOut) throw new Error(timeoutMessage);
926
  if (!res.ok) {
927
+ throw new Error(
928
+ body?.error?.message || body?.detail?.error?.message || `The server answered ${res.status}.`
929
+ );
 
 
930
  }
931
  const detail = parseConnectorDetail(body, connectorKey);
932
  if (!detail) {
933
+ throw new Error(
934
+ "This connector's details were refused because the answer described a different connection."
935
+ );
936
+ }
937
+ connectorDetailCache.set(connectorKey, { detail, at: Date.now() });
938
+ setLoad({ phase: "ready", detail });
939
+ } catch (error) {
940
+ // A failed background read must leave the already painted detail intact.
941
+ if (!dead && !cached) {
942
  setLoad({
943
  phase: "error",
944
+ message: timedOut ? timeoutMessage
945
+ : error instanceof Error ? error.message : "Cannot reach the server.",
946
  });
 
947
  }
948
+ } finally {
949
+ clearTimeout(timeout);
 
950
  }
951
  })();
952
  return () => {
953
  dead = true;
954
+ clearTimeout(timeout);
955
+ controller.abort();
956
  };
957
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- Omit row.label (timeout wording only); connectorKey identifies the row; verify_ui.py keychain-tab asserts this pair.
958
  }, [connectorKey, reads]);
959
 
960
+ const rotationNow = useRotationClock();
961
+ const rotationEntry = row.key === "amazon_sp" && load.phase === "ready"
962
+ ? load.detail.keychain.entries
963
+ .filter((entry) => amazonRotationNotice(entry.client_secret_rotation_deadline, rotationNow))
964
+ .sort((a, b) => Date.parse(a.client_secret_rotation_deadline || "") -
965
+ Date.parse(b.client_secret_rotation_deadline || ""))[0]
966
+ : undefined;
967
+ const rotationNotice = rotationEntry
968
+ ? amazonRotationNotice(rotationEntry.client_secret_rotation_deadline, rotationNow) : null;
969
+
970
  const renderTab = useCallback(() => {
971
  // ⛔ THE KEYCHAIN TAB IS BELOW THE LOAD GUARD, and the placeholder it replaces was above it.
972
  // C4 serves the credential rows on the SAME payload as the overview, so a keychain tab that
 
981
  }
982
  if (load.phase === "error") {
983
  return (
984
+ <div className="conn-modal-error">
985
+ <p role="alert">{load.message}</p>
986
+ <button className="conn-modal-retry" type="button" onClick={() => reread()}>
987
+ Try again
988
+ </button>
989
+ </div>
990
  );
991
  }
992
  if (tab === "keychain") {
 
1051
  );
1052
  }
1053
  return (
1054
+ <>
1055
+ {rotationNotice ? (
1056
+ <RotationNotice
1057
+ notice={rotationNotice}
1058
+ onRotate={rotationEntry?.replaceable && load.detail.keychain.connect
1059
+ ? () => setTab("keychain") : undefined}
1060
+ />
1061
+ ) : null}
1062
  <ConnectorOverviewPanel
1063
  detail={load.detail}
1064
  onPullReviews={canPull ? () => setPulling(true) : undefined}
1065
  />
1066
+ </>
1067
  );
1068
+ }, [canPull, databaseReveal, load, onOpenDatabases, reread, rotationEntry, rotationNotice, row, tab]);
1069
 
1070
  const saveDatabaseChanges = useCallback(async () => {
1071
  if (!databasePendingCount || !databasesRef.current) return;
 
1091
  else setTab(destination.tab);
1092
  }, [discardDatabaseChanges, onClose, pendingLeave]);
1093
 
1094
+ const expired = rotationNotice?.tone === "expired";
1095
+ const status = expired ? "expired" : load.phase === "ready" ? load.detail.overview.status : row.state;
1096
  const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label;
1097
 
1098
  return (
 
1115
  card to read a state off, so until `/detail` lands there is nothing to say and an
1116
  empty pill would be a coloured hole in the header. */}
1117
  {status ? (
1118
+ <span
1119
+ className={"conn-modal-pill" + (status === "expired" ? " is-expired" : stateTone(status))}
1120
+ role={status === "expired" ? "alert" : undefined}
1121
+ >{status}</span>
1122
  ) : null}
1123
  {tab === "databases" ? (
1124
  <div className="conn-modal-save-actions">
web/src/connectors/DatabasesTab.tsx CHANGED
@@ -56,9 +56,10 @@
56
  // `ConnectorOverviewPanel` and `KeychainTab` are exported panels.
57
  // ---------------------------------------------------------------------------
58
 
59
- import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useState } from "react";
60
  import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
61
  import { ConfirmDialog } from "../ui/ConfirmDialog";
 
62
  import type { ConnectorDatabase, ConnectorDetail } from "./ConnectorModal";
63
  import type { ConnectorRow } from "./ConnectorsPage";
64
  import { watchMaterialization } from "./materializationJobs";
@@ -260,14 +261,16 @@ type PopulationCountAnswer =
260
  durationMs: number;
261
  modelsCounted: number;
262
  modelsWithRows: number;
 
 
263
  errors: string[];
264
  }
265
  | { ok: false; message: string };
266
 
267
- /** The explicit long-running door. Connector detail never starts this work. */
268
- async function countSourceRows(): Promise<PopulationCountAnswer> {
269
  try {
270
- const res = await fetch(`${API_V1}/connectors/odoo/census`, {
271
  method: "POST",
272
  credentials: CREDENTIALS,
273
  });
@@ -286,8 +289,20 @@ async function countSourceRows(): Promise<PopulationCountAnswer> {
286
  ? Math.max(0, Math.trunc(value))
287
  : 0;
288
  const rawErrors = payload?.errors;
 
 
 
 
 
 
 
 
 
 
289
  return {
290
  ok: true,
 
 
291
  complete: payload?.complete === true,
292
  capturedAt: typeof payload?.capturedAt === "string" ? payload.capturedAt : "",
293
  durationMs: number(payload?.durationMs),
@@ -333,6 +348,13 @@ function populationResult(
333
  (complete ? "" : " The count was incomplete because some source tables could not be read.");
334
  }
335
 
 
 
 
 
 
 
 
336
  /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */
337
  function Switch({
338
  on,
@@ -383,6 +405,7 @@ export function DatabasesUnavailable({ row, reason }: { row: ConnectorRow; reaso
383
  /** One database's disclosure: its fields, and what the catalogue left out. */
384
  function DatabasePanel({
385
  database,
 
386
  siblingLabels,
387
  fieldsVisible,
388
  canToggleFields,
@@ -392,6 +415,7 @@ function DatabasePanel({
392
  onField,
393
  }: {
394
  database: ConnectorDatabase;
 
395
  /** The OTHER databases reading the same Odoo model, by label. See the shared note below. */
396
  siblingLabels: string[];
397
  fieldsVisible: boolean;
@@ -412,10 +436,10 @@ function DatabasePanel({
412
  <p className="conn-db-note">The field list for this database is administrator only.</p>
413
  );
414
  }
415
- if (!catalogueComplete) {
416
  return (
417
  <p className="conn-db-note">
418
- No schema sync has finished, so this workspace holds no field list from Odoo yet.
419
  </p>
420
  );
421
  }
@@ -428,8 +452,8 @@ function DatabasePanel({
428
  database change. */}
429
  {siblingLabels.length ? (
430
  <p className="conn-db-shared">
431
- These fields come from the same Odoo source as {siblingLabels.join(", ")}, so switching
432
- one on or off changes it there too.
433
  </p>
434
  ) : null}
435
  {database.fields.length ? (
@@ -469,7 +493,7 @@ function DatabasePanel({
469
  </tbody>
470
  </table>
471
  ) : (
472
- <p className="conn-db-note">Odoo reported no fields for this database.</p>
473
  )}
474
  <div className="conn-db-excluded">
475
  <h4 className="conn-db-sub">Excluded</h4>
@@ -508,6 +532,15 @@ function DatabasePanel({
508
  * `routes_connectors.py::_enable_odoo_database`), so there is no waiting state left to describe.
509
  * A reader who may not rename gets no control at all, rather than a sentence about a wait.
510
  */
 
 
 
 
 
 
 
 
 
511
  function NameCell({
512
  database,
513
  editing,
@@ -528,25 +561,29 @@ function NameCell({
528
  /** An empty string CLEARS, which is what falling back to our default means. */
529
  onSave: (next: string) => void;
530
  }) {
 
 
 
 
 
 
 
 
 
 
531
  if (!editing) {
532
- // ⚠ `conn-db-head` IS THE ROW SHAPE THIS TAB ALREADY USES for a name beside its control, and
533
- // it is reused rather than re-declared: two adjacent inline controls with no rule between
534
- // them set flush against each other, which is the run-on this surface reads as one word.
535
  return (
536
- <div className="conn-db-head">
537
- {database.override ? (
538
- <span className="conn-db-name">{database.override}</span>
539
- ) : (
540
- <span className="conn-db-state">Inherits the default name</span>
541
- )}
542
  {database.canRename ? (
543
  <button
 
544
  type="button"
545
- className="conn-db-link"
546
  aria-label={`Rename the database ${database.label}`}
547
  onClick={onEdit}
548
  >
549
- {database.override ? "Change" : "Rename"}
550
  </button>
551
  ) : null}
552
  </div>
@@ -563,8 +600,16 @@ function NameCell({
563
  id={`conn-db-rename-${database.key}`}
564
  value={draft}
565
  disabled={busy}
 
566
  autoComplete="off"
567
  onChange={(event) => onDraft(event.target.value)}
 
 
 
 
 
 
 
568
  />
569
  </div>
570
  <div className="conn-db-head">
@@ -659,6 +704,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
659
  };
660
  const [censusBusy, setCensusBusy] = useState(false);
661
  const [censusResult, setCensusResult] = useState("");
 
662
  /** The one row being renamed, and the text in its box. Empty means nobody is renaming. */
663
  const [renaming, setRenaming] = useState("");
664
  const [draft, setDraft] = useState("");
@@ -698,6 +744,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
698
  .map(({ database }) => database),
699
  [databases, pending.tables]
700
  );
 
701
 
702
  const stageTable = useCallback(
703
  (database: ConnectorDatabase, next: boolean) => {
@@ -830,7 +877,8 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
830
  if (next) {
831
  const answer = await enableDatabase(databaseKey);
832
  if (!answer.ok) {
833
- failed.tables[databaseKey] = next;
 
834
  failures.push(`${label}: ${answer.message}`);
835
  continue;
836
  }
@@ -897,23 +945,32 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
897
  tableEnabled: (database) => pending.tables[database.key] ?? database.enabled,
898
  }), [discardPending, flipTable, pending.tables, savePending]);
899
 
900
- const runPopulationCount = useCallback(async () => {
901
  setCensusBusy(true);
902
  setCensusResult("");
 
903
  setError("");
904
- const answer = await countSourceRows();
905
  setCensusBusy(false);
906
  if (!answer.ok) {
907
  setError(answer.message);
908
  return;
909
  }
910
- setCensusResult(populationResult(
 
 
 
 
 
 
 
 
911
  answer.modelsCounted,
912
  answer.modelsWithRows,
913
  answer.durationMs,
914
  answer.capturedAt,
915
  answer.complete
916
- ));
917
  onChanged();
918
  }, [onChanged]);
919
 
@@ -938,8 +995,9 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
938
  <div className="conn-db-head">
939
  <div>
940
  <p className="conn-db-note" id="odoo-census-warning">
941
- Counting every source table takes about a minute and a half on a workspace this
942
- size. You can keep this tab open while it runs.
 
943
  </p>
944
  {censusResult ? (
945
  <p className="conn-db-note" role="status">{censusResult}</p>
@@ -964,6 +1022,15 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
964
  >
965
  {censusBusy ? "Counting rows..." : "Count rows"}
966
  </button>
 
 
 
 
 
 
 
 
 
967
  </div>
968
  ) : null}
969
  {error ? (
@@ -977,12 +1044,13 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
977
  connection. Enabled databases are first.
978
  </p>
979
  {/* ⛔ THE IDENTITY BLOCK IS EXPLAINED, NOT INFERRED FROM A GREYED CONTROL. Which of the
980
- three names is ours, which is theirs and which one a rename touches is the question this
981
  screen exists to answer, so it is answered in words above the table. */}
982
  <p className="conn-db-note">
983
- Source name is what {row.label} calls the table, so it cannot be changed here. Default
984
- name is ours. Your name replaces it everywhere in this workspace, including the
985
- navigation rail, and clearing it brings the default back.
 
986
  </p>
987
  {showsPopulation ? (
988
  <p className="conn-db-note">
@@ -995,7 +1063,6 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
995
  <tr>
996
  <th scope="col">Source name</th>
997
  <th scope="col">Default name</th>
998
- <th scope="col">Your name</th>
999
  <th scope="col">Fields</th>
1000
  {showsPopulation ? <th scope="col">Source rows</th> : null}
1001
  <th scope="col">Enabled</th>
@@ -1037,7 +1104,6 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
1037
  <td className="conn-db-src">
1038
  {database.native || <span className="conn-db-state">Not published</span>}
1039
  </td>
1040
- <td>{database.defaultLabel}</td>
1041
  <td>
1042
  <NameCell
1043
  database={renderedDatabase}
@@ -1092,8 +1158,12 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
1092
  <td className="conn-db-source-rows">
1093
  {database.sourceRows === 0 ? (
1094
  <span className="conn-db-state">Empty</span>
 
 
1095
  ) : typeof database.sourceRows === "number" ? (
1096
- database.sourceRows.toLocaleString("en-US")
 
 
1097
  ) : (
1098
  <span className="conn-db-state">Not counted yet</span>
1099
  )}
@@ -1119,9 +1189,9 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
1119
  )}
1120
  </td>
1121
  </tr>
1122
- {!effectiveEnabled && siblingLabels.length ? (
1123
  <tr>
1124
- <td colSpan={showsPopulation ? 6 : 5}>
1125
  <p className="conn-db-shared">
1126
  {renderedDatabase.label} shares its Odoo source table with {sentenceList(siblingLabels)},
1127
  so populated fields will be switched on there too.
@@ -1131,7 +1201,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
1131
  ) : null}
1132
  {autoEnableStatus && !job ? (
1133
  <tr>
1134
- <td colSpan={showsPopulation ? 6 : 5}>
1135
  <p className="conn-db-note" role="status" aria-live="polite">
1136
  {autoEnableStatus}
1137
  </p>
@@ -1143,7 +1213,7 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
1143
  // the cause and the subject, in the server's own sentence, and offers nothing to
1144
  // dismiss because the table simply stayed on.
1145
  <tr>
1146
- <td colSpan={showsPopulation ? 6 : 5}>
1147
  <p className="conn-db-refusal" role="alert">
1148
  {refusal}
1149
  </p>
@@ -1152,9 +1222,10 @@ const DatabasesTab = forwardRef<DatabasesTabHandle, {
1152
  ) : null}
1153
  {isOpen ? (
1154
  <tr>
1155
- <td colSpan={showsPopulation ? 6 : 5}>
1156
  <DatabasePanel
1157
  database={renderedDatabase}
 
1158
  siblingLabels={siblingLabels}
1159
  fieldsVisible={introspection.fieldsVisible}
1160
  canToggleFields={introspection.canToggleFields}
 
56
  // `ConnectorOverviewPanel` and `KeychainTab` are exported panels.
57
  // ---------------------------------------------------------------------------
58
 
59
+ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
60
  import { API_V1, CREDENTIALS, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
61
  import { ConfirmDialog } from "../ui/ConfirmDialog";
62
+ import { useEscapeClose } from "../ui/useEscapeClose";
63
  import type { ConnectorDatabase, ConnectorDetail } from "./ConnectorModal";
64
  import type { ConnectorRow } from "./ConnectorsPage";
65
  import { watchMaterialization } from "./materializationJobs";
 
261
  durationMs: number;
262
  modelsCounted: number;
263
  modelsWithRows: number;
264
+ mode: string;
265
+ exactCounts: Record<string, number>;
266
  errors: string[];
267
  }
268
  | { ok: false; message: string };
269
 
270
+ /** Both passes start on a click. Connector detail never starts this work. */
271
+ async function countSourceRows(exact = false): Promise<PopulationCountAnswer> {
272
  try {
273
+ const res = await fetch(`${API_V1}/connectors/odoo/census${exact ? "?exact=true" : ""}`, {
274
  method: "POST",
275
  credentials: CREDENTIALS,
276
  });
 
289
  ? Math.max(0, Math.trunc(value))
290
  : 0;
291
  const rawErrors = payload?.errors;
292
+ const mode = typeof payload?.mode === "string" ? payload.mode : "unknown";
293
+ const exactCounts: Record<string, number> = {};
294
+ if ((mode === "exact" || mode === "exact_fallback") && payload?.counts &&
295
+ typeof payload.counts === "object" && !Array.isArray(payload.counts)) {
296
+ for (const [model, value] of Object.entries(payload.counts)) {
297
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
298
+ exactCounts[model] = value;
299
+ }
300
+ }
301
+ }
302
  return {
303
  ok: true,
304
+ mode,
305
+ exactCounts,
306
  complete: payload?.complete === true,
307
  capturedAt: typeof payload?.capturedAt === "string" ? payload.capturedAt : "",
308
  durationMs: number(payload?.durationMs),
 
348
  (complete ? "" : " The count was incomplete because some source tables could not be read.");
349
  }
350
 
351
+ function sourceRowsTitle(exactCount: number | undefined): string {
352
+ const explanation = "The display threshold is 100 for speed and does not limit data pulled from the source";
353
+ return typeof exactCount === "number"
354
+ ? `Exact total: ${exactCount.toLocaleString("en-US")} rows. ${explanation}.`
355
+ : `${explanation}; use Exact totals beside Count rows for the full total.`;
356
+ }
357
+
358
  /** The on/off control, one shape for both rails (DESIGN.md section 4: one control shape). */
359
  function Switch({
360
  on,
 
405
  /** One database's disclosure: its fields, and what the catalogue left out. */
406
  function DatabasePanel({
407
  database,
408
+ sourceLabel,
409
  siblingLabels,
410
  fieldsVisible,
411
  canToggleFields,
 
415
  onField,
416
  }: {
417
  database: ConnectorDatabase;
418
+ sourceLabel: string;
419
  /** The OTHER databases reading the same Odoo model, by label. See the shared note below. */
420
  siblingLabels: string[];
421
  fieldsVisible: boolean;
 
436
  <p className="conn-db-note">The field list for this database is administrator only.</p>
437
  );
438
  }
439
+ if (!catalogueComplete && !database.fields.length) {
440
  return (
441
  <p className="conn-db-note">
442
+ No field list is available for this database yet.
443
  </p>
444
  );
445
  }
 
452
  database change. */}
453
  {siblingLabels.length ? (
454
  <p className="conn-db-shared">
455
+ These fields come from the same {sourceLabel} source as {siblingLabels.join(", ")}
456
+ {canToggleFields ? ", so switching one on or off changes it there too." : "."}
457
  </p>
458
  ) : null}
459
  {database.fields.length ? (
 
493
  </tbody>
494
  </table>
495
  ) : (
496
+ <p className="conn-db-note">{sourceLabel} reported no fields for this database.</p>
497
  )}
498
  <div className="conn-db-excluded">
499
  <h4 className="conn-db-sub">Excluded</h4>
 
532
  * `routes_connectors.py::_enable_odoo_database`), so there is no waiting state left to describe.
533
  * A reader who may not rename gets no control at all, rather than a sentence about a wait.
534
  */
535
+ function PenIcon() {
536
+ return (
537
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false">
538
+ <path d="m3.2 11.9.7-2.8 6.5-6.5 2.5 2.5-6.5 6.5-2.7.8Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" />
539
+ <path d="m9.1 4 2.5 2.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" />
540
+ </svg>
541
+ );
542
+ }
543
+
544
  function NameCell({
545
  database,
546
  editing,
 
561
  /** An empty string CLEARS, which is what falling back to our default means. */
562
  onSave: (next: string) => void;
563
  }) {
564
+ const penRef = useRef<HTMLButtonElement>(null);
565
+ const wasEditing = useRef(editing);
566
+ useEffect(() => {
567
+ if (wasEditing.current && !editing) penRef.current?.focus();
568
+ wasEditing.current = editing;
569
+ }, [editing]);
570
+ // Escape is claimed through useEscapeClose: the arbiter listens at document capture,
571
+ // so a local handler cannot see the key. Enter stays local because nothing arbitrates it.
572
+ useEscapeClose(editing, onCancel);
573
+
574
  if (!editing) {
 
 
 
575
  return (
576
+ <div className="conn-db-name-line">
577
+ <span className="conn-db-name">{database.override || database.defaultLabel}</span>
 
 
 
 
578
  {database.canRename ? (
579
  <button
580
+ ref={penRef}
581
  type="button"
582
+ className="conn-db-pen"
583
  aria-label={`Rename the database ${database.label}`}
584
  onClick={onEdit}
585
  >
586
+ <PenIcon />
587
  </button>
588
  ) : null}
589
  </div>
 
600
  id={`conn-db-rename-${database.key}`}
601
  value={draft}
602
  disabled={busy}
603
+ autoFocus
604
  autoComplete="off"
605
  onChange={(event) => onDraft(event.target.value)}
606
+ onKeyDown={(event) => {
607
+ if (event.key === "Enter") {
608
+ event.preventDefault();
609
+ event.stopPropagation();
610
+ if (!(busy || !draft.trim())) onSave(draft);
611
+ }
612
+ }}
613
  />
614
  </div>
615
  <div className="conn-db-head">
 
704
  };
705
  const [censusBusy, setCensusBusy] = useState(false);
706
  const [censusResult, setCensusResult] = useState("");
707
+ const [exactCounts, setExactCounts] = useState<Record<string, number>>({});
708
  /** The one row being renamed, and the text in its box. Empty means nobody is renaming. */
709
  const [renaming, setRenaming] = useState("");
710
  const [draft, setDraft] = useState("");
 
744
  .map(({ database }) => database),
745
  [databases, pending.tables]
746
  );
747
+ const hasRenamableDatabase = orderedDatabases.some((database) => database.canRename);
748
 
749
  const stageTable = useCallback(
750
  (database: ConnectorDatabase, next: boolean) => {
 
877
  if (next) {
878
  const answer = await enableDatabase(databaseKey);
879
  if (!answer.ok) {
880
+ // Unlike disables and renames, a refused enable needs something else to change.
881
+ // Drop its pending state so the toggle shows the server state instead of a fake retry.
882
  failures.push(`${label}: ${answer.message}`);
883
  continue;
884
  }
 
945
  tableEnabled: (database) => pending.tables[database.key] ?? database.enabled,
946
  }), [discardPending, flipTable, pending.tables, savePending]);
947
 
948
+ const runPopulationCount = useCallback(async (exact = false) => {
949
  setCensusBusy(true);
950
  setCensusResult("");
951
+ setExactCounts({});
952
  setError("");
953
+ const answer = await countSourceRows(exact);
954
  setCensusBusy(false);
955
  if (!answer.ok) {
956
  setError(answer.message);
957
  return;
958
  }
959
+ setExactCounts(answer.exactCounts);
960
+ const pass = answer.mode === "bounded" ? "Counted up to 101 rows per source table. "
961
+ : answer.mode === "exact" ? "Counted exact totals. "
962
+ : answer.mode === "exact_fallback"
963
+ ? "Counted exact totals because this connection does not support bounded counts. "
964
+ : "";
965
+ const exactHint = Object.keys(answer.exactCounts).length
966
+ ? " Exact totals are available in each Source rows tooltip." : "";
967
+ setCensusResult(pass + populationResult(
968
  answer.modelsCounted,
969
  answer.modelsWithRows,
970
  answer.durationMs,
971
  answer.capturedAt,
972
  answer.complete
973
+ ) + exactHint);
974
  onChanged();
975
  }, [onChanged]);
976
 
 
995
  <div className="conn-db-head">
996
  <div>
997
  <p className="conn-db-note" id="odoo-census-warning">
998
+ Count rows stops at 101 rows per source table and displays 100+ from 100 onward.
999
+ Each table still needs a request, so this can take about a minute or longer.
1000
+ Counting exact totals takes considerably longer than the default pass.
1001
  </p>
1002
  {censusResult ? (
1003
  <p className="conn-db-note" role="status">{censusResult}</p>
 
1022
  >
1023
  {censusBusy ? "Counting rows..." : "Count rows"}
1024
  </button>
1025
+ <button
1026
+ type="button"
1027
+ className="conn-db-link"
1028
+ aria-describedby="odoo-census-warning"
1029
+ disabled={censusBusy}
1030
+ onClick={() => void runPopulationCount(true)}
1031
+ >
1032
+ Exact totals
1033
+ </button>
1034
  </div>
1035
  ) : null}
1036
  {error ? (
 
1044
  connection. Enabled databases are first.
1045
  </p>
1046
  {/* ⛔ THE IDENTITY BLOCK IS EXPLAINED, NOT INFERRED FROM A GREYED CONTROL. Which of the
1047
+ two names is ours, which is theirs and which one the pen edits is the question this
1048
  screen exists to answer, so it is answered in words above the table. */}
1049
  <p className="conn-db-note">
1050
+ Source name belongs to {row.label} and cannot be changed here. Default name is ours
1051
+ {hasRenamableDatabase
1052
+ ? "; the pen changes the workspace name, including in the navigation rail."
1053
+ : "."}
1054
  </p>
1055
  {showsPopulation ? (
1056
  <p className="conn-db-note">
 
1063
  <tr>
1064
  <th scope="col">Source name</th>
1065
  <th scope="col">Default name</th>
 
1066
  <th scope="col">Fields</th>
1067
  {showsPopulation ? <th scope="col">Source rows</th> : null}
1068
  <th scope="col">Enabled</th>
 
1104
  <td className="conn-db-src">
1105
  {database.native || <span className="conn-db-state">Not published</span>}
1106
  </td>
 
1107
  <td>
1108
  <NameCell
1109
  database={renderedDatabase}
 
1158
  <td className="conn-db-source-rows">
1159
  {database.sourceRows === 0 ? (
1160
  <span className="conn-db-state">Empty</span>
1161
+ ) : typeof database.sourceRows === "number" && database.sourceRows >= 100 ? (
1162
+ <span title={sourceRowsTitle(exactCounts[database.native])}>100+</span>
1163
  ) : typeof database.sourceRows === "number" ? (
1164
+ <span title={sourceRowsTitle(exactCounts[database.native])}>
1165
+ {database.sourceRows.toLocaleString("en-US")}
1166
+ </span>
1167
  ) : (
1168
  <span className="conn-db-state">Not counted yet</span>
1169
  )}
 
1189
  )}
1190
  </td>
1191
  </tr>
1192
+ {!effectiveEnabled && introspection.canToggleFields && siblingLabels.length ? (
1193
  <tr>
1194
+ <td colSpan={showsPopulation ? 5 : 4}>
1195
  <p className="conn-db-shared">
1196
  {renderedDatabase.label} shares its Odoo source table with {sentenceList(siblingLabels)},
1197
  so populated fields will be switched on there too.
 
1201
  ) : null}
1202
  {autoEnableStatus && !job ? (
1203
  <tr>
1204
+ <td colSpan={showsPopulation ? 5 : 4}>
1205
  <p className="conn-db-note" role="status" aria-live="polite">
1206
  {autoEnableStatus}
1207
  </p>
 
1213
  // the cause and the subject, in the server's own sentence, and offers nothing to
1214
  // dismiss because the table simply stayed on.
1215
  <tr>
1216
+ <td colSpan={showsPopulation ? 5 : 4}>
1217
  <p className="conn-db-refusal" role="alert">
1218
  {refusal}
1219
  </p>
 
1222
  ) : null}
1223
  {isOpen ? (
1224
  <tr>
1225
+ <td colSpan={showsPopulation ? 5 : 4}>
1226
  <DatabasePanel
1227
  database={renderedDatabase}
1228
+ sourceLabel={row.label}
1229
  siblingLabels={siblingLabels}
1230
  fieldsVisible={introspection.fieldsVisible}
1231
  canToggleFields={introspection.canToggleFields}
web/src/connectors/KeychainTab.tsx CHANGED
@@ -34,7 +34,7 @@
34
  // per-user secret slots — so it goes through `POST /oauth/{slug}/disconnect`.
35
  // ---------------------------------------------------------------------------
36
 
37
- import { useCallback, useState } from "react";
38
  import { API_V1, CREDENTIALS } from "../apiContract";
39
  import type {
40
  ConnectorConnectSpec,
@@ -43,6 +43,95 @@ import type {
43
  } from "./ConnectorModal";
44
  import type { ConnectorRow } from "./ConnectorsPage";
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  /**
47
  * ⭐ WAVE 32 · R4 / contract C1 — WHO A CONNECTION IS FOR, in the two words the server declares.
48
  *
@@ -67,7 +156,7 @@ export function hasOwnDisconnect(row: ConnectorRow): boolean {
67
  return row.key === "odoo" || row.kind === "oauth";
68
  }
69
 
70
- async function post(path: string, body?: unknown): Promise<string> {
71
  try {
72
  const res = await fetch(`${API_V1}${path}`, {
73
  method: "POST",
@@ -75,14 +164,33 @@ async function post(path: string, body?: unknown): Promise<string> {
75
  headers: { "Content-Type": "application/json" },
76
  body: JSON.stringify(body ?? {}),
77
  });
78
- const payload = (await res.json().catch(() => null)) as { error?: { message?: string } } | null;
79
- if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
80
- return "";
 
 
 
 
81
  } catch {
82
- return "Cannot reach the server.";
83
  }
84
  }
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  async function del(path: string): Promise<string> {
87
  try {
88
  const res = await fetch(`${API_V1}${path}`, { method: "DELETE", credentials: CREDENTIALS });
@@ -115,7 +223,11 @@ function ConnectForm({
115
  onCancel: () => void;
116
  }) {
117
  const [entryLabel, setEntryLabel] = useState(label);
118
- const [values, setValues] = useState<Record<string, string>>({});
 
 
 
 
119
  const [scope, setScope] = useState(spec.scopes[0] || "business");
120
  const [busy, setBusy] = useState(false);
121
  const [error, setError] = useState("");
@@ -124,33 +236,50 @@ function ConnectForm({
124
  if (busy) return;
125
  setBusy(true);
126
  setError("");
127
- const fields: Record<string, string> = {};
128
- for (const field of spec.fields) {
129
- const value = (values[field.key] || "").trim();
130
- if (value) fields[field.key] = value;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  }
132
- const message = await post("/admin/keychain", {
133
- label: entryLabel.trim(),
134
- type: spec.type,
135
- scope,
136
- fields,
137
- });
138
  if (message) {
139
  setError(message);
140
  setBusy(false);
141
  return;
142
  }
143
- // The form is dropped rather than cleared: a secret that has been stored must not sit in a
144
- // React state object waiting for the next render.
145
  onDone();
146
  };
147
 
148
  return (
149
  <div className="conn-kc-form">
 
150
  <div className="conn-kc-field">
151
  <label htmlFor="conn-kc-label">Name this connection</label>
152
  <input
153
  id="conn-kc-label"
 
154
  value={entryLabel}
155
  maxLength={80}
156
  onChange={(event) => setEntryLabel(event.target.value)}
@@ -161,6 +290,7 @@ function ConnectForm({
161
  {spec.scopes.length > 1 ? (
162
  <select
163
  id="conn-kc-scope"
 
164
  value={scope}
165
  onChange={(event) => setScope(event.target.value)}
166
  >
@@ -187,6 +317,7 @@ function ConnectForm({
187
  <label htmlFor={`conn-kc-${field.key}`}>{field.label}</label>
188
  <input
189
  id={`conn-kc-${field.key}`}
 
190
  type={field.secret ? "password" : "text"}
191
  autoComplete={field.secret ? "new-password" : "off"}
192
  value={values[field.key] ?? ""}
@@ -196,22 +327,31 @@ function ConnectForm({
196
  />
197
  </div>
198
  ))}
 
 
 
 
 
 
 
 
 
199
  {error ? (
200
  <p className="conn-kc-error" role="alert">
201
  {error}
202
  </p>
203
  ) : null}
204
  <div className="conn-kc-actions">
205
- <button type="button" className="conn-kc-btn" onClick={onCancel}>
206
- Cancel
207
  </button>
208
  <button
209
  type="button"
210
  className="conn-kc-btn is-primary"
211
- disabled={busy || !entryLabel.trim()}
212
  onClick={() => void save()}
213
  >
214
- {busy ? "Storing" : "Store the key"}
215
  </button>
216
  </div>
217
  </div>
@@ -238,6 +378,8 @@ function ReplaceForm({
238
  onCancel: () => void;
239
  }) {
240
  const [values, setValues] = useState<Record<string, string>>({});
 
 
241
  const [busy, setBusy] = useState(false);
242
  const [error, setError] = useState("");
243
  const fields = spec.fields.filter((field) => field.secret);
@@ -245,16 +387,30 @@ function ReplaceForm({
245
  fields.length > 0 && fields.every((field) => Boolean((values[field.key] || "").trim()));
246
 
247
  const save = async () => {
248
- if (busy || !complete) return;
249
  setBusy(true);
250
  setError("");
251
- const replacement = Object.fromEntries(
252
- fields.map((field) => [field.key, (values[field.key] || "").trim()])
253
- );
254
- const message = await post(
255
- `/connectors/${encodeURIComponent(connectorKey)}/keychain/${encodeURIComponent(entry.id)}/replace`,
256
- { fields: replacement }
257
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  if (message) {
259
  setError(message);
260
  setBusy(false);
@@ -267,10 +423,18 @@ function ReplaceForm({
267
 
268
  return (
269
  <div className="conn-kc-form conn-kc-replace">
270
- <h3>Replace key</h3>
 
271
  <p className="conn-kc-note">
272
  The current key stays unchanged until the complete replacement is stored.
273
  </p>
 
 
 
 
 
 
 
274
  {fields.map((field) => (
275
  <div className="conn-kc-field" key={field.key}>
276
  <label htmlFor={`conn-kc-replace-${entry.id}-${field.key}`}>
@@ -288,6 +452,16 @@ function ReplaceForm({
288
  />
289
  </div>
290
  ))}
 
 
 
 
 
 
 
 
 
 
291
  <div className="conn-kc-message-slot">
292
  {error ? (
293
  <p className="conn-kc-error" role="alert">
@@ -297,15 +471,15 @@ function ReplaceForm({
297
  </div>
298
  <div className="conn-kc-actions">
299
  <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>
300
- Cancel
301
  </button>
302
  <button
303
  type="button"
304
  className="conn-kc-btn is-primary"
305
- disabled={busy || !complete}
306
  onClick={() => void save()}
307
  >
308
- {busy ? "Replacing" : "Store replacement"}
309
  </button>
310
  </div>
311
  </div>
@@ -333,6 +507,7 @@ export default function KeychainTab({
333
  const [error, setError] = useState("");
334
  const [adding, setAdding] = useState(false);
335
  const [replacing, setReplacing] = useState<ConnectorKeychainEntry | null>(null);
 
336
 
337
  const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
338
  setTested((current) => ({ ...current, [entry.id]: "Testing" }));
@@ -351,7 +526,8 @@ export default function KeychainTab({
351
  } catch {
352
  setTested((current) => ({ ...current, [entry.id]: "Cannot reach the server." }));
353
  }
354
- }, []);
 
355
 
356
  const remove = useCallback(
357
  async (entry: ConnectorKeychainEntry) => {
@@ -385,9 +561,9 @@ export default function KeychainTab({
385
  setError("");
386
  let message = "";
387
  if (row.key === "odoo") {
388
- message = await post("/admin/connectors/odoo/disconnect");
389
  } else if (row.kind === "oauth") {
390
- message = await post(`/oauth/${encodeURIComponent(row.key)}/disconnect`);
391
  } else {
392
  for (const entry of keychain.entries) {
393
  message = await del(`/admin/keychain/${encodeURIComponent(entry.id)}`);
@@ -406,7 +582,10 @@ export default function KeychainTab({
406
  <ConnectForm
407
  spec={keychain.connect}
408
  label={row.label}
409
- onCancel={() => setAdding(false)}
 
 
 
410
  onDone={() => {
411
  setAdding(false);
412
  onChanged();
@@ -421,7 +600,10 @@ export default function KeychainTab({
421
  connectorKey={row.key}
422
  spec={keychain.connect}
423
  entry={replacing}
424
- onCancel={() => setReplacing(null)}
 
 
 
425
  onDone={() => {
426
  setReplacing(null);
427
  onChanged();
@@ -439,7 +621,10 @@ export default function KeychainTab({
439
  ) : null}
440
  {keychain.entries.length ? (
441
  <ul className="conn-kc-list">
442
- {keychain.entries.map((entry) => (
 
 
 
443
  <li className="conn-kc-row" key={entry.id}>
444
  <div className="conn-kc-main">
445
  <span className="conn-kc-label">{entry.label}</span>
@@ -451,21 +636,29 @@ export default function KeychainTab({
451
  {" · "}
452
  {scopeLabel(entry.scope)}
453
  </span>
454
- {tested[entry.id] ? (
 
 
 
 
 
 
 
 
455
  <span className="conn-kc-test" role="status">
456
  {tested[entry.id]}
457
  </span>
458
  ) : null}
459
  </div>
460
  <div className="conn-kc-controls">
461
- {entry.replaceable && keychain.connect ? (
462
  <button
463
  type="button"
464
  className="conn-kc-btn"
465
  disabled={Boolean(busyId)}
466
  onClick={() => setReplacing(entry)}
467
  >
468
- Replace
469
  </button>
470
  ) : null}
471
  {entry.testable ? (
@@ -491,7 +684,8 @@ export default function KeychainTab({
491
  )}
492
  </div>
493
  </li>
494
- ))}
 
495
  </ul>
496
  ) : (
497
  // One line, plus the action that fills it. Never a paragraph (DESIGN.md).
@@ -506,7 +700,11 @@ export default function KeychainTab({
506
  <button
507
  type="button"
508
  className="conn-kc-btn is-primary"
509
- onClick={() => setAdding(true)}
 
 
 
 
510
  >
511
  {keychain.entries.length ? "Add another key" : "Connect"}
512
  </button>
 
34
  // per-user secret slots — so it goes through `POST /oauth/{slug}/disconnect`.
35
  // ---------------------------------------------------------------------------
36
 
37
+ import { useCallback, useEffect, useState } from "react";
38
  import { API_V1, CREDENTIALS } from "../apiContract";
39
  import type {
40
  ConnectorConnectSpec,
 
43
  } from "./ConnectorModal";
44
  import type { ConnectorRow } from "./ConnectorsPage";
45
 
46
+ const AMAZON_ROTATION_DEADLINE_FIELD = "client_secret_rotation_deadline";
47
+ const DAY_MS = 24 * 60 * 60 * 1000;
48
+
49
+ export function amazonRotationNotice(deadline: string | undefined, now: number) {
50
+ if (!deadline) return null;
51
+ const remaining = Date.parse(deadline) - now;
52
+ if (!Number.isFinite(remaining) || remaining > 30 * DAY_MS) return null;
53
+ if (remaining <= 0) return { tone: "expired", message: "Client secret expired." };
54
+ const days = Math.ceil(remaining / DAY_MS);
55
+ const time = days === 1 ? "within a day" : `in ${days} days`;
56
+ return remaining <= 7 * DAY_MS
57
+ ? { tone: "urgent", message: `Secret expires ${time}.` }
58
+ : { tone: "attention", message: `Client secret expires ${time}.` };
59
+ }
60
+
61
+ export function RotationNotice({ notice, onRotate, disabled = false }: {
62
+ notice: NonNullable<ReturnType<typeof amazonRotationNotice>>;
63
+ onRotate?: () => void;
64
+ disabled?: boolean;
65
+ }) {
66
+ return (
67
+ <div
68
+ className={`conn-kc-rotation is-${notice.tone}`}
69
+ role={notice.tone === "expired" ? "alert" : "status"}
70
+ >
71
+ <span>{notice.message}</span>
72
+ {onRotate ? (
73
+ <button
74
+ type="button"
75
+ className="conn-kc-rotation-action"
76
+ disabled={disabled}
77
+ onClick={onRotate}
78
+ >
79
+ {notice.tone === "attention" ? "Rotate secret" : "Rotate now"}
80
+ </button>
81
+ ) : null}
82
+ </div>
83
+ );
84
+ }
85
+
86
+ /** Recalculate even when the tab stays open across a deadline or resumes from sleep. */
87
+ export function useRotationClock() {
88
+ const [now, setNow] = useState(Date.now);
89
+ useEffect(() => {
90
+ const refresh = () => setNow(Date.now());
91
+ const timer = window.setInterval(refresh, 60_000);
92
+ window.addEventListener("focus", refresh);
93
+ document.addEventListener("visibilitychange", refresh);
94
+ return () => {
95
+ window.clearInterval(timer);
96
+ window.removeEventListener("focus", refresh);
97
+ document.removeEventListener("visibilitychange", refresh);
98
+ };
99
+ }, []);
100
+ return now;
101
+ }
102
+
103
+ function RotationDeadlineField({
104
+ id, value, onChange, disabled, replacement = false,
105
+ }: {
106
+ id: string;
107
+ value: string;
108
+ onChange: (value: string) => void;
109
+ disabled: boolean;
110
+ replacement?: boolean;
111
+ }) {
112
+ return (
113
+ <div className="conn-kc-field">
114
+ <label htmlFor={id}>
115
+ {replacement ? "New client secret expiry (optional)" : "Client secret expiry (optional)"}
116
+ </label>
117
+ <input
118
+ id={id}
119
+ name={AMAZON_ROTATION_DEADLINE_FIELD}
120
+ type="text"
121
+ autoComplete="off"
122
+ placeholder="Amazon timestamp with timezone"
123
+ aria-describedby={`${id}-help`}
124
+ disabled={disabled}
125
+ value={value}
126
+ onChange={(event) => onChange(event.target.value)}
127
+ />
128
+ <p id={`${id}-help`} className="conn-kc-note">
129
+ Amazon issues this with the client secret. Include its timezone; blank means no expiry warnings.
130
+ </p>
131
+ </div>
132
+ );
133
+ }
134
+
135
  /**
136
  * ⭐ WAVE 32 · R4 / contract C1 — WHO A CONNECTION IS FOR, in the two words the server declares.
137
  *
 
156
  return row.key === "odoo" || row.kind === "oauth";
157
  }
158
 
159
+ async function post(path: string, body?: unknown): Promise<{ message: string; entryId: string }> {
160
  try {
161
  const res = await fetch(`${API_V1}${path}`, {
162
  method: "POST",
 
164
  headers: { "Content-Type": "application/json" },
165
  body: JSON.stringify(body ?? {}),
166
  });
167
+ const payload = (await res.json().catch(() => null)) as
168
+ | { entry?: { id?: string }; error?: { message?: string } }
169
+ | null;
170
+ if (!res.ok) {
171
+ return { message: payload?.error?.message || `The server answered ${res.status}.`, entryId: "" };
172
+ }
173
+ return { message: "", entryId: typeof payload?.entry?.id === "string" ? payload.entry.id : "" };
174
  } catch {
175
+ return { message: "Cannot reach the server.", entryId: "" };
176
  }
177
  }
178
 
179
+ async function testAmazonEntry(entryId: string): Promise<string> {
180
+ if (!entryId) return "The stored key could not be identified. Close and reload this connection.";
181
+ try {
182
+ const res = await fetch(`${API_V1}/admin/keychain/${encodeURIComponent(entryId)}/test`, {
183
+ method: "POST",
184
+ credentials: CREDENTIALS,
185
+ });
186
+ const body = (await res.json().catch(() => null)) as { ok?: boolean } | null;
187
+ if (res.ok && body?.ok === true) return "";
188
+ } catch {
189
+ // Storage already succeeded. Retrying must test the same entry, never create another one.
190
+ }
191
+ return "The key is stored, but Amazon access is unconfirmed. Test again or close and use Replace.";
192
+ }
193
+
194
  async function del(path: string): Promise<string> {
195
  try {
196
  const res = await fetch(`${API_V1}${path}`, { method: "DELETE", credentials: CREDENTIALS });
 
223
  onCancel: () => void;
224
  }) {
225
  const [entryLabel, setEntryLabel] = useState(label);
226
+ const [values, setValues] = useState<Record<string, string>>(() =>
227
+ Object.fromEntries(spec.fields.map((field) => [field.key, field.default ?? ""]))
228
+ );
229
+ const [storedId, setStoredId] = useState<string | null>(null);
230
+ const [rotationDeadline, setRotationDeadline] = useState("");
231
  const [scope, setScope] = useState(spec.scopes[0] || "business");
232
  const [busy, setBusy] = useState(false);
233
  const [error, setError] = useState("");
 
236
  if (busy) return;
237
  setBusy(true);
238
  setError("");
239
+ let entryId = storedId;
240
+ if (entryId === null) {
241
+ const fields: Record<string, string> = {};
242
+ for (const field of spec.fields) {
243
+ const value = (values[field.key] || "").trim();
244
+ if (value) fields[field.key] = value;
245
+ }
246
+ if (spec.type === "amazon_sp") {
247
+ fields[AMAZON_ROTATION_DEADLINE_FIELD] = rotationDeadline.trim();
248
+ }
249
+ const result = await post("/admin/keychain", {
250
+ label: entryLabel.trim(),
251
+ type: spec.type,
252
+ scope,
253
+ fields,
254
+ });
255
+ if (result.message) {
256
+ setError(result.message);
257
+ setBusy(false);
258
+ return;
259
+ }
260
+ entryId = result.entryId;
261
+ setStoredId(entryId);
262
+ setValues({});
263
+ setRotationDeadline("");
264
  }
265
+ const message = spec.type === "amazon_sp" ? await testAmazonEntry(entryId) : "";
 
 
 
 
 
266
  if (message) {
267
  setError(message);
268
  setBusy(false);
269
  return;
270
  }
271
+ // Values were cleared at storage; close only after the required connection test answers.
 
272
  onDone();
273
  };
274
 
275
  return (
276
  <div className="conn-kc-form">
277
+ {storedId === null ? <>
278
  <div className="conn-kc-field">
279
  <label htmlFor="conn-kc-label">Name this connection</label>
280
  <input
281
  id="conn-kc-label"
282
+ disabled={busy}
283
  value={entryLabel}
284
  maxLength={80}
285
  onChange={(event) => setEntryLabel(event.target.value)}
 
290
  {spec.scopes.length > 1 ? (
291
  <select
292
  id="conn-kc-scope"
293
+ disabled={busy}
294
  value={scope}
295
  onChange={(event) => setScope(event.target.value)}
296
  >
 
317
  <label htmlFor={`conn-kc-${field.key}`}>{field.label}</label>
318
  <input
319
  id={`conn-kc-${field.key}`}
320
+ disabled={busy}
321
  type={field.secret ? "password" : "text"}
322
  autoComplete={field.secret ? "new-password" : "off"}
323
  value={values[field.key] ?? ""}
 
327
  />
328
  </div>
329
  ))}
330
+ {spec.type === "amazon_sp" ? (
331
+ <RotationDeadlineField
332
+ id="conn-kc-rotation-deadline"
333
+ value={rotationDeadline}
334
+ onChange={setRotationDeadline}
335
+ disabled={busy}
336
+ />
337
+ ) : null}
338
+ </> : null}
339
  {error ? (
340
  <p className="conn-kc-error" role="alert">
341
  {error}
342
  </p>
343
  ) : null}
344
  <div className="conn-kc-actions">
345
+ <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>
346
+ {storedId !== null ? "Close" : "Cancel"}
347
  </button>
348
  <button
349
  type="button"
350
  className="conn-kc-btn is-primary"
351
+ disabled={busy || (storedId === null ? !entryLabel.trim() : !storedId)}
352
  onClick={() => void save()}
353
  >
354
+ {busy ? (storedId !== null ? "Testing" : "Storing") : storedId !== null ? "Test again" : "Store the key"}
355
  </button>
356
  </div>
357
  </div>
 
378
  onCancel: () => void;
379
  }) {
380
  const [values, setValues] = useState<Record<string, string>>({});
381
+ const [rotationDeadline, setRotationDeadline] = useState("");
382
+ const [stored, setStored] = useState(false);
383
  const [busy, setBusy] = useState(false);
384
  const [error, setError] = useState("");
385
  const fields = spec.fields.filter((field) => field.secret);
 
387
  fields.length > 0 && fields.every((field) => Boolean((values[field.key] || "").trim()));
388
 
389
  const save = async () => {
390
+ if (busy || (!stored && !complete)) return;
391
  setBusy(true);
392
  setError("");
393
+ if (!stored) {
394
+ const replacement = Object.fromEntries(
395
+ fields.map((field) => [field.key, (values[field.key] || "").trim()])
396
+ );
397
+ if (spec.type === "amazon_sp") {
398
+ replacement[AMAZON_ROTATION_DEADLINE_FIELD] = rotationDeadline.trim();
399
+ }
400
+ const result = await post(
401
+ `/connectors/${encodeURIComponent(connectorKey)}/keychain/${encodeURIComponent(entry.id)}/replace`,
402
+ { fields: replacement }
403
+ );
404
+ if (result.message) {
405
+ setError(result.message);
406
+ setBusy(false);
407
+ return;
408
+ }
409
+ setStored(true);
410
+ setValues({});
411
+ setRotationDeadline("");
412
+ }
413
+ const message = spec.type === "amazon_sp" ? await testAmazonEntry(entry.id) : "";
414
  if (message) {
415
  setError(message);
416
  setBusy(false);
 
423
 
424
  return (
425
  <div className="conn-kc-form conn-kc-replace">
426
+ <h3>{stored ? "Test connection" : spec.type === "amazon_sp" ? "Rotate secret" : "Replace key"}</h3>
427
+ {!stored ? <>
428
  <p className="conn-kc-note">
429
  The current key stays unchanged until the complete replacement is stored.
430
  </p>
431
+ {fields.length > 1 ? (
432
+ <p className="conn-kc-note">
433
+ {spec.type === "amazon_sp"
434
+ ? "Re-enter both the client secret and refresh token together. The connection stays in place."
435
+ : "To rotate one secret, re-enter all secrets together."}
436
+ </p>
437
+ ) : null}
438
  {fields.map((field) => (
439
  <div className="conn-kc-field" key={field.key}>
440
  <label htmlFor={`conn-kc-replace-${entry.id}-${field.key}`}>
 
452
  />
453
  </div>
454
  ))}
455
+ {spec.type === "amazon_sp" ? (
456
+ <RotationDeadlineField
457
+ id={`conn-kc-replace-${entry.id}-rotation-deadline`}
458
+ value={rotationDeadline}
459
+ onChange={setRotationDeadline}
460
+ disabled={busy}
461
+ replacement
462
+ />
463
+ ) : null}
464
+ </> : null}
465
  <div className="conn-kc-message-slot">
466
  {error ? (
467
  <p className="conn-kc-error" role="alert">
 
471
  </div>
472
  <div className="conn-kc-actions">
473
  <button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>
474
+ {stored ? "Close" : "Cancel"}
475
  </button>
476
  <button
477
  type="button"
478
  className="conn-kc-btn is-primary"
479
+ disabled={busy || (!stored && !complete)}
480
  onClick={() => void save()}
481
  >
482
+ {busy ? (stored ? "Testing" : "Replacing") : stored ? "Test again" : "Store replacement"}
483
  </button>
484
  </div>
485
  </div>
 
507
  const [error, setError] = useState("");
508
  const [adding, setAdding] = useState(false);
509
  const [replacing, setReplacing] = useState<ConnectorKeychainEntry | null>(null);
510
+ const now = useRotationClock();
511
 
512
  const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
513
  setTested((current) => ({ ...current, [entry.id]: "Testing" }));
 
526
  } catch {
527
  setTested((current) => ({ ...current, [entry.id]: "Cannot reach the server." }));
528
  }
529
+ if (row.key === "amazon_sp") onChanged();
530
+ }, [onChanged, row.key]);
531
 
532
  const remove = useCallback(
533
  async (entry: ConnectorKeychainEntry) => {
 
561
  setError("");
562
  let message = "";
563
  if (row.key === "odoo") {
564
+ message = (await post("/admin/connectors/odoo/disconnect")).message;
565
  } else if (row.kind === "oauth") {
566
+ message = (await post(`/oauth/${encodeURIComponent(row.key)}/disconnect`)).message;
567
  } else {
568
  for (const entry of keychain.entries) {
569
  message = await del(`/admin/keychain/${encodeURIComponent(entry.id)}`);
 
582
  <ConnectForm
583
  spec={keychain.connect}
584
  label={row.label}
585
+ onCancel={() => {
586
+ setAdding(false);
587
+ onChanged();
588
+ }}
589
  onDone={() => {
590
  setAdding(false);
591
  onChanged();
 
600
  connectorKey={row.key}
601
  spec={keychain.connect}
602
  entry={replacing}
603
+ onCancel={() => {
604
+ setReplacing(null);
605
+ onChanged();
606
+ }}
607
  onDone={() => {
608
  setReplacing(null);
609
  onChanged();
 
621
  ) : null}
622
  {keychain.entries.length ? (
623
  <ul className="conn-kc-list">
624
+ {keychain.entries.map((entry) => {
625
+ const notice = row.key === "amazon_sp"
626
+ ? amazonRotationNotice(entry.client_secret_rotation_deadline, now) : null;
627
+ return (
628
  <li className="conn-kc-row" key={entry.id}>
629
  <div className="conn-kc-main">
630
  <span className="conn-kc-label">{entry.label}</span>
 
636
  {" · "}
637
  {scopeLabel(entry.scope)}
638
  </span>
639
+ {notice ? (
640
+ <RotationNotice
641
+ notice={notice}
642
+ disabled={Boolean(busyId)}
643
+ onRotate={entry.replaceable && keychain.connect
644
+ ? () => setReplacing(entry) : undefined}
645
+ />
646
+ ) : null}
647
+ {tested[entry.id] && notice?.tone !== "expired" ? (
648
  <span className="conn-kc-test" role="status">
649
  {tested[entry.id]}
650
  </span>
651
  ) : null}
652
  </div>
653
  <div className="conn-kc-controls">
654
+ {entry.replaceable && keychain.connect && !notice ? (
655
  <button
656
  type="button"
657
  className="conn-kc-btn"
658
  disabled={Boolean(busyId)}
659
  onClick={() => setReplacing(entry)}
660
  >
661
+ {row.key === "amazon_sp" ? "Rotate secret" : "Replace"}
662
  </button>
663
  ) : null}
664
  {entry.testable ? (
 
684
  )}
685
  </div>
686
  </li>
687
+ );
688
+ })}
689
  </ul>
690
  ) : (
691
  // One line, plus the action that fills it. Never a paragraph (DESIGN.md).
 
700
  <button
701
  type="button"
702
  className="conn-kc-btn is-primary"
703
+ disabled={Boolean(busyId)}
704
+ onClick={() => {
705
+ setError("");
706
+ setAdding(true);
707
+ }}
708
  >
709
  {keychain.entries.length ? "Add another key" : "Connect"}
710
  </button>
web/src/customer-grid/SwipeView.tsx CHANGED
@@ -1,586 +1,586 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / SwipeView.tsx
3
- // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
4
- //
5
- // One record at a time, decided left or right into two options of ONE
6
- // single-select. R2 fixes the shape and it is narrow on purpose:
7
- // · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
- // · the deck holds only the records whose bound field is EMPTY — a record
9
- // that already has a value has been decided, and re-asking is not triage.
10
- // · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
- // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
- // echo-suppression and the permission wall all hold without being
13
- // re-implemented here.
14
- //
15
- // Honesty rules carried from the other modes:
16
- // · nothing is silently hidden — the deck states what is left, and the
17
- // empty state names the bound field rather than saying "all done".
18
- // · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
- // validates that `fieldKey` names a field the table HAS and stops there;
20
- // it cannot know the field is still a select, or that the two options are
21
- // still in its vocabulary (its docstring draws that line explicitly). So
22
- // those three losses land here, and each one says what happened and
23
- // re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
24
- // because the wave-7 trap was a picker silently falling back to its first
25
- // option.
26
- // ---------------------------------------------------------------------------
27
-
28
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
- // ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
30
- // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
- import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
- import { choiceOptions } from "./types";
33
- import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
- // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
- // loaded here) — the same import `RecordComments` takes for the same prop.
36
- import type { SurfaceScope } from "./apiBridge";
37
- import RecordComments from "./RecordComments";
38
- import { Documents } from "./Documents";
39
- import { formatDisplay } from "./cells";
40
- import { actionHref } from "./display";
41
- import { optionTint } from "./choiceColors";
42
- import { ModeIcon } from "./icons";
43
- // ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
44
- // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
- // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
46
- // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
- // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
- import "./SwipeView.css";
49
-
50
- export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
-
52
- /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
- type BindingFault =
54
- | { kind: "unbound" }
55
- | { kind: "field-gone"; fieldKey: string }
56
- | { kind: "not-select"; field: Field }
57
- | { kind: "option-gone"; field: Field; missing: string[] };
58
-
59
- function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
- const field = fieldByKey.get(spec.fieldKey);
63
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
- // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
- // adds and sometimes overwrites is two gestures wearing one button.
67
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
- const options = choiceOptions(field);
69
- const has = new Set(options.map((o) => o.toLowerCase()));
70
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
- return { ok: true, field, spec };
73
- }
74
-
75
- /** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
76
- const isUndecided = (row: Row, key: string): boolean =>
77
- String(row[key] ?? "").trim() === "";
78
-
79
- export function SwipeView({
80
- rows,
81
- fields,
82
- fieldByKey,
83
- spec,
84
- cardKeys,
85
- detailKeys,
86
- scope,
87
- viewer,
88
- docs,
89
- docPayload,
90
- onDocAdd,
91
- onDocFetch,
92
- onDocDelete,
93
- titleKey,
94
- canWrite,
95
- readOnlyReason,
96
- canBind,
97
- onSpec,
98
- onSwipe,
99
- onOpen,
100
- }: {
101
- /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
102
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
- * patch lands; there is no local cursor to drift out of step with the data. */
104
- rows: Row[];
105
- /** Every field, for the picker's field list. */
106
- fields: Field[];
107
- fieldByKey: Map<string, Field>;
108
- /** The stored binding, or undefined for a deck nobody has configured yet. */
109
- spec: SwipeSpec | undefined;
110
- /** The handful of visible fields the card lists under its title. */
111
- cardKeys: string[];
112
- titleKey: string;
113
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
- canWrite: boolean;
115
- /** Stated when the deck cannot be decided — permissions, or a computed column. */
116
- readOnlyReason: string | null;
117
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
- * view-editing permission and NOT `canWrite` — conflating the two is
119
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
- canBind: boolean;
122
- /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
123
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
- onSpec: (next: SwipeSpec | undefined) => void;
125
- onSwipe: (pid: number, value: string) => void;
126
- onOpen: (pid: number) => void;
127
- /**
128
- * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
- *
130
- * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
131
- * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
132
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
- * different amounts. A card must render with none of them rather than throw — the standalone
134
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
- */
136
- /** Every field the VIEW shows, in its order — not the three-key card summary. */
137
- detailKeys?: string[];
138
- /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
139
- * which is the pre-existing precondition `RecordDetail` already carries. */
140
- scope?: SurfaceScope;
141
- viewer?: Viewer;
142
- /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
143
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
- * cannot keep). */
145
- /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
146
- * and that shape cannot serve a deck. */
147
- docs?: Record<string, CustomerDoc[]>;
148
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
- * open record. A deck paints many records at once, so a handler bound to a single pid would
151
- * attach every reviewer's upload to whichever card happened to be open. */
152
- onDocAdd?: (
153
- pid: number,
154
- file: { name: string; mime: string; size: number; data_b64: string }
155
- ) => void;
156
- onDocFetch?: (pid: number, docId: string) => void;
157
- onDocDelete?: (pid: number, docId: string) => void;
158
- }) {
159
- // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
160
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
- // state rather than quietly shrinking the deck (rule 8b).
163
- const [later, setLater] = useState<Set<number>>(new Set());
164
- const deckRef = useRef<HTMLDivElement>(null);
165
-
166
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
- const boundKey = binding.ok ? binding.field.key : null;
168
-
169
- const undecided = useMemo(
170
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
- [rows, boundKey]
172
- );
173
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
- const card = deck[0];
175
-
176
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
177
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
- useEffect(() => {
179
- setLater((prev) => {
180
- if (prev.size === 0) return prev;
181
- const live = new Set(undecided.map((r) => r.pid));
182
- const next = new Set([...prev].filter((pid) => live.has(pid)));
183
- return next.size === prev.size ? prev : next;
184
- });
185
- }, [undecided]);
186
-
187
- const decide = useCallback(
188
- (value: string) => {
189
- if (!card || !canWrite) return;
190
- onSwipe(card.pid, value);
191
- },
192
- [card, canWrite, onSwipe]
193
- );
194
-
195
- // �� / → decide, and they are the SAME two actions the buttons are rather than a second code
196
- // path: the whole point of the mode is that one hand can clear a queue.
197
- useEffect(() => {
198
- if (!binding.ok || !canWrite || !card) return;
199
- const onKey = (e: KeyboardEvent) => {
200
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
- const el = document.activeElement as HTMLElement | null;
202
- // Never steal an arrow key from a text field or a native control the user is inside.
203
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
- return;
205
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
- e.preventDefault();
207
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
- };
209
- window.addEventListener("keydown", onKey);
210
- return () => window.removeEventListener("keydown", onKey);
211
- }, [binding, canWrite, card, decide]);
212
-
213
- if (!binding.ok) {
214
- return (
215
- <div className="cg-swipe" ref={deckRef}>
216
- <SwipeBinder
217
- fault={binding.fault}
218
- fields={fields}
219
- fieldByKey={fieldByKey}
220
- spec={spec}
221
- canBind={canBind}
222
- onSpec={onSpec}
223
- />
224
- </div>
225
- );
226
- }
227
-
228
- const { field } = binding;
229
- const leftTint = optionTint(field, binding.spec.leftOption);
230
- const rightTint = optionTint(field, binding.spec.rightOption);
231
-
232
- return (
233
- <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
- <div className="cg-swipe-bar">
235
- <span className="cg-swipe-bound">
236
- <ModeIcon mode="swipe" />
237
- Sorting into <strong>{field.label}</strong>
238
- </span>
239
- <span className="cg-swipe-left">
240
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
- </span>
242
- {canBind && (
243
- <button
244
- type="button"
245
- className="cg-link-btn"
246
- onClick={() => onSpec(undefined)}
247
- title="Choose a different field or different options for this deck"
248
- >
249
- Change
250
- </button>
251
- )}
252
- </div>
253
- {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
- {card ? (
255
- <div className="cg-swipe-deck">
256
- <button
257
- type="button"
258
- className="cg-swipe-side cg-swipe-side--left"
259
- disabled={!canWrite}
260
- style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
- onClick={() => decide(binding.spec.leftOption)}
262
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
- >
264
- <span aria-hidden className="cg-swipe-arrow">
265
- <svg width="16" height="16" viewBox="0 0 16 16">
266
- <path
267
- d="M11 3.2 6.2 8l4.8 4.8"
268
- fill="none"
269
- stroke="currentColor"
270
- strokeWidth="1.6"
271
- strokeLinecap="round"
272
- strokeLinejoin="round"
273
- />
274
- </svg>
275
- </span>
276
- {binding.spec.leftOption}
277
- </button>
278
- <article
279
- className="cg-swipe-card"
280
- role="button"
281
- tabIndex={0}
282
- onClick={(e) => {
283
- // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
284
- // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
- // card (a url cell, the comments box, the document tray) already stops its own
286
- // click, and the left/right decision buttons are siblings of the card, not
287
- // children of it. The deck also has no pointer drag to disambiguate — its swipe
288
- // is the two buttons and the arrow keys, neither of which opens anything.
289
- // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
- // never arrives here as a synthetic click; the keydown path below is the whole
291
- // keyboard story and the two cannot both fire for one gesture.
292
- if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
- onOpen(card.pid);
294
- }}
295
- onKeyDown={(e) => {
296
- if (e.key !== "Enter" && e.key !== " ") return;
297
- e.preventDefault();
298
- // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
- // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
- if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
- onOpen(card.pid);
302
- }}
303
- >
304
- <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
- <div className="cg-swipe-cells">
306
- {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
307
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
- been widened yet renders exactly what it rendered before. */}
309
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
- const f = fieldByKey.get(k);
311
- if (!f) return null;
312
- const text = formatDisplay(f, card[k]);
313
- if (!text) return null;
314
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
- // scheme guard — and every gesture that reaches it must be stopped from also
316
- // reaching the card, which is a button (the kanban card's note, same trap).
317
- const href = actionHref(f, card[k]);
318
- return (
319
- <div key={k} className="cg-swipe-cell">
320
- <span className="cg-lv-k">{f.label}</span>
321
- {href ? (
322
- <a
323
- className="cg-lv-v"
324
- href={href}
325
- target="_blank"
326
- rel="noopener noreferrer"
327
- title={text}
328
- onClick={(e) => e.stopPropagation()}
329
- onKeyDown={(e) => e.stopPropagation()}
330
- >
331
- {text}
332
- </a>
333
- ) : (
334
- <span className="cg-lv-v">{text}</span>
335
- )}
336
- </div>
337
- );
338
- })}
339
- </div>
340
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
- that opens the record, and a click on a comment box or an upload control must not
342
- also open the modal it exists to make unnecessary (the kanban card's link trap,
343
- one surface over). */}
344
- {onDocAdd && onDocFetch && onDocDelete && (
345
- <div
346
- className="cg-swipe-docs"
347
- onClick={(e) => e.stopPropagation()}
348
- onKeyDown={(e) => e.stopPropagation()}
349
- role="presentation"
350
- >
351
- <Documents
352
- pid={Number(card.pid)}
353
- docs={docs?.[String(card.pid)] ?? []}
354
- docPayload={docPayload}
355
- onAdd={(file) => onDocAdd(card.pid, file)}
356
- onFetch={(docId) => onDocFetch(card.pid, docId)}
357
- onDelete={(docId) => onDocDelete(card.pid, docId)}
358
- />
359
- </div>
360
- )}
361
- {scope != null && (
362
- <div
363
- className="cg-swipe-comments"
364
- onClick={(e) => e.stopPropagation()}
365
- onKeyDown={(e) => e.stopPropagation()}
366
- role="presentation"
367
- >
368
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
- reuses the mounted instance across a card change and paints one record's
370
- comments under another's name until the fetch returns. */}
371
- <RecordComments
372
- key={`${scope}:${Number(card.pid)}`}
373
- scope={scope}
374
- pid={Number(card.pid)}
375
- viewer={viewer}
376
- />
377
- </div>
378
- )}
379
- {canWrite && (
380
- <button
381
- type="button"
382
- className="cg-link-btn cg-swipe-later"
383
- onClick={(e) => {
384
- e.stopPropagation();
385
- setLater((prev) => new Set(prev).add(card.pid));
386
- }}
387
- >
388
- Decide later
389
- </button>
390
- )}
391
- </article>
392
- <button
393
- type="button"
394
- className="cg-swipe-side cg-swipe-side--right"
395
- disabled={!canWrite}
396
- style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
- onClick={() => decide(binding.spec.rightOption)}
398
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
- >
400
- {binding.spec.rightOption}
401
- <span aria-hidden className="cg-swipe-arrow">
402
- <svg width="16" height="16" viewBox="0 0 16 16">
403
- <path
404
- d="M5 3.2 9.8 8 5 12.8"
405
- fill="none"
406
- stroke="currentColor"
407
- strokeWidth="1.6"
408
- strokeLinecap="round"
409
- strokeLinejoin="round"
410
- />
411
- </svg>
412
- </span>
413
- </button>
414
- </div>
415
- ) : (
416
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
- // between "the deck is finished" and "the filter hid everything", and the two want
418
- // different next actions. `later` is disclosed rather than quietly subtracted.
419
- <div className="cg-mode-empty cg-swipe-empty">
420
- {later.size > 0 ? (
421
- <>
422
- <p>
423
- {later.size.toLocaleString()}{" "}
424
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
- in this view is missing a <strong>{field.label}</strong>.
426
- </p>
427
- <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
- Bring them back
429
- </button>
430
- </>
431
- ) : (
432
- <p>
433
- Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
- view's filters to sort more.
435
- </p>
436
- )}
437
- </div>
438
- )}
439
- </div>
440
- );
441
- }
442
-
443
- /**
444
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
- * with the loss stated above it — one place that answers "what is this deck for", rather than an
446
- * error screen beside a separate setup screen.
447
- */
448
- function SwipeBinder({
449
- fault,
450
- fields,
451
- fieldByKey,
452
- spec,
453
- canBind,
454
- onSpec,
455
- }: {
456
- fault: BindingFault;
457
- fields: Field[];
458
- fieldByKey: Map<string, Field>;
459
- spec: SwipeSpec | undefined;
460
- canBind: boolean;
461
- onSpec: (next: SwipeSpec | undefined) => void;
462
- }) {
463
- const selects = useMemo(
464
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
- [fields]
466
- );
467
- const [fieldKey, setFieldKey] = useState<string>(() => {
468
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
- return selects[0]?.key ?? "";
470
- });
471
- const chosen = fieldByKey.get(fieldKey);
472
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
- const [left, setLeft] = useState<string>("");
474
- const [right, setRight] = useState<string>("");
475
-
476
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
- // pick survives re-renders, and reset whenever the field changes — carrying an option from the
478
- // previous field would offer a value the new field cannot hold.
479
- useEffect(() => {
480
- setLeft(options[0] ?? "");
481
- setRight(options.find((o) => o !== options[0]) ?? "");
482
- }, [options]);
483
-
484
- const message = ((): string => {
485
- switch (fault.kind) {
486
- case "field-gone":
487
- return "The field this deck sorted into has been deleted. Pick another one.";
488
- case "not-select":
489
- return `“${fault.field.label}” is no longer a single-select, so it has no options to`
490
- + " sort into. Pick another field.";
491
- case "option-gone":
492
- return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
493
- fault.missing.length === 1 ? "is" : "are"
494
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
495
- fault.field.label
496
- }”. Pick the sides again.`;
497
- default:
498
- return "Sort records one at a time into two options of a single-select field.";
499
- }
500
- })();
501
-
502
- if (!canBind) {
503
- return (
504
- <div className="cg-mode-empty">
505
- <p>{message}</p>
506
- <p>Its creator or an admin can set this view up.</p>
507
- </div>
508
- );
509
- }
510
- if (selects.length === 0) {
511
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
- // requirement is what turns a dead end into a next action.
513
- return (
514
- <div className="cg-mode-empty">
515
- <p>
516
- A swipe deck sorts into a single-select field with at least two options. This database
517
- does not have one yet — add a single-select column, then come back.
518
- </p>
519
- </div>
520
- );
521
- }
522
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
- return (
524
- <div className="cg-swipe-setup">
525
- <p className="cg-swipe-setup-note">{message}</p>
526
- <label className="cg-swipe-setup-row">
527
- <span>Sort into</span>
528
- <select
529
- className="cg-select"
530
- value={fieldKey}
531
- onChange={(e) => setFieldKey(e.target.value)}
532
- >
533
- {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
- renders its FIRST option and reports a choice the user never made
535
- ([[cg-condition-builder-items]]). */}
536
- {selects.map((f) => (
537
- <option key={f.key} value={f.key}>
538
- {f.label}
539
- </option>
540
- ))}
541
- </select>
542
- </label>
543
- <div className="cg-swipe-setup-sides">
544
- <label className="cg-swipe-setup-row">
545
- <span>Swipe left</span>
546
- <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
- {options.map((o) => (
548
- <option key={o} value={o}>
549
- {o}
550
- </option>
551
- ))}
552
- </select>
553
- </label>
554
- <label className="cg-swipe-setup-row">
555
- <span>Swipe right</span>
556
- <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
- {options.map((o) => (
558
- <option key={o} value={o}>
559
- {o}
560
- </option>
561
- ))}
562
- </select>
563
- </label>
564
- </div>
565
- {!ready && left && right && (
566
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
- // option, so a Save that looked like it worked would simply not persist.
568
- <p className="cg-swipe-setup-warn">
569
- The two sides must be different options — otherwise both gestures do the same thing.
570
- </p>
571
- )}
572
- <button
573
- type="button"
574
- className="cg-btn cg-btn--primary"
575
- disabled={!ready}
576
- onClick={() =>
577
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
- }
579
- >
580
- Start sorting
581
- </button>
582
- </div>
583
- );
584
- }
585
-
586
- export default SwipeView;
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / SwipeView.tsx
3
+ // ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
4
+ //
5
+ // One record at a time, decided left or right into two options of ONE
6
+ // single-select. R2 fixes the shape and it is narrow on purpose:
7
+ // · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
8
+ // · the deck holds only the records whose bound field is EMPTY — a record
9
+ // that already has a value has been decided, and re-asking is not triage.
10
+ // · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
11
+ // maps to the same `patchAndRecord` a kanban card move uses), so undo,
12
+ // echo-suppression and the permission wall all hold without being
13
+ // re-implemented here.
14
+ //
15
+ // Honesty rules carried from the other modes:
16
+ // · nothing is silently hidden — the deck states what is left, and the
17
+ // empty state names the bound field rather than saying "all done".
18
+ // · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
19
+ // validates that `fieldKey` names a field the table HAS and stops there;
20
+ // it cannot know the field is still a select, or that the two options are
21
+ // still in its vocabulary (its docstring draws that line explicitly). So
22
+ // those three losses land here, and each one says what happened and
23
+ // re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
24
+ // because the wave-7 trap was a picker silently falling back to its first
25
+ // option.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
+ // ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
30
+ // navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
31
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
32
+ import { choiceOptions } from "./types";
33
+ import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
34
+ // ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
35
+ // loaded here) — the same import `RecordComments` takes for the same prop.
36
+ import type { SurfaceScope } from "./apiBridge";
37
+ import RecordComments from "./RecordComments";
38
+ import { Documents } from "./Documents";
39
+ import { formatDisplay } from "./cells";
40
+ import { actionHref } from "./display";
41
+ import { optionTint } from "./choiceColors";
42
+ import { ModeIcon } from "./icons";
43
+ // ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
44
+ // `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
45
+ // unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
46
+ // a partially-styled surface reads as a design choice, which is why nobody reported it and no
47
+ // gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
48
+ import "./SwipeView.css";
49
+
50
+ export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;
51
+
52
+ /** The three ways a stored binding can rot that the host cannot see (see the header note). */
53
+ type BindingFault =
54
+ | { kind: "unbound" }
55
+ | { kind: "field-gone"; fieldKey: string }
56
+ | { kind: "not-select"; field: Field }
57
+ | { kind: "option-gone"; field: Field; missing: string[] };
58
+
59
+ function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):
60
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
61
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
62
+ const field = fieldByKey.get(spec.fieldKey);
63
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
64
+ // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
65
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
66
+ // adds and sometimes overwrites is two gestures wearing one button.
67
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
68
+ const options = choiceOptions(field);
69
+ const has = new Set(options.map((o) => o.toLowerCase()));
70
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
71
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
72
+ return { ok: true, field, spec };
73
+ }
74
+
75
+ /** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
76
+ const isUndecided = (row: Row, key: string): boolean =>
77
+ String(row[key] ?? "").trim() === "";
78
+
79
+ export function SwipeView({
80
+ rows,
81
+ fields,
82
+ fieldByKey,
83
+ spec,
84
+ cardKeys,
85
+ detailKeys,
86
+ scope,
87
+ viewer,
88
+ docs,
89
+ docPayload,
90
+ onDocAdd,
91
+ onDocFetch,
92
+ onDocDelete,
93
+ titleKey,
94
+ canWrite,
95
+ readOnlyReason,
96
+ canBind,
97
+ onSpec,
98
+ onSwipe,
99
+ onOpen,
100
+ }: {
101
+ /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
102
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
103
+ * patch lands; there is no local cursor to drift out of step with the data. */
104
+ rows: Row[];
105
+ /** Every field, for the picker's field list. */
106
+ fields: Field[];
107
+ fieldByKey: Map<string, Field>;
108
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
109
+ spec: SwipeSpec | undefined;
110
+ /** The handful of visible fields the card lists under its title. */
111
+ cardKeys: string[];
112
+ titleKey: string;
113
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
114
+ canWrite: boolean;
115
+ /** Stated when the deck cannot be decided — permissions, or a computed column. */
116
+ readOnlyReason: string | null;
117
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
118
+ * view-editing permission and NOT `canWrite` — conflating the two is
119
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
120
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
121
+ canBind: boolean;
122
+ /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
123
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
124
+ onSpec: (next: SwipeSpec | undefined) => void;
125
+ onSwipe: (pid: number, value: string) => void;
126
+ onOpen: (pid: number) => void;
127
+ /**
128
+ * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
129
+ *
130
+ * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
131
+ * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
132
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
133
+ * different amounts. A card must render with none of them rather than throw — the standalone
134
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
135
+ */
136
+ /** Every field the VIEW shows, in its order — not the three-key card summary. */
137
+ detailKeys?: string[];
138
+ /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
139
+ * which is the pre-existing precondition `RecordDetail` already carries. */
140
+ scope?: SurfaceScope;
141
+ viewer?: Viewer;
142
+ /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
143
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
144
+ * cannot keep). */
145
+ /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
146
+ * and that shape cannot serve a deck. */
147
+ docs?: Record<string, CustomerDoc[]>;
148
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
149
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
150
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
151
+ * attach every reviewer's upload to whichever card happened to be open. */
152
+ onDocAdd?: (
153
+ pid: number,
154
+ file: { name: string; mime: string; size: number; data_b64: string }
155
+ ) => void;
156
+ onDocFetch?: (pid: number, docId: string) => void;
157
+ onDocDelete?: (pid: number, docId: string) => void;
158
+ }) {
159
+ // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
160
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
161
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
162
+ // state rather than quietly shrinking the deck (rule 8b).
163
+ const [later, setLater] = useState<Set<number>>(new Set());
164
+ const deckRef = useRef<HTMLDivElement>(null);
165
+
166
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
167
+ const boundKey = binding.ok ? binding.field.key : null;
168
+
169
+ const undecided = useMemo(
170
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
171
+ [rows, boundKey]
172
+ );
173
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
174
+ const card = deck[0];
175
+
176
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
177
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
178
+ useEffect(() => {
179
+ setLater((prev) => {
180
+ if (prev.size === 0) return prev;
181
+ const live = new Set(undecided.map((r) => r.pid));
182
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
183
+ return next.size === prev.size ? prev : next;
184
+ });
185
+ }, [undecided]);
186
+
187
+ const decide = useCallback(
188
+ (value: string) => {
189
+ if (!card || !canWrite) return;
190
+ onSwipe(card.pid, value);
191
+ },
192
+ [card, canWrite, onSwipe]
193
+ );
194
+
195
+ // ← / → decide, and they are the SAME two actions the buttons are rather than a second code
196
+ // path: the whole point of the mode is that one hand can clear a queue.
197
+ useEffect(() => {
198
+ if (!binding.ok || !canWrite || !card) return;
199
+ const onKey = (e: KeyboardEvent) => {
200
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
201
+ const el = document.activeElement as HTMLElement | null;
202
+ // Never steal an arrow key from a text field or a native control the user is inside.
203
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
204
+ return;
205
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
206
+ e.preventDefault();
207
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
208
+ };
209
+ window.addEventListener("keydown", onKey);
210
+ return () => window.removeEventListener("keydown", onKey);
211
+ }, [binding, canWrite, card, decide]);
212
+
213
+ if (!binding.ok) {
214
+ return (
215
+ <div className="cg-swipe" ref={deckRef}>
216
+ <SwipeBinder
217
+ fault={binding.fault}
218
+ fields={fields}
219
+ fieldByKey={fieldByKey}
220
+ spec={spec}
221
+ canBind={canBind}
222
+ onSpec={onSpec}
223
+ />
224
+ </div>
225
+ );
226
+ }
227
+
228
+ const { field } = binding;
229
+ const leftTint = optionTint(field, binding.spec.leftOption);
230
+ const rightTint = optionTint(field, binding.spec.rightOption);
231
+
232
+ return (
233
+ <div className="cg-swipe" ref={deckRef} tabIndex={-1}>
234
+ <div className="cg-swipe-bar">
235
+ <span className="cg-swipe-bound">
236
+ <ModeIcon mode="swipe" />
237
+ Sorting into <strong>{field.label}</strong>
238
+ </span>
239
+ <span className="cg-swipe-left">
240
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
241
+ </span>
242
+ {canBind && (
243
+ <button
244
+ type="button"
245
+ className="cg-link-btn"
246
+ onClick={() => onSpec(undefined)}
247
+ title="Choose a different field or different options for this deck"
248
+ >
249
+ Change
250
+ </button>
251
+ )}
252
+ </div>
253
+ {readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}
254
+ {card ? (
255
+ <div className="cg-swipe-deck">
256
+ <button
257
+ type="button"
258
+ className="cg-swipe-side cg-swipe-side--left"
259
+ disabled={!canWrite}
260
+ style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}
261
+ onClick={() => decide(binding.spec.leftOption)}
262
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
263
+ >
264
+ <span aria-hidden className="cg-swipe-arrow">
265
+ <svg width="16" height="16" viewBox="0 0 16 16">
266
+ <path
267
+ d="M11 3.2 6.2 8l4.8 4.8"
268
+ fill="none"
269
+ stroke="currentColor"
270
+ strokeWidth="1.6"
271
+ strokeLinecap="round"
272
+ strokeLinejoin="round"
273
+ />
274
+ </svg>
275
+ </span>
276
+ {binding.spec.leftOption}
277
+ </button>
278
+ <article
279
+ className="cg-swipe-card"
280
+ role="button"
281
+ tabIndex={0}
282
+ onClick={(e) => {
283
+ // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
284
+ // ⚠ Nothing that is NOT an open can reach this line: every control inside the
285
+ // card (a url cell, the comments box, the document tray) already stops its own
286
+ // click, and the left/right decision buttons are siblings of the card, not
287
+ // children of it. The deck also has no pointer drag to disambiguate — its swipe
288
+ // is the two buttons and the arrow keys, neither of which opens anything.
289
+ // ⚠ `<article role="button">`, not a native button, so a keyboard activation
290
+ // never arrives here as a synthetic click; the keydown path below is the whole
291
+ // keyboard story and the two cannot both fire for one gesture.
292
+ if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
293
+ onOpen(card.pid);
294
+ }}
295
+ onKeyDown={(e) => {
296
+ if (e.key !== "Enter" && e.key !== " ") return;
297
+ e.preventDefault();
298
+ // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
299
+ // auto-repeats keydown, and every one of those repeats is the SAME gesture.
300
+ if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
301
+ onOpen(card.pid);
302
+ }}
303
+ >
304
+ <h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3>
305
+ <div className="cg-swipe-cells">
306
+ {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
307
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
308
+ been widened yet renders exactly what it rendered before. */}
309
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
310
+ const f = fieldByKey.get(k);
311
+ if (!f) return null;
312
+ const text = formatDisplay(f, card[k]);
313
+ if (!text) return null;
314
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
315
+ // scheme guard — and every gesture that reaches it must be stopped from also
316
+ // reaching the card, which is a button (the kanban card's note, same trap).
317
+ const href = actionHref(f, card[k]);
318
+ return (
319
+ <div key={k} className="cg-swipe-cell">
320
+ <span className="cg-lv-k">{f.label}</span>
321
+ {href ? (
322
+ <a
323
+ className="cg-lv-v"
324
+ href={href}
325
+ target="_blank"
326
+ rel="noopener noreferrer"
327
+ title={text}
328
+ onClick={(e) => e.stopPropagation()}
329
+ onKeyDown={(e) => e.stopPropagation()}
330
+ >
331
+ {text}
332
+ </a>
333
+ ) : (
334
+ <span className="cg-lv-v">{text}</span>
335
+ )}
336
+ </div>
337
+ );
338
+ })}
339
+ </div>
340
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
341
+ that opens the record, and a click on a comment box or an upload control must not
342
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
343
+ one surface over). */}
344
+ {onDocAdd && onDocFetch && onDocDelete && (
345
+ <div
346
+ className="cg-swipe-docs"
347
+ onClick={(e) => e.stopPropagation()}
348
+ onKeyDown={(e) => e.stopPropagation()}
349
+ role="presentation"
350
+ >
351
+ <Documents
352
+ pid={Number(card.pid)}
353
+ docs={docs?.[String(card.pid)] ?? []}
354
+ docPayload={docPayload}
355
+ onAdd={(file) => onDocAdd(card.pid, file)}
356
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
357
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
358
+ />
359
+ </div>
360
+ )}
361
+ {scope != null && (
362
+ <div
363
+ className="cg-swipe-comments"
364
+ onClick={(e) => e.stopPropagation()}
365
+ onKeyDown={(e) => e.stopPropagation()}
366
+ role="presentation"
367
+ >
368
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
369
+ reuses the mounted instance across a card change and paints one record's
370
+ comments under another's name until the fetch returns. */}
371
+ <RecordComments
372
+ key={`${scope}:${Number(card.pid)}`}
373
+ scope={scope}
374
+ pid={Number(card.pid)}
375
+ viewer={viewer}
376
+ />
377
+ </div>
378
+ )}
379
+ {canWrite && (
380
+ <button
381
+ type="button"
382
+ className="cg-link-btn cg-swipe-later"
383
+ onClick={(e) => {
384
+ e.stopPropagation();
385
+ setLater((prev) => new Set(prev).add(card.pid));
386
+ }}
387
+ >
388
+ Decide later
389
+ </button>
390
+ )}
391
+ </article>
392
+ <button
393
+ type="button"
394
+ className="cg-swipe-side cg-swipe-side--right"
395
+ disabled={!canWrite}
396
+ style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}
397
+ onClick={() => decide(binding.spec.rightOption)}
398
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
399
+ >
400
+ {binding.spec.rightOption}
401
+ <span aria-hidden className="cg-swipe-arrow">
402
+ <svg width="16" height="16" viewBox="0 0 16 16">
403
+ <path
404
+ d="M5 3.2 9.8 8 5 12.8"
405
+ fill="none"
406
+ stroke="currentColor"
407
+ strokeWidth="1.6"
408
+ strokeLinecap="round"
409
+ strokeLinejoin="round"
410
+ />
411
+ </svg>
412
+ </span>
413
+ </button>
414
+ </div>
415
+ ) : (
416
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
417
+ // between "the deck is finished" and "the filter hid everything", and the two want
418
+ // different next actions. `later` is disclosed rather than quietly subtracted.
419
+ <div className="cg-mode-empty cg-swipe-empty">
420
+ {later.size > 0 ? (
421
+ <>
422
+ <p>
423
+ {later.size.toLocaleString()}{" "}
424
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
425
+ in this view is missing a <strong>{field.label}</strong>.
426
+ </p>
427
+ <button type="button" className="cg-btn" onClick={() => setLater(new Set())}>
428
+ Bring them back
429
+ </button>
430
+ </>
431
+ ) : (
432
+ <p>
433
+ Every record in this view already has a <strong>{field.label}</strong>. Widen the
434
+ view's filters to sort more.
435
+ </p>
436
+ )}
437
+ </div>
438
+ )}
439
+ </div>
440
+ );
441
+ }
442
+
443
+ /**
444
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
445
+ * with the loss stated above it — one place that answers "what is this deck for", rather than an
446
+ * error screen beside a separate setup screen.
447
+ */
448
+ function SwipeBinder({
449
+ fault,
450
+ fields,
451
+ fieldByKey,
452
+ spec,
453
+ canBind,
454
+ onSpec,
455
+ }: {
456
+ fault: BindingFault;
457
+ fields: Field[];
458
+ fieldByKey: Map<string, Field>;
459
+ spec: SwipeSpec | undefined;
460
+ canBind: boolean;
461
+ onSpec: (next: SwipeSpec | undefined) => void;
462
+ }) {
463
+ const selects = useMemo(
464
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
465
+ [fields]
466
+ );
467
+ const [fieldKey, setFieldKey] = useState<string>(() => {
468
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
469
+ return selects[0]?.key ?? "";
470
+ });
471
+ const chosen = fieldByKey.get(fieldKey);
472
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
473
+ const [left, setLeft] = useState<string>("");
474
+ const [right, setRight] = useState<string>("");
475
+
476
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
477
+ // pick survives re-renders, and reset whenever the field changes — carrying an option from the
478
+ // previous field would offer a value the new field cannot hold.
479
+ useEffect(() => {
480
+ setLeft(options[0] ?? "");
481
+ setRight(options.find((o) => o !== options[0]) ?? "");
482
+ }, [options]);
483
+
484
+ const message = ((): string => {
485
+ switch (fault.kind) {
486
+ case "field-gone":
487
+ return "The field this deck sorted into has been deleted. Pick another one.";
488
+ case "not-select":
489
+ return `“${fault.field.label}” is no longer a single-select, so it has no options to`
490
+ + " sort into. Pick another field.";
491
+ case "option-gone":
492
+ return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
493
+ fault.missing.length === 1 ? "is" : "are"
494
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
495
+ fault.field.label
496
+ }”. Pick the sides again.`;
497
+ default:
498
+ return "Sort records one at a time into two options of a single-select field.";
499
+ }
500
+ })();
501
+
502
+ if (!canBind) {
503
+ return (
504
+ <div className="cg-mode-empty">
505
+ <p>{message}</p>
506
+ <p>Its creator or an admin can set this view up.</p>
507
+ </div>
508
+ );
509
+ }
510
+ if (selects.length === 0) {
511
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
512
+ // requirement is what turns a dead end into a next action.
513
+ return (
514
+ <div className="cg-mode-empty">
515
+ <p>
516
+ A swipe deck sorts into a single-select field with at least two options. This database
517
+ does not have one yet — add a single-select column, then come back.
518
+ </p>
519
+ </div>
520
+ );
521
+ }
522
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
523
+ return (
524
+ <div className="cg-swipe-setup">
525
+ <p className="cg-swipe-setup-note">{message}</p>
526
+ <label className="cg-swipe-setup-row">
527
+ <span>Sort into</span>
528
+ <select
529
+ className="cg-select"
530
+ value={fieldKey}
531
+ onChange={(e) => setFieldKey(e.target.value)}
532
+ >
533
+ {/* Every option carries an explicit `value`: a <select> whose value names nothing
534
+ renders its FIRST option and reports a choice the user never made
535
+ ([[cg-condition-builder-items]]). */}
536
+ {selects.map((f) => (
537
+ <option key={f.key} value={f.key}>
538
+ {f.label}
539
+ </option>
540
+ ))}
541
+ </select>
542
+ </label>
543
+ <div className="cg-swipe-setup-sides">
544
+ <label className="cg-swipe-setup-row">
545
+ <span>Swipe left</span>
546
+ <select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>
547
+ {options.map((o) => (
548
+ <option key={o} value={o}>
549
+ {o}
550
+ </option>
551
+ ))}
552
+ </select>
553
+ </label>
554
+ <label className="cg-swipe-setup-row">
555
+ <span>Swipe right</span>
556
+ <select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>
557
+ {options.map((o) => (
558
+ <option key={o} value={o}>
559
+ {o}
560
+ </option>
561
+ ))}
562
+ </select>
563
+ </label>
564
+ </div>
565
+ {!ready && left && right && (
566
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
567
+ // option, so a Save that looked like it worked would simply not persist.
568
+ <p className="cg-swipe-setup-warn">
569
+ The two sides must be different options — otherwise both gestures do the same thing.
570
+ </p>
571
+ )}
572
+ <button
573
+ type="button"
574
+ className="cg-btn cg-btn--primary"
575
+ disabled={!ready}
576
+ onClick={() =>
577
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
578
+ }
579
+ >
580
+ Start sorting
581
+ </button>
582
+ </div>
583
+ );
584
+ }
585
+
586
+ export default SwipeView;
web/src/settings/CompliancePane.tsx ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from "react";
2
+ import { API_V1, CREDENTIALS, checkTenant, UNAUTHORIZED_EVENT } from "../apiContract";
3
+ import "../styles/wave59/security.css";
4
+
5
+ type ClaimState = "met" | "not_met" | "unproven";
6
+ type Claim = {
7
+ id: string;
8
+ group: string;
9
+ claim: string;
10
+ state: ClaimState;
11
+ evidence: string;
12
+ source: string | null;
13
+ };
14
+ type Compliance = { claims: Claim[]; generated_at: number };
15
+
16
+ const STATE_WORDS: Record<ClaimState, string> = {
17
+ met: "Met", not_met: "Not met", unproven: "Unproven",
18
+ };
19
+ const UNAVAILABLE = "Amazon compliance could not be loaded. Try reopening Settings.";
20
+
21
+ function requireResponse(response: Response): void {
22
+ if (checkTenant(response)) throw new Error(UNAVAILABLE);
23
+ if (response.status === 401) {
24
+ window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
25
+ throw new Error("Sign in again to view Amazon compliance.");
26
+ }
27
+ if (response.status === 403) throw new Error("Amazon compliance is available to administrators only.");
28
+ if (!response.ok) throw new Error(UNAVAILABLE);
29
+ }
30
+
31
+ function isClaim(value: unknown): value is Claim {
32
+ if (!value || typeof value !== "object") return false;
33
+ const row = value as Record<string, unknown>;
34
+ return ["id", "group", "claim", "evidence"].every((key) =>
35
+ typeof row[key] === "string" && row[key].trim().length > 0)
36
+ && (row.state === "met" || row.state === "not_met" || row.state === "unproven")
37
+ && (row.source === null || typeof row.source === "string");
38
+ }
39
+
40
+ function readCompliance(value: unknown): Compliance {
41
+ if (!value || typeof value !== "object") throw new Error(UNAVAILABLE);
42
+ const payload = value as Record<string, unknown>;
43
+ if (!Array.isArray(payload.claims) || !payload.claims.length || !payload.claims.every(isClaim)
44
+ || new Set(payload.claims.map((row) => row.id)).size !== payload.claims.length
45
+ || typeof payload.generated_at !== "number" || !Number.isFinite(payload.generated_at)) {
46
+ throw new Error(UNAVAILABLE);
47
+ }
48
+ return { claims: payload.claims, generated_at: payload.generated_at };
49
+ }
50
+
51
+ export default function CompliancePane() {
52
+ const [payload, setPayload] = useState<Compliance | null>(null);
53
+ const [loading, setLoading] = useState(true);
54
+ const [error, setError] = useState("");
55
+ const [downloading, setDownloading] = useState(false);
56
+ const [notice, setNotice] = useState("");
57
+
58
+ useEffect(() => {
59
+ const controller = new AbortController();
60
+ async function load() {
61
+ try {
62
+ const response = await fetch(`${API_V1}/security/compliance`, {
63
+ credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
64
+ });
65
+ requireResponse(response);
66
+ const result = readCompliance(await response.json());
67
+ if (!controller.signal.aborted) setPayload(result);
68
+ } catch (failure) {
69
+ if (!controller.signal.aborted) {
70
+ setError(failure instanceof Error && [UNAVAILABLE,
71
+ "Sign in again to view Amazon compliance.",
72
+ "Amazon compliance is available to administrators only."].includes(failure.message)
73
+ ? failure.message : UNAVAILABLE);
74
+ }
75
+ } finally {
76
+ if (!controller.signal.aborted) setLoading(false);
77
+ }
78
+ }
79
+ void load();
80
+ return () => controller.abort();
81
+ }, []);
82
+
83
+ async function downloadEvidence() {
84
+ if (downloading) return;
85
+ setDownloading(true);
86
+ setError("");
87
+ setNotice("");
88
+ try {
89
+ const response = await fetch(`${API_V1}/security/compliance/export`, {
90
+ credentials: CREDENTIALS, cache: "no-store",
91
+ });
92
+ requireResponse(response);
93
+ if (!response.headers.get("Content-Type")?.startsWith("text/plain")) throw new Error(UNAVAILABLE);
94
+ const body = await response.text();
95
+ const url = URL.createObjectURL(new Blob([body], { type: "text/plain;charset=utf-8" }));
96
+ const anchor = window.document.createElement("a");
97
+ anchor.href = url;
98
+ anchor.download = "amazon-compliance.txt";
99
+ window.document.body.appendChild(anchor);
100
+ anchor.click();
101
+ anchor.remove();
102
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
103
+ setNotice("amazon-compliance.txt downloaded. It contains no credential or other secret.");
104
+ } catch {
105
+ setError("The evidence file could not be downloaded. Try reopening Settings.");
106
+ } finally {
107
+ setDownloading(false);
108
+ }
109
+ }
110
+
111
+ const groups = new Map<string, Claim[]>();
112
+ for (const claim of payload?.claims ?? []) {
113
+ const rows = groups.get(claim.group) ?? [];
114
+ rows.push(claim);
115
+ groups.set(claim.group, rows);
116
+ }
117
+
118
+ return (
119
+ <div className="set-pane">
120
+ <h3 className="set-h">Amazon compliance</h3>
121
+ {loading ? <p className="set-help" role="status">Reading the current controls…</p> : null}
122
+ {error ? <p className="set-error" role="alert">{error}</p> : null}
123
+ {payload ? <>
124
+ <p className="set-help">Observed {new Date(payload.generated_at * 1000).toLocaleString()}.</p>
125
+ <button type="button" className="security-compliance-download" disabled={downloading}
126
+ onClick={() => void downloadEvidence()}>
127
+ {downloading ? "Preparing the evidence file…" : "Download the evidence file"}
128
+ </button>
129
+ {notice ? <p className="set-help" role="status">{notice}</p> : null}
130
+ {Array.from(groups, ([group, claims]) => (
131
+ <section className="security-compliance-group" key={group}>
132
+ <h4 className="security-compliance-heading">{group}</h4>
133
+ <ul className="security-compliance-list">
134
+ {claims.map((claim) => (
135
+ <li className="security-compliance-row" key={claim.id} data-claim-id={claim.id}>
136
+ <div className="security-compliance-claim">
137
+ <span>{claim.claim}</span>
138
+ <span className={`security-compliance-state is-${claim.state.replace("_", "-")}`}>
139
+ {STATE_WORDS[claim.state]}
140
+ </span>
141
+ </div>
142
+ <p className="security-compliance-evidence">{claim.evidence}</p>
143
+ </li>
144
+ ))}
145
+ </ul>
146
+ </section>
147
+ ))}
148
+ </> : null}
149
+ </div>
150
+ );
151
+ }
web/src/settings/SecurityPane.tsx CHANGED
@@ -1,20 +1,164 @@
1
  // ---------------------------------------------------------------------------
2
  // settings / SecurityPane.tsx - W57-T36, R15 / C12.
3
  //
4
- // Every stored account owns its second factor, so this is a session-scoped
5
- // room for every user. It reads status, never the installed secret. A new phone
6
- // goes through the admin reset and the login enrolment door, not a second editor.
 
7
  // ---------------------------------------------------------------------------
8
 
9
- import { useEffect, useRef, useState } from "react";
10
  import type { FormEvent } from "react";
11
- import { mfaStatus, regenerateRecoveryCodes } from "../shell/session";
12
- import type { MFAStatus } from "../shell/session";
13
- import { RecoveryCodes } from "../shell/LoginPage";
14
  import { useEscapeClose } from "../ui/useEscapeClose";
 
15
  import "../styles/wave57/login-mfa.css";
 
16
 
17
- export default function SecurityPane() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  const [status, setStatus] = useState<MFAStatus | null>(null);
19
  const [loading, setLoading] = useState<boolean>(true);
20
  const [reload, setReload] = useState<number>(0);
@@ -22,12 +166,22 @@ export default function SecurityPane() {
22
  const [busy, setBusy] = useState<boolean>(false);
23
  const [codes, setCodes] = useState<string[] | null>(null);
24
  const [error, setError] = useState<string>("");
 
 
 
 
 
 
25
  const flight = useRef<boolean>(false);
26
  const dialog = useRef<HTMLDialogElement>(null);
27
  const passwordField = useRef<HTMLInputElement>(null);
 
28
  const locked = busy || codes !== null;
 
 
29
 
30
  useEffect(() => {
 
31
  let current = true;
32
  setLoading(true);
33
  setError("");
@@ -38,7 +192,26 @@ export default function SecurityPane() {
38
  if (!next) setError("Security status could not be loaded. Try again.");
39
  });
40
  return () => { current = false; };
41
- }, [reload]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  // Lock BEFORE issuing codes, not only after receiving them: closing Settings
44
  // during the POST would throw away its only clear response. A native modal
@@ -77,10 +250,60 @@ export default function SecurityPane() {
77
  setBusy(false);
78
  }
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  return (
81
  <div className="set-pane login-form login-mfa-security">
82
- <h3 className="set-h">Security</h3>
83
- {loading ? <p className="login-mfa-help" role="status">Loading security status…</p> : status ? (
 
 
84
  <>
85
  <dl className="login-mfa-status">
86
  <div><dt>Two step sign in</dt><dd>{status.enrolled ? "On" : "Off"}</dd></div>
@@ -91,21 +314,29 @@ export default function SecurityPane() {
91
  ) : null}
92
  <div><dt>Recovery codes left</dt><dd>{status.recoveryCodesRemaining}</dd></div>
93
  </dl>
94
- <p className="login-mfa-help">To enrol a new phone, ask an administrator to reset two step sign in, then sign in again.</p>
95
  {status.enrolled ? (
96
  <>
97
- <p className="login-mfa-help">Generating new recovery codes replaces the old codes and signs this account's other sessions out.</p>
98
- {!locked ? (
99
- <form className="login-form login-mfa-regenerate" onSubmit={generate}>
100
- <label className="login-mfa-label" htmlFor="security-password">Account password</label>
101
- <input id="security-password" className="login-input" type="password" autoComplete="current-password"
102
- ref={passwordField} value={password} disabled={busy} required
103
- aria-invalid={error ? true : undefined} aria-describedby="security-message"
104
- onChange={(event) => { setPassword(event.target.value); setError(""); }} />
105
- <button type="submit" className="login-submit" disabled={!password || busy}>
106
- Generate new recovery codes
107
- </button>
108
- </form>
 
 
 
 
 
 
 
 
 
109
  ) : null}
110
  </>
111
  ) : <p className="login-mfa-help">Sign in again to set up your authenticator app.</p>}
@@ -115,6 +346,47 @@ export default function SecurityPane() {
115
  Try again
116
  </button>
117
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  <p className="login-msg" id="security-message" role="status" aria-live="polite">{locked ? "" : error}</p>
119
 
120
  {/* R15/C12's explicit acknowledgement is the exception to ordinary
@@ -127,6 +399,13 @@ export default function SecurityPane() {
127
  <div className="login-form">
128
  {codes ? (
129
  <RecoveryCodes codes={codes} onError={setError} onSaved={() => {
 
 
 
 
 
 
 
130
  setCodes(null);
131
  setError("");
132
  // Count only, independently re-read after acknowledgement.
 
1
  // ---------------------------------------------------------------------------
2
  // settings / SecurityPane.tsx - W57-T36, R15 / C12.
3
  //
4
+ // Every stored account owns its second factor. W59-T31 also renders this pane
5
+ // before a session exists: R1 moves the enrollment screen, never the MFA wall.
6
+ // Settings reads status, never the installed secret, and can replace a phone
7
+ // only after password re-authentication and proof of the candidate factor.
8
  // ---------------------------------------------------------------------------
9
 
10
+ import { useEffect, useMemo, useRef, useState } from "react";
11
  import type { FormEvent } from "react";
12
+ import { errorMessage, mfaEnrollConfirm, mfaEnrollStart, mfaStatus, regenerateRecoveryCodes, SERVER_UNAVAILABLE } from "../shell/session";
13
+ import type { MFASetup, MFAStatus, SessionUser } from "../shell/session";
14
+ import { API_V1, CREDENTIALS, checkTenant } from "../apiContract";
15
  import { useEscapeClose } from "../ui/useEscapeClose";
16
+ import { encodeQr } from "../shell/qrcode";
17
  import "../styles/wave57/login-mfa.css";
18
+ import "../styles/wave59/security.css";
19
 
20
+ function SetupQr({ uri }: { uri: string }) {
21
+ const drawing = useMemo(() => {
22
+ try {
23
+ const qr = encodeQr(uri);
24
+ const quiet = 4;
25
+ // One path keeps the modal's DOM small; the four-module light border
26
+ // belongs in the viewBox so responsive sizing cannot crop it away.
27
+ const path = qr.modules.flatMap((row, y) => row.flatMap((dark, x) =>
28
+ dark ? [`M${x + quiet} ${y + quiet}h1v1h-1z`] : [])).join("");
29
+ return { extent: qr.size + 2 * quiet, path };
30
+ } catch {
31
+ // Keep enrollment usable, but never draw a plausible square on failure.
32
+ return null;
33
+ }
34
+ }, [uri]);
35
+ if (!drawing) return <p className="security-qr-help">The QR code could not be drawn.</p>;
36
+ return (
37
+ <>
38
+ <p className="security-qr-help">Or scan this code with your authenticator app.</p>
39
+ <svg className="security-qr-image" viewBox={`0 0 ${drawing.extent} ${drawing.extent}`}
40
+ shapeRendering="crispEdges" role="img" aria-label="Setup code as a QR code" focusable="false">
41
+ <rect className="security-qr-field" width={drawing.extent} height={drawing.extent} />
42
+ <path fill="currentColor" d={drawing.path} />
43
+ </svg>
44
+ </>
45
+ );
46
+ }
47
+
48
+ /** W57-T36 / C12: one show-once treatment in both doors. Copy is a quiet,
49
+ * explicit export to the person's clipboard, never persistence on their behalf.
50
+ * Only the acknowledgement can dismiss this surface; Escape names what remains.
51
+ * Browser reload/close can only be warned about, never made impossible by a page. */
52
+ export function RecoveryCodes({ codes, onSaved, onError }: {
53
+ codes: string[];
54
+ onSaved: () => void;
55
+ onError: (message: string) => void;
56
+ }) {
57
+ const [copied, setCopied] = useState<boolean>(false);
58
+ const [copying, setCopying] = useState<boolean>(false);
59
+ useEscapeClose(true, () => onError("Save your recovery codes before continuing."));
60
+ useEffect(() => {
61
+ const warn = (event: BeforeUnloadEvent) => {
62
+ event.preventDefault();
63
+ event.returnValue = "";
64
+ };
65
+ window.addEventListener("beforeunload", warn);
66
+ return () => window.removeEventListener("beforeunload", warn);
67
+ }, []);
68
+
69
+ async function copy() {
70
+ if (copying) return;
71
+ setCopying(true);
72
+ try {
73
+ await navigator.clipboard.writeText(codes.join("\n"));
74
+ setCopied(true);
75
+ onError("");
76
+ } catch {
77
+ setCopied(false);
78
+ onError("Copy did not work. Select the codes and copy them manually.");
79
+ } finally {
80
+ setCopying(false);
81
+ }
82
+ }
83
+
84
+ return (
85
+ <>
86
+ <p className="login-mfa-help">This screen is the only place these recovery codes will ever be shown.</p>
87
+ <p className="login-mfa-help">Save them somewhere safe; each code works once if you lose your authenticator.</p>
88
+ <ul className="login-mfa-codes" aria-label="Recovery codes">
89
+ {codes.map((code) => <li key={code}><code>{code}</code></li>)}
90
+ </ul>
91
+ <div className="login-mfa-copy-row">
92
+ <button type="button" className="login-mfa-quiet" onClick={() => void copy()} disabled={copying}>
93
+ {copying ? "Copying…" : "Copy codes"}
94
+ </button>
95
+ <span className="login-mfa-copy-status" role="status">{copied ? "Copied" : ""}</span>
96
+ </div>
97
+ {/* A type=button acknowledgement cannot be submitted by Enter left over
98
+ from the previous code field. There is no Back or secondary exit. */}
99
+ <button type="button" className="login-submit" onClick={onSaved} disabled={copying}>
100
+ I have saved these codes
101
+ </button>
102
+ </>
103
+ );
104
+ }
105
+
106
+ type AuthFailure = { ok: false; message: string };
107
+
108
+ // Keep the literal fetch doors visible to D-48. These session-scoped helpers
109
+ // mirror authPost's tenant guard and error policy without creating a second session module.
110
+ async function startDevice(password: string): Promise<({ ok: true } & MFASetup) | AuthFailure> {
111
+ let res: Response;
112
+ try {
113
+ res = await fetch(`${API_V1}/auth/mfa/device`, {
114
+ method: "POST", credentials: CREDENTIALS, cache: "no-store",
115
+ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }),
116
+ });
117
+ } catch {
118
+ return { ok: false, message: errorMessage(0, null) };
119
+ }
120
+ if (checkTenant(res)) return { ok: false, message: SERVER_UNAVAILABLE };
121
+ const body = await res.json().catch(() => null);
122
+ if (!res.ok) return { ok: false, message: errorMessage(res.status, body) };
123
+ if (!body || typeof body.secret !== "string" || !body.secret.trim()
124
+ || typeof body.otpauthUri !== "string" || !body.otpauthUri.trim()
125
+ || typeof body.issuer !== "string" || !body.issuer.trim())
126
+ return { ok: false, message: SERVER_UNAVAILABLE };
127
+ return { ok: true, secret: body.secret, otpauthUri: body.otpauthUri, issuer: body.issuer };
128
+ }
129
+
130
+ async function confirmDevice(password: string, secret: string, code: string): Promise<
131
+ { ok: true; recoveryCodes: string[] } | AuthFailure
132
+ > {
133
+ let res: Response;
134
+ try {
135
+ res = await fetch(`${API_V1}/auth/mfa/device/confirm`, {
136
+ method: "POST", credentials: CREDENTIALS, cache: "no-store",
137
+ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password, secret, code }),
138
+ });
139
+ } catch {
140
+ return { ok: false, message: errorMessage(0, null) };
141
+ }
142
+ if (checkTenant(res)) return { ok: false, message: SERVER_UNAVAILABLE };
143
+ const body = await res.json().catch(() => null);
144
+ if (!res.ok) return { ok: false, message: errorMessage(res.status, body) };
145
+ const codes: unknown = body?.recoveryCodes;
146
+ // Accept the whole fresh set or refuse success, just like the existing issuers.
147
+ if (!Array.isArray(codes) || codes.length === 0
148
+ || !codes.every((value): value is string => typeof value === "string" && value.trim().length > 0)
149
+ || new Set(codes).size !== codes.length)
150
+ return { ok: false, message: SERVER_UNAVAILABLE };
151
+ return { ok: true, recoveryCodes: codes };
152
+ }
153
+
154
+ export type EnrolmentGate = {
155
+ username: string;
156
+ password: string;
157
+ onEnrolled: (user: SessionUser, recoveryCodes: string[]) => void;
158
+ onBack: () => void;
159
+ };
160
+
161
+ export default function SecurityPane({ gate }: { gate?: EnrolmentGate } = {}) {
162
  const [status, setStatus] = useState<MFAStatus | null>(null);
163
  const [loading, setLoading] = useState<boolean>(true);
164
  const [reload, setReload] = useState<number>(0);
 
166
  const [busy, setBusy] = useState<boolean>(false);
167
  const [codes, setCodes] = useState<string[] | null>(null);
168
  const [error, setError] = useState<string>("");
169
+ const [device, setDevice] = useState<boolean>(false);
170
+ const [setup, setSetup] = useState<MFASetup | null>(null);
171
+ const [code, setCode] = useState<string>("");
172
+ const [preparing, setPreparing] = useState<boolean>(false);
173
+ const [setupRetry, setSetupRetry] = useState<number>(0);
174
+ const [enrolledUser, setEnrolledUser] = useState<SessionUser | null>(null);
175
  const flight = useRef<boolean>(false);
176
  const dialog = useRef<HTMLDialogElement>(null);
177
  const passwordField = useRef<HTMLInputElement>(null);
178
+ const heading = useRef<HTMLHeadingElement>(null);
179
  const locked = busy || codes !== null;
180
+ const gateUsername = gate?.username;
181
+ const gatePassword = gate?.password;
182
 
183
  useEffect(() => {
184
+ if (gate) return;
185
  let current = true;
186
  setLoading(true);
187
  setError("");
 
192
  if (!next) setError("Security status could not be loaded. Try again.");
193
  });
194
  return () => { current = false; };
195
+ }, [gate, reload]);
196
+
197
+ // Scalar dependencies keep a parent re-render from replacing the candidate.
198
+ // Starting setup is read-only; ignore a late response after Back or a retry.
199
+ useEffect(() => {
200
+ if (gateUsername === undefined || gatePassword === undefined) return;
201
+ let current = true;
202
+ heading.current?.focus();
203
+ setPreparing(true);
204
+ setSetup(null);
205
+ setCode("");
206
+ setError("");
207
+ void mfaEnrollStart(gateUsername, gatePassword).then((result) => {
208
+ if (!current) return;
209
+ setPreparing(false);
210
+ if (result.ok === false) setError(result.message);
211
+ else setSetup(result);
212
+ });
213
+ return () => { current = false; };
214
+ }, [gateUsername, gatePassword, setupRetry]);
215
 
216
  // Lock BEFORE issuing codes, not only after receiving them: closing Settings
217
  // during the POST would throw away its only clear response. A native modal
 
250
  setBusy(false);
251
  }
252
 
253
+ async function enrol(event: FormEvent) {
254
+ event.preventDefault();
255
+ if (flight.current || locked || preparing) return;
256
+ if (!setup) {
257
+ if (gate) {
258
+ setSetupRetry((value) => value + 1);
259
+ return;
260
+ }
261
+ if (!status?.enrolled || !password) return;
262
+ flight.current = true;
263
+ setPreparing(true);
264
+ setError("");
265
+ try {
266
+ const result = await startDevice(password);
267
+ if (result.ok === false) {
268
+ setError(result.message);
269
+ setPassword("");
270
+ } else setSetup(result);
271
+ } finally {
272
+ flight.current = false;
273
+ setPreparing(false);
274
+ }
275
+ return;
276
+ }
277
+ if (!code || (!gate && (!status?.enrolled || !password))) return;
278
+ flight.current = true;
279
+ setBusy(true);
280
+ setError("");
281
+ try {
282
+ const result: { ok: true; user?: SessionUser; recoveryCodes: string[] } | AuthFailure = gate
283
+ ? await mfaEnrollConfirm(gate.username, gate.password, setup.secret, code)
284
+ : await confirmDevice(password, setup.secret, code);
285
+ if (result.ok === false) setError(result.message);
286
+ else {
287
+ // A cookie exists only now. The frame still waits for the show-once acknowledgement.
288
+ if (result.user) setEnrolledUser(result.user);
289
+ setCodes(result.recoveryCodes);
290
+ setSetup(null);
291
+ setDevice(false);
292
+ }
293
+ } finally {
294
+ setPassword("");
295
+ setCode("");
296
+ flight.current = false;
297
+ setBusy(false);
298
+ }
299
+ }
300
+
301
  return (
302
  <div className="set-pane login-form login-mfa-security">
303
+ <h3 className="set-h" ref={heading} tabIndex={gate ? -1 : undefined}>Security</h3>
304
+ {gate ? (
305
+ <p className="login-mfa-help">Two step sign in is required before the rest of the app opens.</p>
306
+ ) : loading ? <p className="login-mfa-help" role="status">Loading security status…</p> : status ? (
307
  <>
308
  <dl className="login-mfa-status">
309
  <div><dt>Two step sign in</dt><dd>{status.enrolled ? "On" : "Off"}</dd></div>
 
314
  ) : null}
315
  <div><dt>Recovery codes left</dt><dd>{status.recoveryCodesRemaining}</dd></div>
316
  </dl>
 
317
  {status.enrolled ? (
318
  <>
319
+ {!device && !locked ? (
320
+ <button type="button" className="login-mfa-quiet" onClick={() => {
321
+ setDevice(true); setPassword(""); setCode(""); setSetup(null); setError("");
322
+ }}>Enrol a new device</button>
323
+ ) : null}
324
+ {!device ? (
325
+ <>
326
+ <p className="login-mfa-help">Generating new recovery codes replaces the old codes and signs this account's other sessions out.</p>
327
+ {!locked ? (
328
+ <form className="login-form login-mfa-regenerate" onSubmit={generate}>
329
+ <label className="login-mfa-label" htmlFor="security-password">Account password</label>
330
+ <input id="security-password" className="login-input" type="password" autoComplete="current-password"
331
+ ref={passwordField} value={password} disabled={busy} required
332
+ aria-invalid={error ? true : undefined} aria-describedby="security-message"
333
+ onChange={(event) => { setPassword(event.target.value); setError(""); }} />
334
+ <button type="submit" className="login-submit" disabled={!password || busy}>
335
+ Generate new recovery codes
336
+ </button>
337
+ </form>
338
+ ) : null}
339
+ </>
340
  ) : null}
341
  </>
342
  ) : <p className="login-mfa-help">Sign in again to set up your authenticator app.</p>}
 
346
  Try again
347
  </button>
348
  )}
349
+ {(gate || device) && !locked ? (
350
+ <form className="login-form" onSubmit={enrol}>
351
+ {!gate ? (
352
+ <>
353
+ <p className="login-mfa-help">Confirming a new device replaces your old recovery codes and signs this account's other sessions out.</p>
354
+ <label className="login-mfa-label" htmlFor="security-device-password">Account password</label>
355
+ <input id="security-device-password" className="login-input" type="password" autoComplete="current-password"
356
+ ref={passwordField} value={password} disabled={preparing} required
357
+ aria-invalid={error ? true : undefined} aria-describedby="security-message"
358
+ onChange={(event) => { setPassword(event.target.value); setError(""); }} />
359
+ </>
360
+ ) : null}
361
+ {setup ? (
362
+ <>
363
+ {/* The in-app encoder adds no dependency or external QR service.
364
+ Keep manual setup available even when the QR cannot be drawn. */}
365
+ <p className="login-mfa-help">Type this setup code into any authenticator app.</p>
366
+ <span className="login-mfa-label">{setup.issuer} setup code</span>
367
+ <code className="login-mfa-secret">{setup.secret.match(/.{1,4}/g)?.join(" ")}</code>
368
+ <div className="security-qr-setup">
369
+ <SetupQr uri={setup.otpauthUri} />
370
+ <span className="login-mfa-label">Authenticator setup link</span>
371
+ <code className="login-mfa-uri">{setup.otpauthUri}</code>
372
+ </div>
373
+ <label className="login-mfa-label" htmlFor="security-enrol-code">First authenticator code</label>
374
+ <input id="security-enrol-code" className="login-input" type="text" inputMode="numeric"
375
+ autoComplete="one-time-code" maxLength={6} value={code} required
376
+ onChange={(event) => { setCode(event.target.value); setError(""); }}
377
+ aria-invalid={error ? true : undefined} aria-describedby="security-message" />
378
+ </>
379
+ ) : preparing ? <p className="login-mfa-help" role="status">Preparing your setup code…</p> : null}
380
+ <button type="submit" className="login-submit"
381
+ disabled={preparing || (!gate && !password) || (setup !== null && !code)}>
382
+ {preparing ? "Preparing setup…" : setup ? "Confirm setup" : gate ? "Try setup again" : "Set up new device"}
383
+ </button>
384
+ <button type="button" className="login-mfa-quiet" disabled={preparing} onClick={() => {
385
+ if (gate) gate.onBack();
386
+ else { setDevice(false); setPassword(""); setSetup(null); setCode(""); setError(""); }
387
+ }}>{gate ? "Back to sign in" : "Cancel"}</button>
388
+ </form>
389
+ ) : null}
390
  <p className="login-msg" id="security-message" role="status" aria-live="polite">{locked ? "" : error}</p>
391
 
392
  {/* R15/C12's explicit acknowledgement is the exception to ordinary
 
399
  <div className="login-form">
400
  {codes ? (
401
  <RecoveryCodes codes={codes} onError={setError} onSaved={() => {
402
+ if (gate) {
403
+ if (!enrolledUser) return;
404
+ gate.onEnrolled(enrolledUser, codes);
405
+ setEnrolledUser(null);
406
+ setCodes(null);
407
+ return;
408
+ }
409
  setCodes(null);
410
  setError("");
411
  // Count only, independently re-read after acknowledgement.
web/src/sheet/BindingEditor.tsx CHANGED
@@ -39,6 +39,7 @@
39
  import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
40
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
41
  import type { SurfaceScope } from "../customer-grid/apiBridge";
 
42
  import { FieldSelectButton } from "../customer-grid/FieldSelect";
43
  import { FieldTypeIcon } from "../customer-grid/icons";
44
  import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
@@ -60,10 +61,11 @@ import type { BindingAggregate } from "./types";
60
  import { bindingStepMode, bindingStepValues, seedBindingStep } from "./bindingRefs";
61
  import "../styles/wave57/binding-actions.css";
62
  import "../styles/wave58/sheet.css";
 
63
 
64
  const BINDING_SECTIONS = [
65
  { key: "data", label: "Data" },
66
- { key: "rows", label: "Rows" },
67
  { key: "period", label: "Period" },
68
  { key: "copied", label: "When copied" },
69
  ] as const;
@@ -134,6 +136,8 @@ const scopeOf = (database: string): SurfaceScope | null => {
134
  // `period: {unit: "month"|"quarter"|"year", start: "YYYY-MM", locked: boolean, ref?: A1}`. The
135
  // unit values are LOWERCASE on the wire even though the picker reads Month / Quarter / Year, and
136
  // `start` is a MONTH string for every unit.
 
 
137
  //
138
  // ⭐ `start` IS THE PERIOD'S FIRST MONTH, and that is the decision the ticket leaves implicit.
139
  // `unit` and `start` have to jointly name exactly one period, so Q3 2026 is `2026-07` and the year
@@ -148,6 +152,9 @@ export interface PeriodBinding {
148
  start: string;
149
  locked: boolean;
150
  ref?: string;
 
 
 
151
  window?: WindowSpec;
152
  }
153
 
@@ -200,6 +207,15 @@ export function shiftPeriodStart(unit: PeriodUnit, ym: string, steps: number): s
200
  return joinYm(Math.floor(total / 12), (total % 12) + 1);
201
  }
202
 
 
 
 
 
 
 
 
 
 
203
  // ⚠ W53-T16 (instruction 13) - `periodLabel` LIVED HERE and is gone with the summary block that
204
  // was its only caller. The period a person reads is now the Year / Month / Quarter pickers
205
  // themselves, which is where they set it, so a second rendering of the same value had nothing left
@@ -257,6 +273,13 @@ export function migratePeriod(raw: unknown): PeriodBinding | null {
257
  if (!/^\d{4}-\d{2}$/.test(stored) && !ref) return null;
258
  const start = normalizePeriodStart(unit, stored || todayYm());
259
  const locked = p.locked === true;
 
 
 
 
 
 
 
260
  return ref ? { unit, start, locked, ref } : { unit, start, locked };
261
  }
262
 
@@ -272,9 +295,11 @@ export interface OnDragBinding {
272
  down: { field: string } | "none";
273
  }
274
 
275
- /** Every permission-visible tenant field participates in the type-aware Step catalogue. */
 
 
276
  export function isDragDownField(f: Field): boolean {
277
- return Boolean(f.key) && !f.key.startsWith("__");
278
  }
279
 
280
  /** The saved `onDrag`, defaulted. `down` is carried as a field key, empty meaning nothing. */
@@ -720,6 +745,26 @@ export default function BindingEditor({
720
  migrated?.start ?? normalizePeriodStart("month", todayYm()),
721
  );
722
  const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
723
  // ⛔⛔ W57-T17 - THE DATABASE IS SEEDED AT MOUNT OUT OF A LIST THAT ARRIVES LATER, AND AN EMPTY
724
  // SEED NEVER HEALED. `databases` is fetched by `SheetPage` from `/api/v1/nav`; a panel opened
725
  // before that answer lands seeds `database` to `""`, and nothing re-seeds it. A `<select>` whose
@@ -1077,7 +1122,11 @@ export default function BindingEditor({
1077
  const period: Record<string, unknown> = {
1078
  unit, start, locked: chosenIsMetric ? locked : true,
1079
  };
1080
- if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
 
 
 
 
1081
  out.period = period;
1082
  }
1083
  }
@@ -1090,7 +1139,7 @@ export default function BindingEditor({
1090
  };
1091
  return out;
1092
  }, [database, sourceKind, metricKey, fn, field, scopeKind, viewId, views, tree, initial,
1093
- unit, start, locked, refOpen, periodRef, periodOn, periodMode, windowSpec,
1094
  across, downField, driverField, chosenIsMetric]);
1095
 
1096
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
@@ -1110,11 +1159,42 @@ export default function BindingEditor({
1110
  // ⭐ W54-T33 — `optionsResolved` FIRST, so Preview and Save are inert while the skeleton is up.
1111
  // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a
1112
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
1113
- const ready = optionsResolved && databases.some((d) => d.key === database)
1114
- && (chosenIsMetric ? Boolean(metricKey) && measures.some((m) => m.key === metricKey) && periodOn
1115
- : fn === "count" || numericFields.some((candidate) => candidate.key === field))
1116
- && (scopeKind === "filter" || Boolean(viewId))
1117
- && !savedDragDriverMissing;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1118
 
1119
  const { y: startYear, m: startMonth } = splitYm(start);
1120
  const thisYear = new Date().getFullYear();
@@ -1126,8 +1206,14 @@ export default function BindingEditor({
1126
  // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every
1127
  // period control below is rendered only while `periodOn`, so reaching one of them is already the
1128
  // decision the flag used to have to infer.
1129
- const setYear = (y: number) => setStart(normalizePeriodStart(unit, joinYm(y, startMonth)));
1130
- const setMonthOfYear = (m: number) => setStart(normalizePeriodStart(unit, joinYm(startYear, m)));
 
 
 
 
 
 
1131
 
1132
  return (
1133
  <section
@@ -1167,16 +1253,20 @@ export default function BindingEditor({
1167
  <>
1168
  <div className="sheet-binding-body">
1169
  <nav className="sheet-binding-rail" aria-label="Cell database sections">
1170
- {BINDING_SECTIONS.map(({ key, label }) => (
1171
  <button
1172
  key={key}
1173
  type="button"
1174
  className={"sheet-binding-rail-item" + (activeSection === key ? " is-active" : "")}
1175
  aria-current={activeSection === key ? "page" : undefined}
 
 
1176
  onClick={() => setActiveSection(key)}
1177
  >
1178
  {label}
1179
- {key === "period" && chosenIsMetric && !periodOn && (
 
 
1180
  <>{" "}<span className="sheet-binding-rail-required">Required</span></>
1181
  )}
1182
  </button>
@@ -1197,12 +1287,12 @@ export default function BindingEditor({
1197
  <label className="sheet-radio">
1198
  <input type="radio" name="sheet-binding-source" checked={sourceKind === "number"}
1199
  onChange={() => changeSource("number")} />
1200
- <span>Number</span>
1201
  </label>
1202
  <label className="sheet-radio">
1203
  <input type="radio" name="sheet-binding-source" checked={sourceKind === "column"}
1204
  onChange={() => changeSource("column")} />
1205
- <span>Column</span>
1206
  </label>
1207
  </fieldset>
1208
  <div className="sheet-field-row">
@@ -1218,8 +1308,11 @@ export default function BindingEditor({
1218
  key: m.key, label: m.label, type: "measure" as const,
1219
  }))}
1220
  />
1221
- {measures.length === 0 && <p className="sheet-notice">No Metrics are available on this database.</p>}
1222
- <button type="button" className="sheet-action" onClick={() => setActiveSection("period")}>
 
 
 
1223
  {periodOn ? "Edit Period / Lookback" : "Choose Period / Lookback"}
1224
  </button>
1225
  </div>
@@ -1445,6 +1538,7 @@ export default function BindingEditor({
1445
  aria-label="Period unit"
1446
  onChange={(e) => {
1447
  const next = e.target.value as PeriodUnit;
 
1448
  setUnit(next);
1449
  // Re-seat the start on the new unit's first month, or the pair stops naming one
1450
  // period: `2026-08` under `quarter` is not a quarter anybody can compile.
@@ -1494,6 +1588,44 @@ export default function BindingEditor({
1494
  )}
1495
  </div>
1496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1497
  {/* W56-T21 (owner instruction 13) - THE QUICK PICKS ARE GONE. Unit, year and
1498
  month-or-quarter already reach every period the This and Last buttons
1499
  could, so a second control for the same value was a second way to say one
@@ -1539,7 +1671,14 @@ export default function BindingEditor({
1539
  <button
1540
  type="button"
1541
  className="sheet-period-link"
1542
- onClick={() => setRefOpen(true)}
 
 
 
 
 
 
 
1543
  >
1544
  Use a cell
1545
  </button>
@@ -1604,31 +1743,43 @@ export default function BindingEditor({
1604
  absent control looks like a loading or configuration failure. */}
1605
  {chosenIsMetric && !periodOn && (
1606
  <p className="sheet-period-note">
1607
- Choose a Period or Lookback before saving this Number.
1608
  </p>
1609
  )}
1610
 
1611
- <label className="sheet-field">
1612
  <span>Step field</span>
1613
- <select value={downField} aria-label="Step field when copied"
1614
- disabled={!rowsResolved} onChange={(e) => chooseStepField(e.target.value)}>
1615
- <option value="">Keep this filter</option>
1616
- {filterClauseOffers.map(({ field: candidate, values }) => (
1617
- <option key={candidate.key} value={candidate.key} disabled={!values.length}>
1618
- {`Step ${candidate.label}${values.length ? "" : " (no values)"}`}
1619
- </option>
1620
- ))}
1621
- {savedDragDriverMissing && <option value={downField}>{`${downField} (unavailable)`}</option>}
1622
- </select>
1623
- </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1624
  {!rowsResolved && <p className="sheet-period-note" role="status">{rowsNotice || "Loading all field values…"}</p>}
1625
  {savedDragDriverMissing && <p className="sheet-notice" role="alert">The saved Step field is unavailable. Choose another field.</p>}
1626
  {localDriver && driverField && (
1627
  <div className="sheet-step-driver">
1628
  <span>{`${driverField.label}: ${driverValue}`}</span>
1629
- <button type="button" className="sheet-action" onClick={() => {
1630
- setActiveSection("rows"); setFilterPopupOpen(true);
1631
- }}>Edit condition</button>
1632
  </div>
1633
  )}
1634
  <p className="sheet-period-note">
 
39
  import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
40
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
41
  import type { SurfaceScope } from "../customer-grid/apiBridge";
42
+ import { dayText } from "../customer-grid/display";
43
  import { FieldSelectButton } from "../customer-grid/FieldSelect";
44
  import { FieldTypeIcon } from "../customer-grid/icons";
45
  import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
 
61
  import { bindingStepMode, bindingStepValues, seedBindingStep } from "./bindingRefs";
62
  import "../styles/wave57/binding-actions.css";
63
  import "../styles/wave58/sheet.css";
64
+ import "../styles/wave59/binding.css";
65
 
66
  const BINDING_SECTIONS = [
67
  { key: "data", label: "Data" },
68
+ { key: "rows", label: "Filter" },
69
  { key: "period", label: "Period" },
70
  { key: "copied", label: "When copied" },
71
  ] as const;
 
136
  // `period: {unit: "month"|"quarter"|"year", start: "YYYY-MM", locked: boolean, ref?: A1}`. The
137
  // unit values are LOWERCASE on the wire even though the picker reads Month / Quarter / Year, and
138
  // `start` is a MONTH string for every unit.
139
+ // A frozen period keeps that pair for returning to the calendar, and adds only
140
+ // `frozen: true, from: "YYYY-MM-DD", to: "YYYY-MM-DD"` in place of a cell reference.
141
  //
142
  // ⭐ `start` IS THE PERIOD'S FIRST MONTH, and that is the decision the ticket leaves implicit.
143
  // `unit` and `start` have to jointly name exactly one period, so Q3 2026 is `2026-07` and the year
 
152
  start: string;
153
  locked: boolean;
154
  ref?: string;
155
+ frozen?: true;
156
+ from?: string;
157
+ to?: string;
158
  window?: WindowSpec;
159
  }
160
 
 
207
  return joinYm(Math.floor(total / 12), (total % 12) + 1);
208
  }
209
 
210
+ /** The inclusive day range a calendar period covers. Mirrors
211
+ * `platform/modules/sheet.py::period_window`, whose `to` is the LAST DAY of the period. */
212
+ export function periodRange(unit: PeriodUnit, ym: string): { from: string; to: string } {
213
+ const start = normalizePeriodStart(unit, ym);
214
+ const last = new Date(`${shiftPeriodStart(unit, start, 1)}-01T00:00:00Z`);
215
+ last.setUTCDate(last.getUTCDate() - 1);
216
+ return { from: `${start}-01`, to: last.toISOString().slice(0, 10) };
217
+ }
218
+
219
  // ⚠ W53-T16 (instruction 13) - `periodLabel` LIVED HERE and is gone with the summary block that
220
  // was its only caller. The period a person reads is now the Year / Month / Quarter pickers
221
  // themselves, which is where they set it, so a second rendering of the same value had nothing left
 
273
  if (!/^\d{4}-\d{2}$/.test(stored) && !ref) return null;
274
  const start = normalizePeriodStart(unit, stored || todayYm());
275
  const locked = p.locked === true;
276
+ if (p.frozen === true) {
277
+ return {
278
+ unit, start, locked, frozen: true,
279
+ from: typeof p.from === "string" ? p.from : "",
280
+ to: typeof p.to === "string" ? p.to : "",
281
+ };
282
+ }
283
  return ref ? { unit, start, locked, ref } : { unit, start, locked };
284
  }
285
 
 
295
  down: { field: string } | "none";
296
  }
297
 
298
+ /** A copy step walks a column's stored values. Measure-backed and Metric columns are computed
299
+ * numbers with no stored values to walk, so offering one promises a step `dragBoundCell`
300
+ * cannot perform. */
301
  export function isDragDownField(f: Field): boolean {
302
+ return Boolean(f.key) && !f.key.startsWith("__") && !f.measure && f.type !== "metric";
303
  }
304
 
305
  /** The saved `onDrag`, defaulted. `down` is carried as a field key, empty meaning nothing. */
 
745
  migrated?.start ?? normalizePeriodStart("month", todayYm()),
746
  );
747
  const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false);
748
+ // An absent flag is rolling, including every binding saved before frozen dates existed.
749
+ const [frozen, setFrozen] = useState<boolean>(Boolean(migrated?.frozen));
750
+ const [frozenFrom, setFrozenFrom] = useState<string>(
751
+ () => migrated?.from ?? periodRange(unit, start).from,
752
+ );
753
+ const [frozenTo, setFrozenTo] = useState<string>(
754
+ () => migrated?.to ?? periodRange(unit, start).to,
755
+ );
756
+ const range = frozen ? { from: frozenFrom, to: frozenTo } : periodRange(unit, start);
757
+ const resumeRollingPeriod = () => {
758
+ setFrozen(false);
759
+ setFrozenFrom("");
760
+ setFrozenTo("");
761
+ };
762
+ const editPeriodDate = (key: "from" | "to", value: string) => {
763
+ // Capture the other displayed endpoint too: the dropdowns may have moved since mount.
764
+ setFrozenFrom(key === "from" ? value : range.from);
765
+ setFrozenTo(key === "to" ? value : range.to);
766
+ setFrozen(true);
767
+ };
768
  // ⛔⛔ W57-T17 - THE DATABASE IS SEEDED AT MOUNT OUT OF A LIST THAT ARRIVES LATER, AND AN EMPTY
769
  // SEED NEVER HEALED. `databases` is fetched by `SheetPage` from `/api/v1/nav`; a panel opened
770
  // before that answer lands seeds `database` to `""`, and nothing re-seeds it. A `<select>` whose
 
1122
  const period: Record<string, unknown> = {
1123
  unit, start, locked: chosenIsMetric ? locked : true,
1124
  };
1125
+ if (frozen) {
1126
+ period.frozen = true;
1127
+ period.from = frozenFrom;
1128
+ period.to = frozenTo;
1129
+ } else if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
1130
  out.period = period;
1131
  }
1132
  }
 
1139
  };
1140
  return out;
1141
  }, [database, sourceKind, metricKey, fn, field, scopeKind, viewId, views, tree, initial,
1142
+ unit, start, locked, frozen, frozenFrom, frozenTo, refOpen, periodRef, periodOn, periodMode, windowSpec,
1143
  across, downField, driverField, chosenIsMetric]);
1144
 
1145
  // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
 
1159
  // ⭐ W54-T33 — `optionsResolved` FIRST, so Preview and Save are inert while the skeleton is up.
1160
  // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a
1161
  // Save taken then would write back a binding assembled from a list nobody had seen yet.
1162
+ // W59-T11: the rail and Save share these terms; only Metrics require a period.
1163
+ const dataComplete = databases.some((d) => d.key === database)
1164
+ && (chosenIsMetric ? Boolean(metricKey) && measures.some((m) => m.key === metricKey)
1165
+ : fn === "count" || numericFields.some((candidate) => candidate.key === field));
1166
+ const filterComplete = scopeKind === "filter" || Boolean(viewId);
1167
+ const frozenRangeComplete = !frozen || Boolean(range.from && range.to && range.from <= range.to);
1168
+ const periodComplete = (!chosenIsMetric || periodOn)
1169
+ && (!periodOn || periodMode !== "calendar" || frozenRangeComplete);
1170
+ const copiedComplete = !savedDragDriverMissing;
1171
+ const ready = optionsResolved && dataComplete && filterComplete && periodComplete && copiedComplete;
1172
+
1173
+ const sectionComplete = {
1174
+ data: dataComplete, rows: filterComplete, period: periodComplete, copied: copiedComplete,
1175
+ };
1176
+ const sectionGates = BINDING_SECTIONS.map((section, index) => {
1177
+ const blocker = BINDING_SECTIONS.slice(0, index).find(({ key }) => !sectionComplete[key]);
1178
+ return {
1179
+ ...section,
1180
+ reachable: !blocker,
1181
+ blockedHint: blocker?.key === "data" ? "Pick a source"
1182
+ : blocker?.key === "rows" ? "Pick rows"
1183
+ : blocker?.key === "period" ? "Set a period" : undefined,
1184
+ };
1185
+ });
1186
+ const periodReachable = sectionGates.some(({ key, reachable }) => key === "period" && reachable);
1187
+ const lastReachableIndex = sectionGates.reduce(
1188
+ (last, section, index) => section.reachable ? index : last, 0,
1189
+ );
1190
+
1191
+ useEffect(() => {
1192
+ setActiveSection((current) => {
1193
+ const currentIndex = BINDING_SECTIONS.findIndex(({ key }) => key === current);
1194
+ // Re-check the current selection so a backward click cannot be advanced by this effect.
1195
+ return currentIndex > lastReachableIndex ? BINDING_SECTIONS[lastReachableIndex].key : current;
1196
+ });
1197
+ }, [activeSection, lastReachableIndex]);
1198
 
1199
  const { y: startYear, m: startMonth } = splitYm(start);
1200
  const thisYear = new Date().getFullYear();
 
1206
  // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every
1207
  // period control below is rendered only while `periodOn`, so reaching one of them is already the
1208
  // decision the flag used to have to infer.
1209
+ const setYear = (y: number) => {
1210
+ resumeRollingPeriod();
1211
+ setStart(normalizePeriodStart(unit, joinYm(y, startMonth)));
1212
+ };
1213
+ const setMonthOfYear = (m: number) => {
1214
+ resumeRollingPeriod();
1215
+ setStart(normalizePeriodStart(unit, joinYm(startYear, m)));
1216
+ };
1217
 
1218
  return (
1219
  <section
 
1253
  <>
1254
  <div className="sheet-binding-body">
1255
  <nav className="sheet-binding-rail" aria-label="Cell database sections">
1256
+ {sectionGates.map(({ key, label, reachable, blockedHint }) => (
1257
  <button
1258
  key={key}
1259
  type="button"
1260
  className={"sheet-binding-rail-item" + (activeSection === key ? " is-active" : "")}
1261
  aria-current={activeSection === key ? "page" : undefined}
1262
+ disabled={!reachable}
1263
+ title={blockedHint}
1264
  onClick={() => setActiveSection(key)}
1265
  >
1266
  {label}
1267
+ {!reachable ? (
1268
+ <span className="sheet-binding-rail-hint">{blockedHint}</span>
1269
+ ) : key === "period" && chosenIsMetric && !periodOn && (
1270
  <>{" "}<span className="sheet-binding-rail-required">Required</span></>
1271
  )}
1272
  </button>
 
1287
  <label className="sheet-radio">
1288
  <input type="radio" name="sheet-binding-source" checked={sourceKind === "number"}
1289
  onChange={() => changeSource("number")} />
1290
+ <span>Metric</span>
1291
  </label>
1292
  <label className="sheet-radio">
1293
  <input type="radio" name="sheet-binding-source" checked={sourceKind === "column"}
1294
  onChange={() => changeSource("column")} />
1295
+ <span>Field</span>
1296
  </label>
1297
  </fieldset>
1298
  <div className="sheet-field-row">
 
1308
  key: m.key, label: m.label, type: "measure" as const,
1309
  }))}
1310
  />
1311
+ <p className="sheet-notice">{measures.length === 0
1312
+ ? "No Metrics are available here. Choose another database."
1313
+ : "Binding adds a Metric column to this database if one is not already there."}</p>
1314
+ <button type="button" className="sheet-action" disabled={!periodReachable}
1315
+ onClick={() => setActiveSection("period")}>
1316
  {periodOn ? "Edit Period / Lookback" : "Choose Period / Lookback"}
1317
  </button>
1318
  </div>
 
1538
  aria-label="Period unit"
1539
  onChange={(e) => {
1540
  const next = e.target.value as PeriodUnit;
1541
+ resumeRollingPeriod();
1542
  setUnit(next);
1543
  // Re-seat the start on the new unit's first month, or the pair stops naming one
1544
  // period: `2026-08` under `quarter` is not a quarter anybody can compile.
 
1588
  )}
1589
  </div>
1590
 
1591
+ <div className="sheet-field-row sheet-period-dates">
1592
+ <label className="sheet-field">
1593
+ <span>Starts</span>
1594
+ <input
1595
+ className="cg-input cg-cond-win-date"
1596
+ type="date"
1597
+ aria-label="Period start"
1598
+ value={range.from}
1599
+ onChange={(e) => editPeriodDate("from", e.target.value)}
1600
+ />
1601
+ </label>
1602
+ <label className="sheet-field">
1603
+ <span>Ends</span>
1604
+ <input
1605
+ className="cg-input cg-cond-win-date"
1606
+ type="date"
1607
+ aria-label="Period end"
1608
+ value={range.to}
1609
+ onChange={(e) => editPeriodDate("to", e.target.value)}
1610
+ />
1611
+ </label>
1612
+ </div>
1613
+ <p className="sheet-period-note" aria-live="polite">
1614
+ {dayText(range.from)} to {dayText(range.to)}
1615
+ </p>
1616
+ {frozen && (
1617
+ <>
1618
+ <p className="sheet-period-note">Frozen to these dates until you choose a period.</p>
1619
+ <button
1620
+ type="button"
1621
+ className="sheet-period-link"
1622
+ onClick={resumeRollingPeriod}
1623
+ >
1624
+ Return to rolling period
1625
+ </button>
1626
+ </>
1627
+ )}
1628
+
1629
  {/* W56-T21 (owner instruction 13) - THE QUICK PICKS ARE GONE. Unit, year and
1630
  month-or-quarter already reach every period the This and Last buttons
1631
  could, so a second control for the same value was a second way to say one
 
1671
  <button
1672
  type="button"
1673
  className="sheet-period-link"
1674
+ onClick={() => {
1675
+ // A cell SUPPLIES the period, so it cannot also be frozen to two
1676
+ // literal dates. Returning to rolling here is the same rule the
1677
+ // unit, year and month pickers follow, and it keeps the payload's
1678
+ // `frozen`-wins branch from silently dropping a typed reference.
1679
+ resumeRollingPeriod();
1680
+ setRefOpen(true);
1681
+ }}
1682
  >
1683
  Use a cell
1684
  </button>
 
1743
  absent control looks like a loading or configuration failure. */}
1744
  {chosenIsMetric && !periodOn && (
1745
  <p className="sheet-period-note">
1746
+ Choose a Period or Lookback before saving this Metric.
1747
  </p>
1748
  )}
1749
 
1750
+ <div className="sheet-field sheet-field--pick">
1751
  <span>Step field</span>
1752
+ <FieldSelectButton
1753
+ ariaLabel="Step field when copied"
1754
+ placeholder="Keep this filter"
1755
+ value={downField}
1756
+ onChange={chooseStepField}
1757
+ disabled={!rowsResolved}
1758
+ searchable
1759
+ searchPlaceholder="Find a step field…"
1760
+ emptyMessage="No step fields available."
1761
+ fields={[
1762
+ { key: "", label: "Keep this filter" },
1763
+ ...filterClauseOffers.map(({ field: candidate, values }) => ({
1764
+ key: candidate.key,
1765
+ label: `Step ${candidate.label}`,
1766
+ type: candidate.type,
1767
+ disabled: !values.length,
1768
+ hint: values.length ? undefined : "No values",
1769
+ })),
1770
+ ...(savedDragDriverMissing ? [{
1771
+ key: downField,
1772
+ label: `${downField} (unavailable)`,
1773
+ disabled: true,
1774
+ }] : []),
1775
+ ]}
1776
+ />
1777
+ </div>
1778
  {!rowsResolved && <p className="sheet-period-note" role="status">{rowsNotice || "Loading all field values…"}</p>}
1779
  {savedDragDriverMissing && <p className="sheet-notice" role="alert">The saved Step field is unavailable. Choose another field.</p>}
1780
  {localDriver && driverField && (
1781
  <div className="sheet-step-driver">
1782
  <span>{`${driverField.label}: ${driverValue}`}</span>
 
 
 
1783
  </div>
1784
  )}
1785
  <p className="sheet-period-note">
web/src/sheet/ChartDialog.tsx CHANGED
@@ -52,7 +52,9 @@ import { parseRange } from "./rules";
52
  import type { Cell, SheetChartRange, SheetChartSpec, SheetTab, SheetChartPresentation, SheetChartColor } from "./types";
53
  import { defaultChartPresentation } from "./types";
54
  import { chartDataForRange, DrawnChart } from "./SheetChart";
 
55
  import "../styles/wave58/sheet.css";
 
56
 
57
  /** The page owns the atomic workbook write; isolated legacy mounts retain their old callback. */
58
  export const ChartWorkbookContext = createContext<{
@@ -71,10 +73,9 @@ export function parseChartRanges(text: string): SheetChartRange[] | null {
71
  export type ChartRange = SheetChartRange;
72
 
73
  /**
74
- * ⭐ THE EIGHT KINDS THE DOCUMENT CARRIES. `types.ts::SheetChartSpec` declares all eight and
75
- * `platform/core/sheets.py::SHEET_CHART_KINDS` keeps all eight since W54-T09, so every one of them
76
- * survives a save and a reload. Four are DRAWN today (`types.ts::SHEET_CHART_DRAWN_KINDS`) and the
77
- * renderer widens next, so the stored kind is the person's real choice either way.
78
  */
79
  export const CHART_KINDS: { kind: SheetChartSpec["kind"]; label: string }[] = [
80
  { kind: "bar", label: "Bar" },
@@ -93,6 +94,116 @@ export const CHART_KINDS: { kind: SheetChartSpec["kind"]; label: string }[] = [
93
  { kind: "stock", label: "Stock" }, { kind: "gantt", label: "Gantt" },
94
  ];
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  /**
97
  * ⭐ THE AGGREGATE VOCABULARY, COPIED FROM `BindingEditor.tsx::AGGREGATES` NAME FOR NAME. The
98
  * server normalizes `aggregate.fn` against this same set, so a name invented here would bind a
@@ -270,6 +381,8 @@ export interface ChartDialogProps {
270
  selection: ChartRange | null;
271
  /** Present when this is the same dialog reopened for an existing chart. */
272
  chart?: SheetChartSpec;
 
 
273
  /** Escape, the close mark, or Cancel. All converge on the same event. */
274
  onClose: () => void;
275
  /**
@@ -295,6 +408,7 @@ export interface ChartDialogProps {
295
  export default function ChartDialog({
296
  selection,
297
  chart,
 
298
  onClose,
299
  onCreate,
300
  onUpdate,
@@ -306,6 +420,14 @@ export default function ChartDialog({
306
  const titleId = useId();
307
  const editing = chart !== undefined;
308
  const seedRange = chart?.source?.ranges[0] ?? chart?.range ?? selection ?? { col0: 0, row0: 0, col1: 0, row1: 0 };
 
 
 
 
 
 
 
 
309
 
310
  const [presentation, setPresentation] = useState<SheetChartPresentation>(() => ({...defaultChartPresentation(),...chart?.presentation}));
311
  const [sourceSheetId, setSourceSheetId] = useState(chart?.source?.sheetId ?? workbook?.activeSheetId ?? "");
@@ -314,13 +436,14 @@ export default function ChartDialog({
314
  const [anchor, setAnchor] = useState(() => addressOf(chart?.geometry?.col ?? 0, chart?.geometry?.row ?? 0));
315
  const [chartWidth, setChartWidth] = useState(String(chart?.geometry?.width ?? 640));
316
  const [chartHeight, setChartHeight] = useState(String(chart?.geometry?.height ?? 360));
317
- const [section, setSection] = useState("Data");
 
318
  const [bounds, setBounds] = useState<Record<string,string>>(() => Object.fromEntries(["yMin","yMax","yMajor","yMinor"].map(k=>[k,String(chart?.presentation?.[k as "yMin"]??"")])));
319
  const setOption = <K extends keyof SheetChartPresentation>(key: K, value: SheetChartPresentation[K]) =>
320
  setPresentation(current => ({...current,[key]:value}));
321
 
322
  const [tab, setTab] = useState<SourceTab>("range");
323
- const [kind, setKind] = useState<SheetChartSpec["kind"]>(chart?.kind ?? "bar");
324
  const [rangeDraft, setRangeDraft] = useState(() => (chart?.source?.ranges ?? [seedRange]).map(chartRangeText).join(", "));
325
  const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
326
  const [loading, setLoading] = useState(!editing);
@@ -379,7 +502,26 @@ export default function ChartDialog({
379
  const range = ranges?.[0] ?? null;
380
  const location = parseRange(anchor);
381
  const sourceCells = workbook?.sheets.find(s => s.id === sourceSheetId)?.cells ?? {};
382
- const model = useMemo(() => chartDataForRange(sourceCells, range ?? seedRange, presentation, ranges ?? [seedRange], kind), [sourceCells,range,presentation,ranges,kind]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  const offeredSeries = useMemo(() => chartDataForRange(sourceCells, range ?? seedRange, {...presentation,series:[]}, ranges ?? [seedRange], kind).series, [sourceCells,range,presentation,ranges,kind]);
384
  const configuredSeries = (presentation.series ?? []).flatMap(setting => {
385
  const offered = offeredSeries.find(s => s.sourceKey === setting.key || s.y === setting.key);
@@ -406,7 +548,7 @@ export default function ChartDialog({
406
 
407
  const wantsField = fn !== "count";
408
  const ready = Boolean(validGeometry) && !boundsError && !newNameError && (tab === "range"
409
- ? range !== null && !(["stock", "gantt"].includes(kind) && model.error)
410
  : Boolean(database) && (!wantsField || field.trim().length > 0) && Number(periods)>=MIN_PERIODS && Number(periods)<=MAX_PERIODS);
411
 
412
  const create = async () => {
@@ -457,6 +599,46 @@ export default function ChartDialog({
457
  );
458
 
459
  const kindPicker = <label className="sheet-chart-setting">Chart type<select aria-label="Chart type" value={kind} onChange={event=>setKind(event.target.value as SheetChartSpec["kind"])}>{CHART_KINDS.map(entry=><option key={entry.kind} value={entry.kind}>{entry.label}</option>)}</select></label>;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
  const select = <K extends keyof SheetChartPresentation>(label: string,key:K,choices: readonly (readonly [string,string])[]) =>
461
  <label className="sheet-chart-setting">{label}<select aria-label={label} value={String(presentation[key]??(key==="ganttMode"?"duration":""))} onChange={e=>setOption(key,e.target.value as SheetChartPresentation[K])}>{choices.map(([value,label])=><option key={value} value={value}>{label}</option>)}</select></label>;
462
  const text = (label: string,key:"title"|"xTitle"|"yTitle"|"categoryTitle") =>
@@ -470,14 +652,18 @@ export default function ChartDialog({
470
  setBounds({yMin:"",yMax:"",yMajor:"",yMinor:""});
471
  };
472
  const settingsPanel = <div className="sheet-chart-settings">
473
- {section==="Chart"?<>{kindPicker}
474
- {kind==="stock"?<p className="sheet-chart-caption">Select a date or label column, then High, Low, Close. Open may precede High.</p>:null}
 
 
475
  {kind==="gantt"?<>{select("Task values","ganttMode",[["duration","Start and duration"],["end","Start and end"]])}<p className="sheet-chart-caption">Select task names, then start and duration or end. Dates use durations in days.</p></>:null}
476
  {select("Layout","layout",[["standard","Standard"],["compact","Compact"],["labels","Labels"]])}
477
  {select("Colors","palette",[["purple","Purple"],["categorical","Categorical"],["blue","Blue"]])}
478
  {select("Style","style",[["filled","Filled"],["outline","Outline"],["soft","Soft"]])}
479
  {kind==="histogram"?<label className="sheet-chart-setting">Bins<input aria-label="Bins" type="number" min={1} max={50} value={presentation.bins??10} onChange={e=>setOption("bins",Math.max(1,Math.min(50,Number(e.target.value)||1)))}/></label>:null}
480
  <button type="button" className="sheet-chart-quiet" onClick={resetFormatting}>Reset formatting</button>
 
 
481
  </>:null}
482
  {section==="Text"?<>{text("Chart title","title")}{text("X axis title","xTitle")}{text("Y axis title","yTitle")}{text("Category name","categoryTitle")}
483
  {toggle("Show legend","showLegend")}{toggle("Show axis titles","showAxisTitles")}{toggle("Show data labels","showDataLabels")}
@@ -515,7 +701,7 @@ export default function ChartDialog({
515
  // `sheet-chart-dialog` carries no rule of its own and is not meant to: it is the name a
516
  // gate, a screenshot or a person in the inspector can point at. The paint is `.lp-dialog`.
517
  className="lp-dialog sheet-chart-dialog"
518
- style={{ width: "min(680px, calc(100vw - 32px))" }}
519
  role="dialog"
520
  aria-modal="true"
521
  aria-labelledby={titleId}
@@ -562,13 +748,16 @@ export default function ChartDialog({
562
  ) : null}
563
 
564
  <div className="sheet-chart-section-tabs" role="tablist" aria-label="Chart settings sections">
565
- {["Data","Chart","Text","Series","Axes","Location"].map(name=><button key={name} type="button" role="tab" aria-selected={section===name} className="sheet-chart-quiet" onClick={()=>setSection(name)}>{name}</button>)}
 
 
 
566
  </div>
567
  <div
568
  className="sheet-chart-panel"
569
  id={`${titleId}-panel`}
570
  role="tabpanel"
571
- aria-labelledby={editing ? titleId : `${titleId}-tab-${tab}`}
572
  >
573
  {section!=="Data" ? settingsPanel : tab === "range" ? (
574
  <>
@@ -672,8 +861,8 @@ export default function ChartDialog({
672
  {boundsError?<p role="alert" className="sheet-chart-caption">{boundsError}</p>:null}
673
  {!validGeometry?<p role="alert" className="sheet-chart-caption">Choose one anchor cell, width 320 to 2400 and height 240 to 1600.</p>:null}
674
  {newNameError?<p role="alert" className="sheet-chart-caption">Choose a unique, valid sheet name.</p>:null}
675
- {workbook&&tab==="range"?<details className="sheet-chart-preview"><summary>Preview</summary>
676
- {model.error?<p role="status">{model.error}</p>:<DrawnChart {...model} kind={kind} presentation={presentation} width={600} height={280}/>}
677
  </details>:null}
678
  </div>
679
 
@@ -699,7 +888,7 @@ export default function ChartDialog({
699
  disabled={!ready}
700
  onClick={create}
701
  >
702
- {editing ? "Save chart" : "Insert chart"}
703
  </button>
704
  </div>
705
  </div>
 
52
  import type { Cell, SheetChartRange, SheetChartSpec, SheetTab, SheetChartPresentation, SheetChartColor } from "./types";
53
  import { defaultChartPresentation } from "./types";
54
  import { chartDataForRange, DrawnChart } from "./SheetChart";
55
+ import type { SheetChartData } from "./SheetChart";
56
  import "../styles/wave58/sheet.css";
57
+ import "../styles/wave59/chart-dialog.css";
58
 
59
  /** The page owns the atomic workbook write; isolated legacy mounts retain their old callback. */
60
  export const ChartWorkbookContext = createContext<{
 
73
  export type ChartRange = SheetChartRange;
74
 
75
  /**
76
+ * ⭐ ALL NINETEEN KINDS ARE DRAWN by `SheetChart.tsx::DrawnChart` and survive a save through
77
+ * `platform/core/sheets.py::SHEET_CHART_KINDS`. Availability for a particular selection depends
78
+ * on its model and the renderer's data requirements, not the unused drawn-kinds export.
 
79
  */
80
  export const CHART_KINDS: { kind: SheetChartSpec["kind"]; label: string }[] = [
81
  { kind: "bar", label: "Bar" },
 
94
  { kind: "stock", label: "Stock" }, { kind: "gantt", label: "Gantt" },
95
  ];
96
 
97
+ type ChartKind = SheetChartSpec["kind"];
98
+ export interface ChartCandidate { kind: ChartKind; model: SheetChartData }
99
+
100
+ const CHART_DESCRIPTIONS: Record<ChartKind, string> = {
101
+ bar: "Compare values across categories with long labels.",
102
+ column: "Compare values across a few categories.",
103
+ line: "Follow changes across an ordered sequence.",
104
+ area: "Show how values build and change over a sequence.",
105
+ pie: "Compare a few categories as shares of a total.",
106
+ donut: "Show how a few categories contribute to a total.",
107
+ scatter: "Explore the relationship between two numeric measures.",
108
+ combo: "Compare series with columns and a line on one scale.",
109
+ waterfall: "Show how successive changes build a running total.",
110
+ histogram: "See how numeric values fall into intervals.",
111
+ bubble: "Compare numeric relationships with size as another measure.",
112
+ bullet: "Compare a value with a target on the same scale.",
113
+ funnel: "Compare values across successive stages.",
114
+ gauge: "Show one value within a bounded scale.",
115
+ polar: "Compare category magnitudes around a circle.",
116
+ radar: "Compare series profiles across the same categories.",
117
+ treemap: "Compare category shares with proportional areas.",
118
+ stock: "Compare high, low and closing values over time.",
119
+ gantt: "Compare task start times and durations.",
120
+ };
121
+
122
+ /**
123
+ * ⛔⛔ THE RENDERER'S OWN REFUSALS, MIRRORED IN ITS OWN ORDER, so the gallery never offers a kind
124
+ * whose preview would be a refusal box. Every arm below is a line of `SheetChart.tsx::DrawnChart`:
125
+ * the shared preamble at 285-293, then gauge 360, radar 372, bullet 401 and the XY family 414-416.
126
+ * ⚠ THIS IS A HAND COPY AND HAND COPIES DRIFT. What keeps it honest is the `all charts ... explain
127
+ * renderer refusals` leg in `verify_charts.py`, which renders all nineteen kinds over several
128
+ * fixtures and asserts this function agrees with the rendered `role="status"` exactly. If you add a
129
+ * refusal to the renderer, that leg reds here until you add it too [W59-T07].
130
+ */
131
+ export function chartPreviewError(kind: ChartKind, model: SheetChartData): string | undefined {
132
+ if (model.error) return model.error;
133
+ if (!model.series.length || !model.rows.length) return "This range has no numeric values to chart.";
134
+ const numeric = (row: SheetChartData["rows"][number], key: string) => {
135
+ const value = (row as unknown as Record<string, unknown>)[key];
136
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
137
+ };
138
+ // `all` is every series' numbers; `valid` is the FIRST series' alone, exactly as the renderer
139
+ // splits them, because gauge counts one series and the share families count the whole selection.
140
+ const all = model.series.flatMap(series => model.rows
141
+ .map(row => numeric(row, series.y)).filter((value): value is number => value !== null));
142
+ const valid = model.rows.map(row => numeric(row, model.series[0].y))
143
+ .filter((value): value is number => value !== null);
144
+ const oneSeries = ["pie", "donut", "funnel", "treemap", "polar", "waterfall", "histogram", "gauge"];
145
+ const nonNegative = ["pie", "donut", "funnel", "treemap", "polar", "radar"];
146
+ const positiveTotal = ["pie", "donut", "funnel", "treemap", "polar"];
147
+ if (oneSeries.includes(kind) && model.series.length !== 1)
148
+ return "Select one visible series for this chart type.";
149
+ if (nonNegative.includes(kind) && all.some(value => value < 0))
150
+ return "This chart type needs nonnegative values.";
151
+ if (positiveTotal.includes(kind) && valid.reduce((sum, value) => sum + value, 0) <= 0)
152
+ return "This chart type needs a positive total.";
153
+ if (kind === "gauge" && valid.length !== 1) return "A gauge needs one numeric value.";
154
+ if (kind === "radar" && model.rows.length < 3) return "A radar chart needs at least three categories.";
155
+ if (kind === "bullet" && model.series.length < 2) return "A bullet chart needs actual and target series.";
156
+ if (kind === "bubble" && model.series.length < 2) return "A bubble chart needs X, Y and size columns.";
157
+ if (kind === "bubble" && model.rows.some(row => (numeric(row, model.series[1].y) ?? 0) < 0))
158
+ return "Bubble sizes must be nonnegative.";
159
+ if ((kind === "scatter" || kind === "bubble") && model.rows.some(row => numeric(row, "category") === null))
160
+ return "The X column must contain numeric values.";
161
+ return undefined;
162
+ }
163
+
164
+ /** Pure data in, ranked kinds out; never recommend a model the preview cannot draw. */
165
+ export function recommendChartKinds(candidates: readonly ChartCandidate[]): ChartKind[] {
166
+ const drawable = candidates.filter(({ kind, model }) => !chartPreviewError(kind, model));
167
+ // Prefer the selection's text categories over an XY reinterpretation of its value columns.
168
+ const categories = candidates.find(candidate => candidate.kind === "column")?.model.rows;
169
+ const numericCategories = !categories || categories.every(row => {
170
+ const category = String(row.category ?? "");
171
+ return /^[A-Z]+[1-9]\d*$/.test(category) || (category.trim() !== "" && Number.isFinite(Number(category)));
172
+ });
173
+ const score = ({ kind, model }: ChartCandidate): number => {
174
+ const many = model.rows.length > 8;
175
+ const multiple = model.series.length > 1;
176
+ if (numericCategories && model.fields[0]?.type === "int") {
177
+ if (kind === "scatter") return 120;
178
+ if (kind === "bubble") return multiple ? 115 : 85;
179
+ }
180
+ if (kind === "stock" && ["high", "low", "close"].every(role => model.series.some(series => series.label.toLowerCase().includes(role)))) return 110;
181
+ if (kind === "gantt" && model.series.some(series => /start|duration|end|days/i.test(series.label))) return 110;
182
+ const preference: Partial<Record<ChartKind, number>> = many
183
+ ? { line: 100, area: 90, bar: 80, column: 70, combo: multiple ? 85 : 30, histogram: 60 }
184
+ : multiple
185
+ ? { column: 100, line: 90, area: 80, combo: 70, bar: 60, radar: 50 }
186
+ : { column: 100, bar: 90, pie: 80, donut: 70, line: 60, area: 50 };
187
+ return preference[kind] ?? 10;
188
+ };
189
+ return drawable.slice().sort((a, b) => score(b) - score(a)).slice(0, 6).map(candidate => candidate.kind);
190
+ }
191
+
192
+ /** Each kind interprets the actual source independently, including fixed-role and XY families. */
193
+ export function chartCandidatesForRange(cells: Record<string, Cell>, range: ChartRange,
194
+ presentation: SheetChartPresentation, ranges: ChartRange[] = [range]): ChartCandidate[] {
195
+ const invalidBounds = [presentation.yMin, presentation.yMax, presentation.yMajor, presentation.yMinor]
196
+ .some(value => value !== undefined && !Number.isFinite(value))
197
+ || [presentation.yMajor, presentation.yMinor].some(value => value !== undefined && value <= 0);
198
+ const boundsError = invalidBounds ? "Enter finite bounds and positive units."
199
+ : presentation.yMin !== undefined && presentation.yMax !== undefined && presentation.yMin >= presentation.yMax
200
+ ? "The Y maximum must exceed the minimum." : undefined;
201
+ return CHART_KINDS.map(({ kind }) => {
202
+ const model = chartDataForRange(cells, range, presentation, ranges, kind);
203
+ return { kind, model: boundsError ? { ...model, error: boundsError } : model };
204
+ });
205
+ }
206
+
207
  /**
208
  * ⭐ THE AGGREGATE VOCABULARY, COPIED FROM `BindingEditor.tsx::AGGREGATES` NAME FOR NAME. The
209
  * server normalizes `aggregate.fn` against this same set, so a name invented here would bind a
 
381
  selection: ChartRange | null;
382
  /** Present when this is the same dialog reopened for an existing chart. */
383
  chart?: SheetChartSpec;
384
+ /** A ribbon chart-kind shortcut opens the chart section on this kind. */
385
+ initialKind?: SheetChartSpec["kind"];
386
  /** Escape, the close mark, or Cancel. All converge on the same event. */
387
  onClose: () => void;
388
  /**
 
408
  export default function ChartDialog({
409
  selection,
410
  chart,
411
+ initialKind,
412
  onClose,
413
  onCreate,
414
  onUpdate,
 
420
  const titleId = useId();
421
  const editing = chart !== undefined;
422
  const seedRange = chart?.source?.ranges[0] ?? chart?.range ?? selection ?? { col0: 0, row0: 0, col1: 0, row1: 0 };
423
+ const [opening] = useState(() => {
424
+ if (initialKind) return { section: "Chart", kind: initialKind };
425
+ const fallback = { section: "Data", kind: chart?.kind ?? "bar" as ChartKind };
426
+ if (editing || !selection || (selection.col0 === selection.col1 && selection.row0 === selection.row1)) return fallback;
427
+ const cells = workbook?.sheets.find(sheet => sheet.id === workbook.activeSheetId)?.cells ?? {};
428
+ const recommended = recommendChartKinds(chartCandidatesForRange(cells, selection, defaultChartPresentation()));
429
+ return recommended.length ? { section: "Chart", kind: recommended[0] } : fallback;
430
+ });
431
 
432
  const [presentation, setPresentation] = useState<SheetChartPresentation>(() => ({...defaultChartPresentation(),...chart?.presentation}));
433
  const [sourceSheetId, setSourceSheetId] = useState(chart?.source?.sheetId ?? workbook?.activeSheetId ?? "");
 
436
  const [anchor, setAnchor] = useState(() => addressOf(chart?.geometry?.col ?? 0, chart?.geometry?.row ?? 0));
437
  const [chartWidth, setChartWidth] = useState(String(chart?.geometry?.width ?? 640));
438
  const [chartHeight, setChartHeight] = useState(String(chart?.geometry?.height ?? 360));
439
+ const [section, setSection] = useState(opening.section);
440
+ const [galleryTab, setGalleryTab] = useState<"recommended" | "all">(editing || initialKind ? "all" : "recommended");
441
  const [bounds, setBounds] = useState<Record<string,string>>(() => Object.fromEntries(["yMin","yMax","yMajor","yMinor"].map(k=>[k,String(chart?.presentation?.[k as "yMin"]??"")])));
442
  const setOption = <K extends keyof SheetChartPresentation>(key: K, value: SheetChartPresentation[K]) =>
443
  setPresentation(current => ({...current,[key]:value}));
444
 
445
  const [tab, setTab] = useState<SourceTab>("range");
446
+ const [kind, setKind] = useState<SheetChartSpec["kind"]>(opening.kind);
447
  const [rangeDraft, setRangeDraft] = useState(() => (chart?.source?.ranges ?? [seedRange]).map(chartRangeText).join(", "));
448
  const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
449
  const [loading, setLoading] = useState(!editing);
 
502
  const range = ranges?.[0] ?? null;
503
  const location = parseRange(anchor);
504
  const sourceCells = workbook?.sheets.find(s => s.id === sourceSheetId)?.cells ?? {};
505
+ const candidates = useMemo(() => chartCandidatesForRange(sourceCells, range ?? seedRange, presentation, ranges ?? [seedRange]), [sourceCells,range,presentation,ranges]);
506
+ const model = candidates.find(candidate => candidate.kind === kind)!.model;
507
+ const recommended = useMemo(() => range ? recommendChartKinds(candidates) : [], [candidates,range]);
508
+ const previewError = range ? chartPreviewError(kind, model) : "Enter a valid data range.";
509
+ const galleryKinds = galleryTab === "recommended" ? recommended : CHART_KINDS.map(entry => entry.kind);
510
+ const thumbnailPresentation: SheetChartPresentation = {
511
+ ...presentation, showLegend: false, showDataLabels: false, showAxisTitles: false, layout: "compact",
512
+ };
513
+ useEffect(() => {
514
+ if (section === "Chart" && tab === "range" && galleryTab === "recommended" && recommended.length && !recommended.includes(kind))
515
+ setKind(recommended[0]);
516
+ }, [section,tab,galleryTab,recommended,kind]);
517
+ // [W59-T08] A ribbon chart-kind shortcut can select a kind that sits below the rail's fold, and a
518
+ // selection nobody can see is not "visibly focused". `nearest` so an already-visible thumbnail
519
+ // never jumps under the pointer.
520
+ const railRef = useRef<HTMLDivElement | null>(null);
521
+ useEffect(() => {
522
+ railRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')
523
+ ?.scrollIntoView({ block: "nearest" });
524
+ }, [kind, galleryTab, section, tab]);
525
  const offeredSeries = useMemo(() => chartDataForRange(sourceCells, range ?? seedRange, {...presentation,series:[]}, ranges ?? [seedRange], kind).series, [sourceCells,range,presentation,ranges,kind]);
526
  const configuredSeries = (presentation.series ?? []).flatMap(setting => {
527
  const offered = offeredSeries.find(s => s.sourceKey === setting.key || s.y === setting.key);
 
548
 
549
  const wantsField = fn !== "count";
550
  const ready = Boolean(validGeometry) && !boundsError && !newNameError && (tab === "range"
551
+ ? range !== null && !previewError
552
  : Boolean(database) && (!wantsField || field.trim().length > 0) && Number(periods)>=MIN_PERIODS && Number(periods)<=MAX_PERIODS);
553
 
554
  const create = async () => {
 
599
  );
600
 
601
  const kindPicker = <label className="sheet-chart-setting">Chart type<select aria-label="Chart type" value={kind} onChange={event=>setKind(event.target.value as SheetChartSpec["kind"])}>{CHART_KINDS.map(entry=><option key={entry.kind} value={entry.kind}>{entry.label}</option>)}</select></label>;
602
+ const chartGallery = <div className="sheet-chart-chooser">
603
+ <div className="sheet-chart-chooser-tabs" role="tablist" aria-label="Chart choices">
604
+ {([['recommended', 'Recommended charts'], ['all', 'All charts']] as const).map(([id, label]) =>
605
+ <button type="button" role="tab" key={id} id={`${titleId}-choices-${id}`}
606
+ className="sheet-chart-chooser-tab" aria-selected={galleryTab === id}
607
+ aria-controls={`${titleId}-choices-panel`} onClick={() => {
608
+ setGalleryTab(id);
609
+ if (id === "recommended" && recommended.length) setKind(recommended[0]);
610
+ }}>{label}</button>)}
611
+ </div>
612
+ <div className="sheet-chart-chooser-body" id={`${titleId}-choices-panel`} role="tabpanel"
613
+ aria-labelledby={`${titleId}-choices-${galleryTab}`}>
614
+ <div className="sheet-chart-thumbnail-rail" ref={railRef} role="tablist" aria-label="Chart types" aria-orientation="vertical">
615
+ {galleryKinds.map(candidateKind => {
616
+ const candidateModel = candidates.find(candidate => candidate.kind === candidateKind)!.model;
617
+ const error = range ? chartPreviewError(candidateKind, candidateModel) : "Enter a valid data range.";
618
+ const label = CHART_KINDS.find(entry => entry.kind === candidateKind)!.label;
619
+ return <button type="button" role="tab" key={candidateKind} id={`${titleId}-kind-${candidateKind}`}
620
+ className="sheet-chart-thumbnail" aria-label={label} aria-selected={kind === candidateKind}
621
+ aria-controls={`${titleId}-live-preview`} onClick={() => setKind(candidateKind)}>
622
+ <span className="sheet-chart-thumbnail-name">{label}</span>
623
+ {error ? <span className="sheet-chart-thumbnail-error">{error}</span>
624
+ : <span className="sheet-chart-thumbnail-drawing" aria-hidden="true">
625
+ <DrawnChart {...candidateModel} kind={candidateKind} presentation={thumbnailPresentation} width={480} height={320}/>
626
+ </span>}
627
+ </button>;
628
+ })}
629
+ </div>
630
+ <div className="sheet-chart-live-preview" id={`${titleId}-live-preview`} role="tabpanel"
631
+ aria-labelledby={galleryKinds.includes(kind) ? `${titleId}-kind-${kind}` : undefined}>
632
+ {galleryKinds.length ? <>
633
+ <h3 className="sheet-chart-live-heading">{CHART_KINDS.find(entry => entry.kind === kind)!.label}</h3>
634
+ <p className="sheet-chart-live-description">{previewError || CHART_DESCRIPTIONS[kind]}</p>
635
+ {!previewError ? <div className="sheet-chart-live-drawing">
636
+ <DrawnChart {...model} kind={kind} presentation={presentation} width={Number(chartWidth)} height={Number(chartHeight)}/>
637
+ </div> : null}
638
+ </> : <p className="sheet-chart-live-description" role="status">Choose a range with numeric values to see recommendations.</p>}
639
+ </div>
640
+ </div>
641
+ </div>;
642
  const select = <K extends keyof SheetChartPresentation>(label: string,key:K,choices: readonly (readonly [string,string])[]) =>
643
  <label className="sheet-chart-setting">{label}<select aria-label={label} value={String(presentation[key]??(key==="ganttMode"?"duration":""))} onChange={e=>setOption(key,e.target.value as SheetChartPresentation[K])}>{choices.map(([value,label])=><option key={value} value={value}>{label}</option>)}</select></label>;
644
  const text = (label: string,key:"title"|"xTitle"|"yTitle"|"categoryTitle") =>
 
652
  setBounds({yMin:"",yMax:"",yMajor:"",yMinor:""});
653
  };
654
  const settingsPanel = <div className="sheet-chart-settings">
655
+ {section==="Chart"?<>{tab==="range" ? chartGallery : kindPicker}
656
+ <details className="sheet-chart-formatting" open={tab==="database" ? true : undefined}>
657
+ <summary>Formatting</summary>
658
+ <div className="sheet-chart-settings">
659
  {kind==="gantt"?<>{select("Task values","ganttMode",[["duration","Start and duration"],["end","Start and end"]])}<p className="sheet-chart-caption">Select task names, then start and duration or end. Dates use durations in days.</p></>:null}
660
  {select("Layout","layout",[["standard","Standard"],["compact","Compact"],["labels","Labels"]])}
661
  {select("Colors","palette",[["purple","Purple"],["categorical","Categorical"],["blue","Blue"]])}
662
  {select("Style","style",[["filled","Filled"],["outline","Outline"],["soft","Soft"]])}
663
  {kind==="histogram"?<label className="sheet-chart-setting">Bins<input aria-label="Bins" type="number" min={1} max={50} value={presentation.bins??10} onChange={e=>setOption("bins",Math.max(1,Math.min(50,Number(e.target.value)||1)))}/></label>:null}
664
  <button type="button" className="sheet-chart-quiet" onClick={resetFormatting}>Reset formatting</button>
665
+ </div>
666
+ </details>
667
  </>:null}
668
  {section==="Text"?<>{text("Chart title","title")}{text("X axis title","xTitle")}{text("Y axis title","yTitle")}{text("Category name","categoryTitle")}
669
  {toggle("Show legend","showLegend")}{toggle("Show axis titles","showAxisTitles")}{toggle("Show data labels","showDataLabels")}
 
701
  // `sheet-chart-dialog` carries no rule of its own and is not meant to: it is the name a
702
  // gate, a screenshot or a person in the inspector can point at. The paint is `.lp-dialog`.
703
  className="lp-dialog sheet-chart-dialog"
704
+ style={{ width: section === "Chart" && tab === "range" ? "min(880px, calc(100vw - 32px))" : "min(680px, calc(100vw - 32px))" }}
705
  role="dialog"
706
  aria-modal="true"
707
  aria-labelledby={titleId}
 
748
  ) : null}
749
 
750
  <div className="sheet-chart-section-tabs" role="tablist" aria-label="Chart settings sections">
751
+ {["Data","Chart","Text","Series","Axes","Location"].map(name=><button key={name} id={`${titleId}-section-${name}`} type="button" role="tab" aria-selected={section===name} aria-controls={`${titleId}-panel`} className="sheet-chart-quiet" onClick={()=>{
752
+ setSection(name);
753
+ if (name === "Chart" && tab === "range" && galleryTab === "recommended" && recommended.length) setKind(recommended[0]);
754
+ }}>{name}</button>)}
755
  </div>
756
  <div
757
  className="sheet-chart-panel"
758
  id={`${titleId}-panel`}
759
  role="tabpanel"
760
+ aria-labelledby={section === "Data" && !editing ? `${titleId}-tab-${tab}` : `${titleId}-section-${section}`}
761
  >
762
  {section!=="Data" ? settingsPanel : tab === "range" ? (
763
  <>
 
861
  {boundsError?<p role="alert" className="sheet-chart-caption">{boundsError}</p>:null}
862
  {!validGeometry?<p role="alert" className="sheet-chart-caption">Choose one anchor cell, width 320 to 2400 and height 240 to 1600.</p>:null}
863
  {newNameError?<p role="alert" className="sheet-chart-caption">Choose a unique, valid sheet name.</p>:null}
864
+ {workbook&&tab==="range"&&section!=="Chart"?<details className="sheet-chart-preview"><summary>Preview</summary>
865
+ {previewError?<p role="status">{previewError}</p>:<DrawnChart {...model} kind={kind} presentation={presentation} width={600} height={280}/>}
866
  </details>:null}
867
  </div>
868
 
 
888
  disabled={!ready}
889
  onClick={create}
890
  >
891
+ {editing ? "Save chart" : "OK"}
892
  </button>
893
  </div>
894
  </div>
web/src/sheet/Ribbon.tsx CHANGED
@@ -46,7 +46,7 @@
46
  // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order
47
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
48
 
49
- import { createContext, useContext, useCallback, useEffect, useMemo, useRef, useState } from "react";
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
  import type { Cell, CellStyle, CellStylePatch, SheetChartSpec, Workbook, SheetPrintSettings } from "./types";
52
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
@@ -246,6 +246,7 @@ const ACTIONS = [
246
 
247
  type TabId = (typeof TABS)[number]["id"];
248
  type ControlKey =
 
249
  | (typeof TABS)[number]["key"]
250
  | (typeof ACTIONS)[number]["key"]
251
  | (typeof TABS)[number]["keys"][number];
@@ -302,6 +303,7 @@ export interface RibbonTabContext {
302
  kt?: string,
303
  ktOpens?: "gallery",
304
  controlDisabled?: boolean,
 
305
  ) => ReactNode;
306
  group: (name: string, body: ReactNode, extra?: string) => ReactNode;
307
  word: (text: string) => ReactNode;
@@ -401,6 +403,18 @@ function IconChevron({ direction }: { direction: "up" | "down" | "left" | "right
401
  );
402
  }
403
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  export default function Ribbon({
405
  style, disabled = false, frozen = false, canImport = false, onApply, onAction, insert,
406
  }: RibbonProps) {
@@ -429,8 +443,10 @@ export default function Ribbon({
429
  const [formulaBarVisible, setFormulaBarVisible] = useState<boolean>(readFormulaBar);
430
  const rootRef = useRef<HTMLDivElement | null>(null);
431
  const scrollRef = useRef<HTMLDivElement | null>(null);
432
- const [canScrollLeft, setCanScrollLeft] = useState(false);
433
- const [canScrollRight, setCanScrollRight] = useState(false);
 
 
434
 
435
  useEffect(() => {
436
  const wrap = rootRef.current?.closest<HTMLElement>(".sheet-grid-wrap");
@@ -449,48 +465,8 @@ export default function Ribbon({
449
  /** Which registered tab is showing. */
450
  const [active, setActive] = useState<TabId>(TABS[0].id);
451
  const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
452
-
453
- useEffect(() => {
454
- const scroller = scrollRef.current;
455
- if (!scroller) {
456
- setCanScrollLeft(false);
457
- setCanScrollRight(false);
458
- return;
459
- }
460
- const updateScrollAvailability = () => {
461
- const toolbar = scroller.parentElement;
462
- const toolbarStyle = toolbar ? window.getComputedStyle(toolbar) : null;
463
- // Measure the full row so the chevrons cannot keep a fitting tab overflowing by themselves.
464
- const fullWidth = toolbar && toolbarStyle
465
- ? toolbar.clientWidth - parseFloat(toolbarStyle.paddingLeft)
466
- - parseFloat(toolbarStyle.paddingRight)
467
- : scroller.clientWidth;
468
- const overflows = scroller.scrollWidth > fullWidth + 1;
469
- setCanScrollLeft(overflows && scroller.scrollLeft > 1);
470
- setCanScrollRight(overflows
471
- && scroller.scrollLeft + scroller.clientWidth < scroller.scrollWidth - 1);
472
- };
473
- updateScrollAvailability();
474
- scroller.addEventListener("scroll", updateScrollAvailability, { passive: true });
475
- window.addEventListener("resize", updateScrollAvailability);
476
- const observer = typeof ResizeObserver === "undefined"
477
- ? null : new ResizeObserver(updateScrollAvailability);
478
- observer?.observe(scroller);
479
- return () => {
480
- scroller.removeEventListener("scroll", updateScrollAvailability);
481
- window.removeEventListener("resize", updateScrollAvailability);
482
- observer?.disconnect();
483
- };
484
- }, [active, collapsed]);
485
-
486
- const scrollGroups = (direction: -1 | 1) => {
487
- const scroller = scrollRef.current;
488
- if (!scroller) return;
489
- scroller.scrollBy({
490
- left: direction * scroller.clientWidth * 0.8,
491
- behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth",
492
- });
493
- };
494
 
495
  /**
496
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else — and
@@ -500,10 +476,10 @@ export default function Ribbon({
500
  * actually has an import door, in both branches.
501
  */
502
  const reachable = useMemo<readonly ControlKey[]>(
503
- () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys])
504
  .filter((key) => (key !== "import" || canImport)
505
  && (key !== "export" || !exportUnavailable)),
506
- [activeTab, canImport, collapsed, exportUnavailable],
507
  );
508
 
509
  // ⛔ FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
@@ -514,11 +490,29 @@ export default function Ribbon({
514
  if (!reachable.includes(focus)) setFocus(reachable[0]);
515
  }, [focus, reachable]);
516
 
 
 
 
 
 
 
517
  const focusControl = useCallback((key: ControlKey) => {
518
  setFocus(key);
519
- rootRef.current
520
- ?.querySelector<HTMLButtonElement>(`[data-ribbon="${key}"]`)
521
- ?.focus();
 
 
 
 
 
 
 
 
 
 
 
 
522
  }, []);
523
 
524
  const toggleCollapsed = useCallback(() => {
@@ -528,6 +522,7 @@ export default function Ribbon({
528
  return next;
529
  });
530
  setOpen("");
 
531
  }, []);
532
 
533
  /**
@@ -602,31 +597,41 @@ export default function Ribbon({
602
  // would be a second claimant on the same key.
603
  // The toolbar's arrows belong to the toolbar only while nothing is open above it.
604
  if (open) return;
605
- const at = Math.max(0, reachable.indexOf(focus));
 
 
 
 
 
 
 
 
606
  if (event.key === "ArrowRight") {
607
  event.preventDefault();
608
- focusControl(reachable[(at + 1) % reachable.length]);
609
  } else if (event.key === "ArrowLeft") {
610
  event.preventDefault();
611
- focusControl(reachable[(at - 1 + reachable.length) % reachable.length]);
612
  } else if (event.key === "Home") {
613
  event.preventDefault();
614
- focusControl(reachable[0]);
615
  } else if (event.key === "End") {
616
  event.preventDefault();
617
- focusControl(reachable[reachable.length - 1]);
618
  }
619
  }, [focus, focusControl, open, reachable]);
620
 
621
  const apply = useCallback((patch: CellStylePatch) => {
622
  setOpen("");
 
623
  onApply(patch);
624
- }, [onApply]);
625
 
626
  const act = useCallback((kind: RibbonActionKind, arg?: string | number) => {
627
  setOpen("");
 
628
  onAction({ kind, arg });
629
- }, [onAction]);
630
 
631
  /**
632
  * ⭐⭐ W53-T07 — CLOSING A MENU RETURNS FOCUS TO THE CONTROL THAT OWNS IT, and that is the
@@ -693,6 +698,7 @@ export default function Ribbon({
693
  kt?: string,
694
  ktOpens?: "gallery",
695
  controlDisabled?: boolean,
 
696
  ) => (
697
  <button
698
  type="button"
@@ -704,9 +710,9 @@ export default function Ribbon({
704
  title={label}
705
  aria-pressed={expanded === undefined ? pressed === true : undefined}
706
  aria-expanded={expanded}
707
- aria-haspopup={expanded === undefined ? undefined : "menu"}
708
  tabIndex={focus === key ? 0 : -1}
709
- disabled={disabled || controlDisabled}
710
  onFocus={() => setFocus(key)}
711
  // The grid keeps the keyboard: pressing a ribbon button must not blur the canvas, or glide
712
  // drops its selection and the act lands on nothing. Same reason as `CellActionBar`.
@@ -723,8 +729,9 @@ export default function Ribbon({
723
  * owner reads them by name, so a row of unnamed clusters would not be the thing that was asked
724
  * for. Sentence case, muted, and a scale token, never a literal size (DESIGN.md 2).
725
  */
 
726
  const group = (name: string, body: ReactNode, extra = "") => (
727
- <div className={"sheet-ribbon-group" + extra} role="group" aria-label={name}>
728
  <div className="sheet-ribbon-group-controls">{body}</div>
729
  <span className="sheet-ribbon-group-name">{name}</span>
730
  </div>
@@ -804,6 +811,80 @@ export default function Ribbon({
804
  newWindowBlocked, openNewWindow, openCellData,
805
  openPop, closePop, control, group, word, unavailable, item, insert,
806
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
 
808
  return (
809
  <div className="sheet-ribbon-shell" ref={rootRef} onKeyDown={onKeyDown}>
@@ -831,7 +912,7 @@ export default function Ribbon({
831
  tabIndex={focus === tab.key ? 0 : -1}
832
  onFocus={() => setFocus(tab.key)}
833
  onMouseDown={(e) => e.preventDefault()}
834
- onClick={() => { setActive(tab.id); if (collapsed) toggleCollapsed(); }}
835
  >
836
  {tab.label}
837
  </button>
@@ -904,44 +985,38 @@ export default function Ribbon({
904
  role="toolbar"
905
  aria-label={activeTab.toolbarLabel}
906
  >
907
- {/* Scroll buttons stay outside the roving order because keyboard focus already scrolls controls into view. */}
908
- {canScrollLeft && (
909
- <button
910
- type="button"
911
- className="sheet-ribbon-scroll-button"
912
- aria-label="Scroll ribbon left"
913
- title="Scroll ribbon left"
914
- tabIndex={-1}
915
- onMouseDown={(e) => e.preventDefault()}
916
- onClick={() => scrollGroups(-1)}
917
- >
918
- <IconChevron direction="left" />
919
- </button>
920
- )}
921
- {/* ⛔ `min-width: 0` ON THE SCROLLER IS LOAD BEARING. A flex child will not scroll
922
- without it. Import, Refresh, Export and Full screen do not live in this row
923
- (W52-T15 moved them to the tab strip above), so the only thing that can walk off
924
- the right edge at a narrow window now is a group itself, which scrolling permits. */}
925
  <div className="sheet-ribbon-scroll" ref={scrollRef}>
926
- {/* ⭐⭐ THE ACTIVE TAB'S OWN GROUPS. `ribbonHome.tsx` holds every one of them, in R8's
927
- order, and this is the whole of the shell's knowledge of what they are. */}
928
- {activeTab.groups(tabContext)}
929
- </div>
930
- {canScrollRight && (
931
- <button
932
- type="button"
933
- className="sheet-ribbon-scroll-button"
934
- aria-label="Scroll ribbon right"
935
- title="Scroll ribbon right"
936
- tabIndex={-1}
937
- onMouseDown={(e) => e.preventDefault()}
938
- onClick={() => scrollGroups(1)}
939
  >
940
- <IconChevron direction="right" />
941
- </button>
942
- )}
 
943
  </div>
944
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
945
  {/* ⭐⭐ W52-T17 (instruction 20, ruling R7) — mounted ONCE, absolutely positioned via its own
946
  `position: fixed` overlay (styles/wave52/ribbon.css), so it adds no layout of its own
947
  (the design contract's "appear without layout shift"). It reads this DOM tree through
 
46
  // labels with no ALL CAPS chrome; motion is 150 ms ease-out on opacity and transform only; z-order
47
  // rides a `--cg-z-*` token. No em dash or en dash in any string that reaches a screen.
48
 
49
+ import { Children, cloneElement, createContext, isValidElement, useContext, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
  import type { Cell, CellStyle, CellStylePatch, SheetChartSpec, Workbook, SheetPrintSettings } from "./types";
52
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
 
246
 
247
  type TabId = (typeof TABS)[number]["id"];
248
  type ControlKey =
249
+ | "overflow"
250
  | (typeof TABS)[number]["key"]
251
  | (typeof ACTIONS)[number]["key"]
252
  | (typeof TABS)[number]["keys"][number];
 
303
  kt?: string,
304
  ktOpens?: "gallery",
305
  controlDisabled?: boolean,
306
+ popupRole?: "menu" | "dialog",
307
  ) => ReactNode;
308
  group: (name: string, body: ReactNode, extra?: string) => ReactNode;
309
  word: (text: string) => ReactNode;
 
403
  );
404
  }
405
 
406
+ /** Keep each tab's wrappers, including Insert's native disabled fieldset, on both sides. */
407
+ function partitionRibbonGroups(node: ReactNode, visibleCount: number, folded: boolean): ReactNode {
408
+ return Children.map(node, (child) => {
409
+ if (!isValidElement<{ children?: ReactNode; "data-ribbon-group"?: number }>(child)) return child;
410
+ const index = child.props["data-ribbon-group"];
411
+ if (index !== undefined) return (index >= visibleCount) === folded ? child : null;
412
+ if (!child.props.children) return child;
413
+ const children = partitionRibbonGroups(child.props.children, visibleCount, folded);
414
+ return Children.count(children) ? cloneElement(child, undefined, children) : null;
415
+ });
416
+ }
417
+
418
  export default function Ribbon({
419
  style, disabled = false, frozen = false, canImport = false, onApply, onAction, insert,
420
  }: RibbonProps) {
 
443
  const [formulaBarVisible, setFormulaBarVisible] = useState<boolean>(readFormulaBar);
444
  const rootRef = useRef<HTMLDivElement | null>(null);
445
  const scrollRef = useRef<HTMLDivElement | null>(null);
446
+ const overflowRef = useRef<HTMLDivElement | null>(null);
447
+ const overflowTriggerRef = useRef<HTMLSpanElement | null>(null);
448
+ const [overflowOpen, setOverflowOpen] = useState(false);
449
+ const [groupFit, setGroupFit] = useState<{ tab: TabId; count: number } | null>(null);
450
 
451
  useEffect(() => {
452
  const wrap = rootRef.current?.closest<HTMLElement>(".sheet-grid-wrap");
 
465
  /** Which registered tab is showing. */
466
  const [active, setActive] = useState<TabId>(TABS[0].id);
467
  const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
468
+ const visibleGroupCount = groupFit?.tab === active ? groupFit.count : Infinity;
469
+ const hasOverflow = Number.isFinite(visibleGroupCount);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
 
471
  /**
472
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else — and
 
476
  * actually has an import door, in both branches.
477
  */
478
  const reachable = useMemo<readonly ControlKey[]>(
479
+ () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys, ...(hasOverflow ? ["overflow" as const] : [])])
480
  .filter((key) => (key !== "import" || canImport)
481
  && (key !== "export" || !exportUnavailable)),
482
+ [activeTab, canImport, collapsed, exportUnavailable, hasOverflow],
483
  );
484
 
485
  // ⛔ FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
 
490
  if (!reachable.includes(focus)) setFocus(reachable[0]);
491
  }, [focus, reachable]);
492
 
493
+ useEffect(() => {
494
+ if (hasOverflow && !overflowOpen && overflowRef.current?.querySelector(`[data-ribbon="${focus}"]`)) {
495
+ setFocus("overflow");
496
+ }
497
+ }, [focus, hasOverflow, overflowOpen, visibleGroupCount]);
498
+
499
  const focusControl = useCallback((key: ControlKey) => {
500
  setFocus(key);
501
+ const selector = `[data-ribbon="${key}"]`;
502
+ const foldedControl = overflowRef.current?.querySelector<HTMLButtonElement>(selector);
503
+ if (foldedControl) {
504
+ // Closed folded groups remain mounted for measurement; reveal them before focusing.
505
+ setOverflowOpen(true);
506
+ requestAnimationFrame(() => overflowRef.current?.querySelector<HTMLButtonElement>(selector)?.focus());
507
+ } else {
508
+ rootRef.current?.querySelector<HTMLButtonElement>(selector)?.focus();
509
+ }
510
+ }, []);
511
+
512
+ const closeOverflow = useCallback(() => {
513
+ setOverflowOpen(false);
514
+ setFocus("overflow");
515
+ overflowTriggerRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
516
  }, []);
517
 
518
  const toggleCollapsed = useCallback(() => {
 
522
  return next;
523
  });
524
  setOpen("");
525
+ setOverflowOpen(false);
526
  }, []);
527
 
528
  /**
 
597
  // would be a second claimant on the same key.
598
  // The toolbar's arrows belong to the toolbar only while nothing is open above it.
599
  if (open) return;
600
+ if (event.target instanceof HTMLElement && event.target.matches("input, textarea, select, [contenteditable=true]")) return;
601
+ const enabledKeys = reachable.filter(key => {
602
+ const selector = `[data-ribbon="${key}"]`;
603
+ const button = rootRef.current?.querySelector<HTMLButtonElement>(selector)
604
+ ?? overflowRef.current?.querySelector<HTMLButtonElement>(selector);
605
+ return button && !button.matches(":disabled");
606
+ });
607
+ if (!enabledKeys.length) return;
608
+ const at = Math.max(0, enabledKeys.indexOf(focus));
609
  if (event.key === "ArrowRight") {
610
  event.preventDefault();
611
+ focusControl(enabledKeys[(at + 1) % enabledKeys.length]);
612
  } else if (event.key === "ArrowLeft") {
613
  event.preventDefault();
614
+ focusControl(enabledKeys[(at - 1 + enabledKeys.length) % enabledKeys.length]);
615
  } else if (event.key === "Home") {
616
  event.preventDefault();
617
+ focusControl(enabledKeys[0]);
618
  } else if (event.key === "End") {
619
  event.preventDefault();
620
+ focusControl(enabledKeys[enabledKeys.length - 1]);
621
  }
622
  }, [focus, focusControl, open, reachable]);
623
 
624
  const apply = useCallback((patch: CellStylePatch) => {
625
  setOpen("");
626
+ if (overflowOpen) closeOverflow();
627
  onApply(patch);
628
+ }, [closeOverflow, onApply, overflowOpen]);
629
 
630
  const act = useCallback((kind: RibbonActionKind, arg?: string | number) => {
631
  setOpen("");
632
+ if (overflowOpen) closeOverflow();
633
  onAction({ kind, arg });
634
+ }, [closeOverflow, onAction, overflowOpen]);
635
 
636
  /**
637
  * ⭐⭐ W53-T07 — CLOSING A MENU RETURNS FOCUS TO THE CONTROL THAT OWNS IT, and that is the
 
698
  kt?: string,
699
  ktOpens?: "gallery",
700
  controlDisabled?: boolean,
701
+ popupRole: "menu" | "dialog" = "menu",
702
  ) => (
703
  <button
704
  type="button"
 
710
  title={label}
711
  aria-pressed={expanded === undefined ? pressed === true : undefined}
712
  aria-expanded={expanded}
713
+ aria-haspopup={expanded === undefined ? undefined : popupRole}
714
  tabIndex={focus === key ? 0 : -1}
715
+ disabled={(key !== "overflow" && disabled) || controlDisabled}
716
  onFocus={() => setFocus(key)}
717
  // The grid keeps the keyboard: pressing a ribbon button must not blur the canvas, or glide
718
  // drops its selection and the act lands on nothing. Same reason as `CellActionBar`.
 
729
  * owner reads them by name, so a row of unnamed clusters would not be the thing that was asked
730
  * for. Sentence case, muted, and a scale token, never a literal size (DESIGN.md 2).
731
  */
732
+ let groupIndex = 0;
733
  const group = (name: string, body: ReactNode, extra = "") => (
734
+ <div key={name} data-ribbon-group={groupIndex++} className={"sheet-ribbon-group" + extra} role="group" aria-label={name}>
735
  <div className="sheet-ribbon-group-controls">{body}</div>
736
  <span className="sheet-ribbon-group-name">{name}</span>
737
  </div>
 
811
  newWindowBlocked, openNewWindow, openCellData,
812
  openPop, closePop, control, group, word, unavailable, item, insert,
813
  };
814
+ const activeGroups = activeTab.groups(tabContext);
815
+ const overflowContent = (
816
+ <div className="sheet-ribbon-overflow-content" ref={overflowRef}>
817
+ {partitionRibbonGroups(activeGroups, visibleGroupCount, true)}
818
+ </div>
819
+ );
820
+
821
+ useLayoutEffect(() => {
822
+ const scroller = scrollRef.current;
823
+ const trigger = overflowTriggerRef.current;
824
+ if (!scroller || !trigger || collapsed) return;
825
+ // An open form must not remount during a resize. Refit immediately after it closes.
826
+ if (open || overflowOpen) return;
827
+ const groups = [
828
+ ...scroller.querySelectorAll<HTMLElement>("[data-ribbon-group]"),
829
+ ...(overflowRef.current?.querySelectorAll<HTMLElement>("[data-ribbon-group]") ?? []),
830
+ ].sort((a, b) => Number(a.dataset.ribbonGroup) - Number(b.dataset.ribbonGroup));
831
+ const fitGroups = () => {
832
+ // Keep natural widths even for folded groups; never measure a compressed flex child.
833
+ // Normalize the last-child divider so folding cannot change the measured total by a pixel.
834
+ const widths = groups.map(element => {
835
+ const border = parseFloat(window.getComputedStyle(element).borderRightWidth) || 0;
836
+ return Math.ceil(element.getBoundingClientRect().width - border + 1);
837
+ });
838
+ const available = scroller.clientWidth;
839
+ if (!available || widths.length !== groupIndex) return;
840
+ let count = Infinity;
841
+ if (widths.reduce((sum, width) => sum + width, 0) > available) {
842
+ const budget = Math.max(0, available - trigger.getBoundingClientRect().width - 8);
843
+ count = 0;
844
+ let used = 0;
845
+ while (count < widths.length && used + widths[count] <= budget) used += widths[count++];
846
+ }
847
+ const focusedGroup = document.activeElement?.closest<HTMLElement>("[data-ribbon-group]");
848
+ if (focusedGroup && scroller.contains(focusedGroup) && Number(focusedGroup.dataset.ribbonGroup) >= count) {
849
+ setFocus("overflow");
850
+ requestAnimationFrame(() => trigger.querySelector<HTMLButtonElement>("button")?.focus());
851
+ } else if (count === Infinity && trigger.contains(document.activeElement)) {
852
+ setFocus(activeTab.key);
853
+ requestAnimationFrame(() => rootRef.current?.querySelector<HTMLButtonElement>(`[data-ribbon="${activeTab.key}"]`)?.focus());
854
+ }
855
+ setGroupFit(current => current?.tab === active && current.count === count ? current : { tab: active, count });
856
+ scroller.scrollLeft = 0;
857
+ };
858
+ fitGroups();
859
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(fitGroups);
860
+ observer?.observe(scroller);
861
+ observer?.observe(trigger);
862
+ groups.forEach(element => observer?.observe(element));
863
+ window.addEventListener("resize", fitGroups);
864
+ return () => {
865
+ observer?.disconnect();
866
+ window.removeEventListener("resize", fitGroups);
867
+ };
868
+ }, [active, activeTab.key, collapsed, groupIndex, open, overflowOpen, visibleGroupCount]);
869
+
870
+ const toggleOverflow = () => {
871
+ if (overflowOpen) {
872
+ closeOverflow();
873
+ return;
874
+ }
875
+ setOpen("");
876
+ setOverflowOpen(true);
877
+ requestAnimationFrame(() => {
878
+ const first = overflowRef.current?.querySelector<HTMLButtonElement>("[data-ribbon]:not(:disabled)");
879
+ if (first) {
880
+ setFocus(first.dataset.ribbon as ControlKey);
881
+ first.focus();
882
+ } else {
883
+ setFocus("overflow");
884
+ overflowTriggerRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
885
+ }
886
+ });
887
+ };
888
 
889
  return (
890
  <div className="sheet-ribbon-shell" ref={rootRef} onKeyDown={onKeyDown}>
 
912
  tabIndex={focus === tab.key ? 0 : -1}
913
  onFocus={() => setFocus(tab.key)}
914
  onMouseDown={(e) => e.preventDefault()}
915
+ onClick={() => { setOpen(""); setOverflowOpen(false); setActive(tab.id); if (collapsed) toggleCollapsed(); }}
916
  >
917
  {tab.label}
918
  </button>
 
985
  role="toolbar"
986
  aria-label={activeTab.toolbarLabel}
987
  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  <div className="sheet-ribbon-scroll" ref={scrollRef}>
989
+ {partitionRibbonGroups(activeGroups, visibleGroupCount, false)}
990
+ <span
991
+ ref={overflowTriggerRef}
992
+ className={"sheet-ribbon-overflow-trigger" + (hasOverflow ? "" : " is-measuring")}
993
+ aria-hidden={!hasOverflow || undefined}
 
 
 
 
 
 
 
 
994
  >
995
+ {control("overflow", "More groups", <><IconChevron direction="down" />{word("More groups")}</>,
996
+ toggleOverflow, false, overflowOpen, hasOverflow ? "Y" : undefined, "gallery", undefined, "dialog")}
997
+ </span>
998
+ </div>
999
  </div>
1000
  )}
1001
+ {!collapsed && (overflowOpen && hasOverflow ? (
1002
+ <AnchoredOverlay
1003
+ anchor={overflowTriggerRef.current}
1004
+ className={"sheet-ribbon sheet-ribbon-overflow " + activeTab.bodyClass + (open ? "" : " sheet-ribbon-pop")}
1005
+ onDismiss={closeOverflow}
1006
+ role="dialog"
1007
+ ariaLabel="More ribbon groups"
1008
+ initialFocus="none"
1009
+ restoreFocus={false}
1010
+ placement="bottom-end"
1011
+ dataKind="sheet-ribbon-overflow"
1012
+ >
1013
+ {overflowContent}
1014
+ </AnchoredOverlay>
1015
+ ) : (
1016
+ <div className={"sheet-ribbon sheet-ribbon-overflow-measure " + activeTab.bodyClass} aria-hidden="true">
1017
+ {overflowContent}
1018
+ </div>
1019
+ ))}
1020
  {/* ⭐⭐ W52-T17 (instruction 20, ruling R7) — mounted ONCE, absolutely positioned via its own
1021
  `position: fixed` overlay (styles/wave52/ribbon.css), so it adds no layout of its own
1022
  (the design contract's "appear without layout shift"). It reads this DOM tree through
web/src/sheet/SheetChart.tsx CHANGED
@@ -129,10 +129,22 @@ export function chartDataForRange(
129
  if (!matrix.length || !matrix[0].length) return empty();
130
  // A lone row is a numeric run, retaining the legacy one-row selection behavior.
131
  if (matrix.length === 1) matrix = matrix[0].map(v => [v]);
 
 
 
 
 
 
 
 
 
 
132
  const first = matrix[0];
133
- const header = presentation.headers === "firstRow" || (presentation.headers !== "none"
 
 
134
  && first.some(v => v.text.trim() && v.number === null)
135
- && matrix.slice(1).some(r => r.some(v => v.number !== null)));
136
  const body = matrix.slice(header ? 1 : 0);
137
  if (!body.length) return empty();
138
  const numericCols = first.map((_, c) => c).filter(c => body.some(r => r[c].number !== null));
@@ -146,7 +158,7 @@ export function chartDataForRange(
146
  if (!valueCols.length) return empty(["stock", "gantt"].includes(kind) ? "Choose numeric chart values." : undefined);
147
  let series = valueCols.map(c => ({
148
  y: `value${c}`,
149
- sourceKey: presentation.orientation === "rows" ? `row:${first[c].row+1}` : `column:${addressOf(first[c].col,0).replace(/[0-9]+$/, "")}`,
150
  label: header ? first[c].text || addressOf(first[c].col,first[c].row) : addressOf(first[c].col,first[c].row).replace(/[0-9]+$/, ""),
151
  color: undefined as SheetChartColor | undefined,
152
  }));
 
129
  if (!matrix.length || !matrix[0].length) return empty();
130
  // A lone row is a numeric run, retaining the legacy one-row selection behavior.
131
  if (matrix.length === 1) matrix = matrix[0].map(v => [v]);
132
+ // [W59-T06] Labels above one numeric run become categories; blanks retain missing values.
133
+ const headerRowCategories = !["stock", "gantt", "scatter", "bubble"].includes(kind)
134
+ && (presentation.headers ?? "auto") !== "none"
135
+ && (presentation.categoryLabels ?? "auto") === "auto"
136
+ && (presentation.orientation ?? "columns") === "columns"
137
+ && matrix.length === 2 && matrix[0].length > 1
138
+ && matrix[0].every(v => v.text.trim() && v.number === null)
139
+ && matrix[1].some(v => v.number !== null)
140
+ && matrix[1].every(v => v.number !== null || !v.text.trim());
141
+ if (headerRowCategories) matrix = matrix[0].map((_, c) => matrix.map(r => r[c]));
142
  const first = matrix[0];
143
+ const numericHeaderCols = first.map((_, c) => c).filter(c => matrix.slice(1).some(r => r[c].number !== null));
144
+ // [W59-T06] Auto headers have no numbers in value columns; a rotated header is already categories.
145
+ const header = !headerRowCategories && (presentation.headers === "firstRow" || (presentation.headers !== "none"
146
  && first.some(v => v.text.trim() && v.number === null)
147
+ && numericHeaderCols.length > 0 && numericHeaderCols.every(c => first[c].number === null)));
148
  const body = matrix.slice(header ? 1 : 0);
149
  if (!body.length) return empty();
150
  const numericCols = first.map((_, c) => c).filter(c => body.some(r => r[c].number !== null));
 
158
  if (!valueCols.length) return empty(["stock", "gantt"].includes(kind) ? "Choose numeric chart values." : undefined);
159
  let series = valueCols.map(c => ({
160
  y: `value${c}`,
161
+ sourceKey: presentation.orientation === "rows" || headerRowCategories ? `row:${first[c].row+1}` : `column:${addressOf(first[c].col,0).replace(/[0-9]+$/, "")}`,
162
  label: header ? first[c].text || addressOf(first[c].col,first[c].row) : addressOf(first[c].col,first[c].row).replace(/[0-9]+$/, ""),
163
  color: undefined as SheetChartColor | undefined,
164
  }));
web/src/sheet/SheetGrid.tsx CHANGED
@@ -197,8 +197,8 @@ import type { SavedViewShadow } from "./bindingRefs";
197
  // `ShortcutsPanel.tsx` renders it, so the two cannot advertise different keys.
198
  import { arrowStep, columnBand, commitDirection, commitTarget, currentRegion, edgeIndex, edgeStart,
199
  extendEdgeRect, isArrowKey, KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow, matchShortcut,
200
- rowBand, shortcutOwner, structureAxis, tabRunOrigin } from "./shortcuts";
201
- import type { SelectionAxis, SelectionRect, ShortcutId } from "./shortcuts";
202
 
203
  /**
204
  * ⭐⭐ W50-T20 — THE EXTENT IS THE SHEET'S NOW, AND THESE ARE ONLY ITS DEFAULTS.
@@ -695,8 +695,8 @@ export default function SheetGrid({
695
  *
696
  * `tabRunAt` holds the column a run of Tabs STARTED at, so the Enter that ends the run can
697
  * return to it; `shortcuts.ts::tabRunOrigin` owns the rule for what it becomes on each press.
698
- * `commitNav` is raised for exactly one selection change, by the commit-navigation arm in
699
- * `onKeyDown`, and read back in `onSelectionChange` below.
700
  *
701
  * ⛔ THE FLAG IS WHY THE RESET CAN LIVE IN `onSelectionChange` AT ALL. The done-when asks the
702
  * run to reset when the selection moves by anything other than Tab, and that handler is the ONE
@@ -710,6 +710,14 @@ export default function SheetGrid({
710
  */
711
  const tabRunAt = useRef<number | null>(null);
712
  const commitNav = useRef(false);
 
 
 
 
 
 
 
 
713
  /**
714
  * ⭐ W51-T17 — THE TWO SURFACES THE KEYBOARD OPENS, and both live INSIDE this component's own
715
  * box rather than in a portal: portalling drops every descendant-scoped rule with no error at
@@ -1188,8 +1196,8 @@ export default function SheetGrid({
1188
  * identity also gives it a new callback identity. Keeping one callback lets a same-tab refresh
1189
  * remain a repaint rather than look like navigation.
1190
  */
1191
- const selectionContextRef = useRef({ addrAt, onSelect, tab, viewRowOf, visCols });
1192
- selectionContextRef.current = { addrAt, onSelect, tab, viewRowOf, visCols };
1193
 
1194
  /**
1195
  * What the NEXT call to `onSelectionChange` is: a reader gesture or an app-owned move.
@@ -1223,8 +1231,43 @@ export default function SheetGrid({
1223
  const replacementCell = replacementSelection?.current?.cell;
1224
  const offeredCell = next.current?.cell;
1225
  let offered = next;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1226
  if (replacementSelection && replacementCell && offeredCell
1227
- && fromGlide && !readerCaused
1228
  && (replacementCell[0] !== offeredCell[0] || replacementCell[1] !== offeredCell[1])) {
1229
  offered = {
1230
  ...replacementSelection,
@@ -1252,6 +1295,13 @@ export default function SheetGrid({
1252
  // own move and this consumes it, so a Tab keeps the run and everything else ends it.
1253
  if (commitNav.current) commitNav.current = false;
1254
  else tabRunAt.current = null;
 
 
 
 
 
 
 
1255
  // R11: the bar is anchored to the selection and unmounts when the selection changes. Clearing
1256
  // the anchor here is what makes "disappears when the selection changes" true rather than
1257
  // approximately true.
@@ -1478,7 +1528,7 @@ export default function SheetGrid({
1478
  }, [formulaEdit]);
1479
 
1480
  /** Enter/Tab outside point mode, and the second half of PM-12 inside it. */
1481
- const commitFormulaEditor = useCallback(() => {
1482
  if (!formulaEdit) return;
1483
  const { addr, draft, inBand, viewCell } = formulaEdit;
1484
  // ⭐⭐ W53-T02 — READY IS RESTORED FIRST, THE WRITE SECOND, and the order is the whole point.
@@ -1497,22 +1547,32 @@ export default function SheetGrid({
1497
  // cancelled rather than tidied up and saved.
1498
  const closed = autoCloseFormula(draft);
1499
  commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), closed, cellValueGetter) });
1500
- // Mirrors glide's own default Enter-commit: the selection moves down one row, so the custom
1501
- // editor does not feel like a different control from editing any other cell.
 
1502
  // ⚠ NOT `applySelection` -- that helper is declared FURTHER DOWN this component (it is the
1503
  // one thing a controlled selection needs `gridRef` for, beside the structural ops below), and
1504
  // this callback is defined ahead of it. `onSelectionChange` is the same door one layer down.
1505
  if (!inBand) {
1506
- const next: Item = [viewCell[0], viewCell[1] + 1];
 
 
 
 
 
 
1507
  selectionIntentRef.current = "reader";
1508
  onSelectionChange({
1509
  columns: CompactSelection.empty(),
1510
  rows: CompactSelection.empty(),
1511
  current: { cell: next, range: { x: next[0], y: next[1], width: 1, height: 1 }, rangeStack: [] },
1512
  });
 
 
 
1513
  gridRef.current?.scrollTo(next[0], next[1]);
1514
  }
1515
- }, [cellValueGetter, commitWithRecalc, formulaEdit, onSelectionChange, tab]);
1516
 
1517
  /**
1518
  * ⭐⭐ W54-T21 — THE BLUR DOOR, AND THE ONE REASON IT IS NO LONGER THE COMMIT ITSELF.
@@ -1850,8 +1910,14 @@ export default function SheetGrid({
1850
  return;
1851
  }
1852
  if (e.key === "Enter") { e.preventDefault(); commitFormulaEditor(); return; }
1853
- // D-1: Tab is captured ONLY while the dropdown is open (handled above); otherwise it traverses
1854
- // focus like any other control, so nothing here intercepts it.
 
 
 
 
 
 
1855
  // ⛔ W54-T21: and NOTHING in this handler reads Escape, in any branch. The arbiter's listener
1856
  // is capture phase on the document and stops propagation, so a branch here could never fire
1857
  // anyway - it would be dead code that a later reader would trust.
@@ -1875,14 +1941,14 @@ export default function SheetGrid({
1875
 
1876
  /**
1877
  * ⭐⭐ CR-1/CR-5/CR-10/PM-6 — EVERY CELL A LIVE REFERENCE TOUCHES, KEYED BY ITS REAL 1-BASED
1878
- * `"col,row"` ADDRESS, TO THE COLOUR IT OWNS. `refsIn` already scans the draft on every
1879
- * keystroke (CR-10: "recolour on every keystroke"), and since a point-mode proposal is spliced
1880
  * into the SAME draft text as any other reference (`proposeCell` above), the proposal gets its
1881
  * border for free through this one map -- PM-6 needs no separate mechanism.
1882
  *
1883
- * ⚠ EACH CELL OF A RANGE GETS ITS OWN BORDER, not one rectangle traced around the range's outer
1884
- * edge. Simpler, and still says "these cells" unambiguously; tracing only the outer edge is the
1885
- * tidy follow up.
1886
  *
1887
  * ⭐⭐ W53-T02 / INSTRUCTION 18 — RANGE FINDER ALSO FIRES ON A BARE SELECTION. Microsoft's own
1888
  * page documents only the edit-mode trigger ("double-click the cell ... Excel highlights each
@@ -1893,12 +1959,14 @@ export default function SheetGrid({
1893
  * (`paintRefBorder` further down) - there is no second outline mechanism to keep in step.
1894
  */
1895
  const formulaRefCells = useMemo(() => {
1896
- const out = new Map<string, string>();
1897
  const source = formulaEdit
1898
  ? formulaEdit.draft
1899
  : (selected?.cell?.kind === "formula" ? (selected.cell.formula ?? "") : "");
1900
  if (!source) return out;
 
1901
  for (const ref of refsIn(source)) {
 
1902
  let c0 = colToIndex(ref.start.col);
1903
  let c1 = colToIndex(ref.end.col);
1904
  let r0 = ref.start.row;
@@ -1915,7 +1983,7 @@ export default function SheetGrid({
1915
  const color = colorForSlot(ref.colorIndex, "light");
1916
  for (let c = Math.min(c0, c1); c <= Math.max(c0, c1); c += 1) {
1917
  for (let r = Math.min(r0, r1); r <= Math.max(r0, r1); r += 1) {
1918
- out.set(`${c},${r}`, color);
1919
  }
1920
  }
1921
  }
@@ -2009,8 +2077,8 @@ export default function SheetGrid({
2009
  */
2010
  const refPaintKey = useMemo(() => {
2011
  const parts: string[] = [];
2012
- for (const [key, color] of formulaRefCells) {
2013
- parts.push(`${key}:${color}:${formulaPointCells.has(key) ? "dash" : "solid"}`);
2014
  }
2015
  for (const key of formulaPointCells) {
2016
  if (!formulaRefCells.has(key)) parts.push(`${key}:none:dash`);
@@ -3745,8 +3813,9 @@ export default function SheetGrid({
3745
  const cur = selection?.current;
3746
 
3747
  switch (hit) {
3748
- // -- the five the grid canvas owns. Unreachable while the table says `canvas`. --------
3749
- case "extend-cell": case "go-home": case "page-up": case "page-down": case "select-all":
 
3750
  return;
3751
 
3752
  // -- moving and selecting -------------------------------------------------------------
@@ -3810,6 +3879,21 @@ export default function SheetGrid({
3810
  if (!cur) return;
3811
  applySelection(rowBand(cur.cell[1], visCols.length), cur.cell);
3812
  return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3813
  case "select-region": {
3814
  if (!cur) return;
3815
  const region = currentRegion({ col: realCol(cur.cell[0]), row: realRow(cur.cell[1]) },
@@ -4150,15 +4234,34 @@ export default function SheetGrid({
4150
  // same reference's slot colour, which is the state instruction 18 describes. The colour is
4151
  // what tells it apart from the copy marquee's own dash further down.
4152
  const refKey = `${realCol(col) + 1},${realRow(row) + 1}`;
4153
- const refColor = formulaRefCells.get(refKey);
4154
  const refProposed = formulaPointCells.has(refKey);
4155
  const paintRefBorder = () => {
4156
- if (!refColor) return;
 
 
4157
  ctx.save();
4158
- ctx.strokeStyle = refColor;
4159
  ctx.lineWidth = 2;
4160
  if (refProposed) ctx.setLineDash([4, 3]);
4161
- ctx.strokeRect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4162
  ctx.setLineDash([]);
4163
  ctx.restore();
4164
  };
@@ -4581,6 +4684,12 @@ export default function SheetGrid({
4581
 
4582
  <div
4583
  className="sheet-grid-canvas"
 
 
 
 
 
 
4584
  onPointerDownCapture={() => { pointerSelectingRef.current = true; }}
4585
  onPointerUpCapture={() => {
4586
  queueMicrotask(() => { pointerSelectingRef.current = false; });
 
197
  // `ShortcutsPanel.tsx` renders it, so the two cannot advertise different keys.
198
  import { arrowStep, columnBand, commitDirection, commitTarget, currentRegion, edgeIndex, edgeStart,
199
  extendEdgeRect, isArrowKey, KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow, matchShortcut,
200
+ rowBand, selectAllTarget, shortcutOwner, structureAxis, tabRunOrigin } from "./shortcuts";
201
+ import type { CommitDirection, SelectionAxis, SelectionRect, ShortcutId } from "./shortcuts";
202
 
203
  /**
204
  * ⭐⭐ W50-T20 — THE EXTENT IS THE SHEET'S NOW, AND THESE ARE ONLY ITS DEFAULTS.
 
695
  *
696
  * `tabRunAt` holds the column a run of Tabs STARTED at, so the Enter that ends the run can
697
  * return to it; `shortcuts.ts::tabRunOrigin` owns the rule for what it becomes on each press.
698
+ * `commitNav` is raised for exactly one selection change by the canvas commit arm and consumed
699
+ * in `onSelectionChange` below. Editor commits restore their run after that door resets it.
700
  *
701
  * ⛔ THE FLAG IS WHY THE RESET CAN LIVE IN `onSelectionChange` AT ALL. The done-when asks the
702
  * run to reset when the selection moves by anything other than Tab, and that handler is the ONE
 
710
  */
711
  const tabRunAt = useRef<number | null>(null);
712
  const commitNav = useRef(false);
713
+ const overlayCommit = useRef<{ dir: CommitDirection; at: number; from: Item } | null>(null);
714
+ /**
715
+ * W59-T02 / R4: the Ctrl+A run remembers its sheet anchor and consecutive press count.
716
+ * Its own selection must preserve the run, so `selectAllNav` is consumed once at the same
717
+ * selection door as `commitNav`. A separate flag matters: a Tab commit must end this run.
718
+ */
719
+ const selectAllRunAt = useRef<{ col: number; row: number; count: number } | null>(null);
720
+ const selectAllNav = useRef(false);
721
  /**
722
  * ⭐ W51-T17 — THE TWO SURFACES THE KEYBOARD OPENS, and both live INSIDE this component's own
723
  * box rather than in a portal: portalling drops every descendant-scoped rule with no error at
 
1196
  * identity also gives it a new callback identity. Keeping one callback lets a same-tab refresh
1197
  * remain a repaint rather than look like navigation.
1198
  */
1199
+ const selectionContextRef = useRef({ addrAt, bandRows, onSelect, tab, viewRowOf, visCols, visRows });
1200
+ selectionContextRef.current = { addrAt, bandRows, onSelect, tab, viewRowOf, visCols, visRows };
1201
 
1202
  /**
1203
  * What the NEXT call to `onSelectionChange` is: a reader gesture or an app-owned move.
 
1231
  const replacementCell = replacementSelection?.current?.cell;
1232
  const offeredCell = next.current?.cell;
1233
  let offered = next;
1234
+ let overlayRun: number | null | undefined;
1235
+ // W59-T03 / D-697: a captured chord alone is not a grid commit. Require both a fresh stamp
1236
+ // from the prior cell and glide's matching, unmodified move. The canvas commit arm already
1237
+ // aged the run and raised commitNav, so consuming its stamp must not age it a second time.
1238
+ const stamp = overlayCommit.current;
1239
+ overlayCommit.current = null;
1240
+ if (!commitNav.current && fromGlide && stamp && prior && offeredCell
1241
+ && Date.now() - stamp.at < 300
1242
+ && prior[0] === stamp.from[0] && prior[1] === stamp.from[1]) {
1243
+ const bounds = {
1244
+ minCol: 0, maxCol: Math.max(0, context.visCols.length - 1),
1245
+ minRow: -context.bandRows, maxRow: Math.max(0, context.visRows.length - 1),
1246
+ };
1247
+ const from = { col: prior[0], row: prior[1] };
1248
+ const expected = commitTarget(from, stamp.dir, null, bounds);
1249
+ if (offeredCell[0] === expected.col && offeredCell[1] === expected.row) {
1250
+ const origin = tabRunAt.current;
1251
+ if ((stamp.dir === "down" || stamp.dir === "up") && origin !== null) {
1252
+ const land = commitTarget(from, stamp.dir, origin, bounds);
1253
+ offered = {
1254
+ ...offered,
1255
+ current: {
1256
+ ...offered.current!,
1257
+ cell: [land.col, land.row] as Item,
1258
+ range: { x: land.col, y: land.row, width: 1, height: 1 },
1259
+ },
1260
+ };
1261
+ }
1262
+ overlayRun = tabRunOrigin(origin, stamp.dir, prior[0]);
1263
+ }
1264
+ }
1265
+ const overlayCommitted = overlayRun !== undefined;
1266
+
1267
+ // An overlay commit can replace the workbook before glide offers its next cell. Its
1268
+ // validated move wins over that replacement's reconciliation handoff, just as a click does.
1269
  if (replacementSelection && replacementCell && offeredCell
1270
+ && fromGlide && !readerCaused && !overlayCommitted
1271
  && (replacementCell[0] !== offeredCell[0] || replacementCell[1] !== offeredCell[1])) {
1272
  offered = {
1273
  ...replacementSelection,
 
1295
  // own move and this consumes it, so a Tab keeps the run and everything else ends it.
1296
  if (commitNav.current) commitNav.current = false;
1297
  else tabRunAt.current = null;
1298
+ // W59-T03 / D-697: a validated glide overlay commit is a commit too. The reset above cannot
1299
+ // know that, because glide never reaches `onKeyDown` and so nothing claimed the move; this
1300
+ // puts back the run the commit should leave behind, computed from the origin read BEFORE it.
1301
+ if (overlayRun !== undefined) tabRunAt.current = overlayRun;
1302
+ // W59-T02 / R4: only Ctrl+A's own selection keeps its run, including at the same anchor.
1303
+ if (selectAllNav.current) selectAllNav.current = false;
1304
+ else selectAllRunAt.current = null;
1305
  // R11: the bar is anchored to the selection and unmounts when the selection changes. Clearing
1306
  // the anchor here is what makes "disappears when the selection changes" true rather than
1307
  // approximately true.
 
1528
  }, [formulaEdit]);
1529
 
1530
  /** Enter/Tab outside point mode, and the second half of PM-12 inside it. */
1531
+ const commitFormulaEditor = useCallback((move: CommitDirection = "down") => {
1532
  if (!formulaEdit) return;
1533
  const { addr, draft, inBand, viewCell } = formulaEdit;
1534
  // ⭐⭐ W53-T02 — READY IS RESTORED FIRST, THE WRITE SECOND, and the order is the whole point.
 
1547
  // cancelled rather than tidied up and saved.
1548
  const closed = autoCloseFormula(draft);
1549
  commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), closed, cellValueGetter) });
1550
+ // W59-T01 / instruction 3: choose the move inside the commit so Tab lands horizontally once.
1551
+ // The default stays down; commitTarget now clamps at the last visible row, matching the
1552
+ // canvas Enter path instead of letting the editor select beyond the sheet.
1553
  // ⚠ NOT `applySelection` -- that helper is declared FURTHER DOWN this component (it is the
1554
  // one thing a controlled selection needs `gridRef` for, beside the structural ops below), and
1555
  // this callback is defined ahead of it. `onSelectionChange` is the same door one layer down.
1556
  if (!inBand) {
1557
+ const origin = tabRunAt.current;
1558
+ const land = commitTarget(
1559
+ { col: viewCell[0], row: viewCell[1] }, move, origin,
1560
+ { minCol: 0, maxCol: Math.max(0, visCols.length - 1),
1561
+ minRow: -bandRows, maxRow: Math.max(0, visRows.length - 1) },
1562
+ );
1563
+ const next: Item = [land.col, land.row];
1564
  selectionIntentRef.current = "reader";
1565
  onSelectionChange({
1566
  columns: CompactSelection.empty(),
1567
  rows: CompactSelection.empty(),
1568
  current: { cell: next, range: { x: next[0], y: next[1], width: 1, height: 1 }, rangeStack: [] },
1569
  });
1570
+ // W59-T03 / D-697's second half: that door resets the run for any move it was not told
1571
+ // about. This is a commit, so the run continues from the origin read above.
1572
+ tabRunAt.current = tabRunOrigin(origin, move, viewCell[0]);
1573
  gridRef.current?.scrollTo(next[0], next[1]);
1574
  }
1575
+ }, [bandRows, cellValueGetter, commitWithRecalc, formulaEdit, onSelectionChange, tab, visCols, visRows]);
1576
 
1577
  /**
1578
  * ⭐⭐ W54-T21 — THE BLUR DOOR, AND THE ONE REASON IT IS NO LONGER THE COMMIT ITSELF.
 
1910
  return;
1911
  }
1912
  if (e.key === "Enter") { e.preventDefault(); commitFormulaEditor(); return; }
1913
+ // W59-T01 / instruction 3: plain-edit Tab commits and moves right; Shift+Tab moves left.
1914
+ // The dropdown and point-mode branches above keep ownership of their Tab gestures.
1915
+ if (e.key === "Tab") {
1916
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
1917
+ e.preventDefault();
1918
+ commitFormulaEditor(e.shiftKey ? "left" : "right");
1919
+ return;
1920
+ }
1921
  // ⛔ W54-T21: and NOTHING in this handler reads Escape, in any branch. The arbiter's listener
1922
  // is capture phase on the document and stops propagation, so a branch here could never fire
1923
  // anyway - it would be dead code that a later reader would trust.
 
1941
 
1942
  /**
1943
  * ⭐⭐ CR-1/CR-5/CR-10/PM-6 — EVERY CELL A LIVE REFERENCE TOUCHES, KEYED BY ITS REAL 1-BASED
1944
+ * `"col,row"` ADDRESS, TO ITS COLOUR AND REFERENCE ORDINAL. `refsIn` already scans the draft
1945
+ * on every keystroke (CR-10: "recolour on every keystroke"), and since a point-mode proposal is spliced
1946
  * into the SAME draft text as any other reference (`proposeCell` above), the proposal gets its
1947
  * border for free through this one map -- PM-6 needs no separate mechanism.
1948
  *
1949
+ * W59-T05 / INSTRUCTION 17 / R7: ONE OUTER PERIMETER PER REFERENCE. Each cell paints only
1950
+ * edges whose neighbour belongs to a different reference or none. Reference ordinals keep
1951
+ * touching ranges separate even when their slot colours repeat; no interior fill is added.
1952
  *
1953
  * ⭐⭐ W53-T02 / INSTRUCTION 18 — RANGE FINDER ALSO FIRES ON A BARE SELECTION. Microsoft's own
1954
  * page documents only the edit-mode trigger ("double-click the cell ... Excel highlights each
 
1959
  * (`paintRefBorder` further down) - there is no second outline mechanism to keep in step.
1960
  */
1961
  const formulaRefCells = useMemo(() => {
1962
+ const out = new Map<string, { color: string; ref: number }>();
1963
  const source = formulaEdit
1964
  ? formulaEdit.draft
1965
  : (selected?.cell?.kind === "formula" ? (selected.cell.formula ?? "") : "");
1966
  if (!source) return out;
1967
+ let refOrdinal = 0;
1968
  for (const ref of refsIn(source)) {
1969
+ const ordinal = refOrdinal++; // Count every reference, including ranges skipped by the cap.
1970
  let c0 = colToIndex(ref.start.col);
1971
  let c1 = colToIndex(ref.end.col);
1972
  let r0 = ref.start.row;
 
1983
  const color = colorForSlot(ref.colorIndex, "light");
1984
  for (let c = Math.min(c0, c1); c <= Math.max(c0, c1); c += 1) {
1985
  for (let r = Math.min(r0, r1); r <= Math.max(r0, r1); r += 1) {
1986
+ out.set(`${c},${r}`, { color, ref: ordinal });
1987
  }
1988
  }
1989
  }
 
2077
  */
2078
  const refPaintKey = useMemo(() => {
2079
  const parts: string[] = [];
2080
+ for (const [key, entry] of formulaRefCells) {
2081
+ parts.push(`${key}:${entry.color}:${formulaPointCells.has(key) ? "dash" : "solid"}:${entry.ref}`);
2082
  }
2083
  for (const key of formulaPointCells) {
2084
  if (!formulaRefCells.has(key)) parts.push(`${key}:none:dash`);
 
3813
  const cur = selection?.current;
3814
 
3815
  switch (hit) {
3816
+ // -- the four the canvas owns: extend-cell, go-home, page-up, page-down. ---------------
3817
+ // Unreachable while the table says `canvas`.
3818
+ case "extend-cell": case "go-home": case "page-up": case "page-down":
3819
  return;
3820
 
3821
  // -- moving and selecting -------------------------------------------------------------
 
3879
  if (!cur) return;
3880
  applySelection(rowBand(cur.cell[1], visCols.length), cur.cell);
3881
  return;
3882
+ case "select-all": {
3883
+ if (!cur) return;
3884
+ const anchor = { col: realCol(cur.cell[0]), row: realRow(cur.cell[1]) };
3885
+ const run = selectAllRunAt.current;
3886
+ const count = run && run.col === anchor.col && run.row === anchor.row
3887
+ ? run.count + 1 : 1;
3888
+ selectAllRunAt.current = { ...anchor, count };
3889
+ const region = selectAllTarget(anchor, extent, (c, r) => isFilled(tab, c, r), count);
3890
+ selectAllNav.current = true;
3891
+ applySelection({
3892
+ col0: viewIndexOf(visCols, region.col0), row0: viewRowOf(region.row0),
3893
+ col1: viewIndexOf(visCols, region.col1), row1: viewRowOf(region.row1),
3894
+ }, cur.cell);
3895
+ return;
3896
+ }
3897
  case "select-region": {
3898
  if (!cur) return;
3899
  const region = currentRegion({ col: realCol(cur.cell[0]), row: realRow(cur.cell[1]) },
 
4234
  // same reference's slot colour, which is the state instruction 18 describes. The colour is
4235
  // what tells it apart from the copy marquee's own dash further down.
4236
  const refKey = `${realCol(col) + 1},${realRow(row) + 1}`;
4237
+ const refEntry = formulaRefCells.get(refKey);
4238
  const refProposed = formulaPointCells.has(refKey);
4239
  const paintRefBorder = () => {
4240
+ if (!refEntry) return;
4241
+ const sameRef = (dc: number, dr: number) =>
4242
+ formulaRefCells.get(`${realCol(col) + 1 + dc},${realRow(row) + 1 + dr}`)?.ref === refEntry.ref;
4243
  ctx.save();
4244
+ ctx.strokeStyle = refEntry.color;
4245
  ctx.lineWidth = 2;
4246
  if (refProposed) ctx.setLineDash([4, 3]);
4247
+ ctx.beginPath();
4248
+ if (!sameRef(-1, 0)) {
4249
+ ctx.moveTo(rect.x + 1, rect.y);
4250
+ ctx.lineTo(rect.x + 1, rect.y + rect.height);
4251
+ }
4252
+ if (!sameRef(1, 0)) {
4253
+ ctx.moveTo(rect.x + rect.width - 1, rect.y);
4254
+ ctx.lineTo(rect.x + rect.width - 1, rect.y + rect.height);
4255
+ }
4256
+ if (!sameRef(0, -1)) {
4257
+ ctx.moveTo(rect.x, rect.y + 1);
4258
+ ctx.lineTo(rect.x + rect.width, rect.y + 1);
4259
+ }
4260
+ if (!sameRef(0, 1)) {
4261
+ ctx.moveTo(rect.x, rect.y + rect.height - 1);
4262
+ ctx.lineTo(rect.x + rect.width, rect.y + rect.height - 1);
4263
+ }
4264
+ ctx.stroke();
4265
  ctx.setLineDash([]);
4266
  ctx.restore();
4267
  };
 
4684
 
4685
  <div
4686
  className="sheet-grid-canvas"
4687
+ onKeyDownCapture={(event) => {
4688
+ const dir = commitDirection(event);
4689
+ const from = selectionRef.current?.current?.cell;
4690
+ if (dir === null || formulaEdit || !from) return;
4691
+ overlayCommit.current = { dir, at: Date.now(), from: [from[0], from[1]] };
4692
+ }}
4693
  onPointerDownCapture={() => { pointerSelectingRef.current = true; }}
4694
  onPointerUpCapture={() => {
4695
  queueMicrotask(() => { pointerSelectingRef.current = false; });
web/src/sheet/SheetRail.tsx CHANGED
@@ -42,12 +42,14 @@ import "../styles/wave52/parity.css";
42
  // path row's seating is decided by weight rather than by emission order. See the file's header
43
  // for the two measured row heights that make the extra pixel necessary.
44
  import "../styles/wave53/sheet-rail.css";
 
45
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
46
  import { FolderMark, MenuLabel } from "../customer-grid/icons";
47
  import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
48
  import { StarIcon } from "../ui/icons";
49
  import { ConfirmDialog } from "../ui/ConfirmDialog";
50
  import ImportDialog from "./ImportDialog";
 
51
  import { ROOT_FOLDER_ID } from "./types";
52
  import type { SheetFolder, WorkbookRow } from "./types";
53
 
@@ -341,6 +343,7 @@ export default function SheetRail({
341
  * be ticking behind it. Unmounting is one of the poll's five terminal conditions.
342
  */
343
  const [importing, setImporting] = useState(false);
 
344
 
345
  /**
346
  * ⭐⭐ W53-T09 (owner instruction 20) — THE RIBBON'S IMPORT BUTTON IS THE SECOND DOOR ONTO THIS
@@ -922,6 +925,13 @@ export default function SheetRail({
922
  >
923
  <MenuLabel icon="upload" text="Import .xlsx" />
924
  </button>
 
 
 
 
 
 
 
925
  </>
926
  )}
927
  </AnchoredOverlay>
@@ -1140,6 +1150,13 @@ export default function SheetRail({
1140
  onOpened={(workbookId) => { setImporting(false); onOpen(workbookId); }}
1141
  />
1142
  ) : null}
 
 
 
 
 
 
 
1143
  </nav>
1144
  );
1145
  }
 
42
  // path row's seating is decided by weight rather than by emission order. See the file's header
43
  // for the two measured row heights that make the extra pixel necessary.
44
  import "../styles/wave53/sheet-rail.css";
45
+ import "../styles/wave59/templates.css";
46
  import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
47
  import { FolderMark, MenuLabel } from "../customer-grid/icons";
48
  import { SHARE_SHAPE, SHEET_SHAPE } from "../customer-grid/iconShapes";
49
  import { StarIcon } from "../ui/icons";
50
  import { ConfirmDialog } from "../ui/ConfirmDialog";
51
  import ImportDialog from "./ImportDialog";
52
+ import TemplateGallery from "./templates/TemplateGallery";
53
  import { ROOT_FOLDER_ID } from "./types";
54
  import type { SheetFolder, WorkbookRow } from "./types";
55
 
 
343
  * be ticking behind it. Unmounting is one of the poll's five terminal conditions.
344
  */
345
  const [importing, setImporting] = useState(false);
346
+ const [pickingTemplate, setPickingTemplate] = useState(false);
347
 
348
  /**
349
  * ⭐⭐ W53-T09 (owner instruction 20) — THE RIBBON'S IMPORT BUTTON IS THE SECOND DOOR ONTO THIS
 
925
  >
926
  <MenuLabel icon="upload" text="Import .xlsx" />
927
  </button>
928
+ <button
929
+ type="button"
930
+ role="menuitem"
931
+ onClick={() => { setCreateAt(null); setPickingTemplate(true); }}
932
+ >
933
+ <MenuLabel icon={<SheetMark size={16} />} text="From a template" />
934
+ </button>
935
  </>
936
  )}
937
  </AnchoredOverlay>
 
1150
  onOpened={(workbookId) => { setImporting(false); onOpen(workbookId); }}
1151
  />
1152
  ) : null}
1153
+ {pickingTemplate ? (
1154
+ <TemplateGallery
1155
+ open
1156
+ onCancel={() => setPickingTemplate(false)}
1157
+ onOpened={(workbookId) => { setPickingTemplate(false); onOpen(workbookId); }}
1158
+ />
1159
+ ) : null}
1160
  </nav>
1161
  );
1162
  }
web/src/sheet/ribbonIcons.tsx CHANGED
@@ -22,6 +22,74 @@ export function IconPaste() {
22
  );
23
  }
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  /** Two handle loops and the crossing blades. */
26
  export function IconCut() {
27
  return (
 
22
  );
23
  }
24
 
25
+ /** Chart shortcuts share the ribbon's 16 by 16 drawing vocabulary. */
26
+ export function IconChartColumn() {
27
+ return (
28
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
29
+ <path d="M2 13.5h12M3.5 11.5v-5h2v5M7 11.5v-9h2v9M10.5 11.5v-7h2v7" />
30
+ </svg>
31
+ );
32
+ }
33
+
34
+ export function IconChartBar() {
35
+ return (
36
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
37
+ <path d="M2.5 2v12M4.5 3.5h7v2h-7M4.5 7h9v2h-9M4.5 10.5h5v2h-5" />
38
+ </svg>
39
+ );
40
+ }
41
+
42
+ export function IconChartLine() {
43
+ return (
44
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
45
+ <path d="M2 2.5v11h12M4 10l3-4 3 2 3-5" />
46
+ </svg>
47
+ );
48
+ }
49
+
50
+ export function IconChartArea() {
51
+ return (
52
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
53
+ <path d="M2 13.5h12M3.5 11.5V9l3-4 3 2 3-4v8.5z" fill="currentColor" fillOpacity="0.18" />
54
+ </svg>
55
+ );
56
+ }
57
+
58
+ export function IconChartPie() {
59
+ return (
60
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
61
+ <path d="M7 2.5a5.5 5.5 0 1 0 6.5 6.5H7zM9 1.5V7h5.5A5.5 5.5 0 0 0 9 1.5z" />
62
+ </svg>
63
+ );
64
+ }
65
+
66
+ export function IconChartDonut() {
67
+ return (
68
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
69
+ <circle cx="8" cy="8" r="5.5" />
70
+ <circle cx="8" cy="8" r="2.5" />
71
+ <path d="M8 2.5v3M10.5 8h3" />
72
+ </svg>
73
+ );
74
+ }
75
+
76
+ export function IconChartScatter() {
77
+ return (
78
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
79
+ <path d="M2 2.5v11h12" />
80
+ <path className="sheet-chart-kind-dots" d="M4.5 10h0M7 7h0M9 9h0M10.5 4h0M13 6h0" />
81
+ </svg>
82
+ );
83
+ }
84
+
85
+ export function IconChartRecommended() {
86
+ return (
87
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon sheet-chart-kind-icon">
88
+ <path d="M2 13.5h12M3.5 11V7M7 11V4M10.5 11V8M9 3.5l1.5 1.5 3-3" />
89
+ </svg>
90
+ );
91
+ }
92
+
93
  /** Two handle loops and the crossing blades. */
94
  export function IconCut() {
95
  return (
web/src/sheet/ribbonInsert.tsx CHANGED
@@ -54,6 +54,11 @@
54
  import { useState } from "react";
55
  import type { FormEvent } from "react";
56
  import type { RibbonTabContext } from "./Ribbon";
 
 
 
 
 
57
  // ⭐⭐ W54-T11 (ruling R5) — THE CHART GALLERY IS GONE AND A DIALOG STANDS WHERE IT STOOD. R5 reads
58
  // "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a database source is
59
  // a second tab in the same dialog. Ship both." A gallery of eight kinds cannot carry a second
@@ -90,7 +95,18 @@ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
90
  // imports its own. See the stylesheet's header for what it restates and why.
91
  import "../styles/wave54/ribbon-insert.css";
92
 
93
- const CHARTS = ["chart"] as const;
 
 
 
 
 
 
 
 
 
 
 
94
  const SPARKLINES = ["sparkline-line", "sparkline-column", "sparkline-winloss"] as const;
95
  const LINKS = ["link"] as const;
96
  const COMMENTS = ["comment"] as const;
@@ -169,9 +185,8 @@ function IconComment() {
169
  }
170
 
171
  /**
172
- * ⚠ `IconCaret` IS GONE WITH THE GALLERY (W54-T11). A caret says "a menu opens under this button",
173
- * and the Charts control now opens a centred modal instead; wearing the caret would have promised
174
- * the wrong surface. The two form popovers below never wore one.
175
  */
176
 
177
  // ═════════════════════════════════════════════════════════════════════════════════════════════
@@ -386,6 +401,13 @@ export const insertGroups = (ctx: RibbonTabContext) => {
386
  // oversight: the only menu this tab ever painted was the chart gallery, and the eight kinds are
387
  // buttons inside `ChartDialog` now. The shell still offers the helper to every tab.
388
  const { open, anchorEl, openPop, closePop, control, group, word, insert, act, openCellData } = ctx;
 
 
 
 
 
 
 
389
 
390
  /**
391
  * ⭐ THE ANCHOR CELL, IN SHEET COORDINATES. The door hands the selection over already translated
@@ -504,21 +526,41 @@ export const insertGroups = (ctx: RibbonTabContext) => {
504
  `styles/wave54/ribbon-insert.css`. */
505
  <fieldset className="sheet-ribbon-insert-fence" disabled={!insert}>
506
  {group("Charts", (
507
- <span className="sheet-ribbon-slot">
 
508
  {control("chart", "Chart", <><IconChart />{word("Chart")}</>,
509
- openPop("chart"), false, open === "chart", "C", "gallery")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  {/* ⚠ MOUNTED CONDITIONALLY, never rendered behind an `open` prop: `useOverlayLayer`
511
  claims Escape the moment it runs, so a hidden dialog would hold the key. The
512
  `insert` guard is belt and braces, and it is not the fieldset's job here: the
513
  dialog portals to the body and is therefore OUTSIDE the disabled fence. */}
514
- {open === "chart" && insert && (
515
  <ChartDialog
 
516
  selection={insert.selection}
 
517
  onClose={closePop}
518
  onCreate={createChart}
519
  />
520
  )}
521
- </span>
522
  ))}
523
 
524
  {/* ⭐ THREE CONTROLS RATHER THAN ONE WITH A GALLERY. Excel's Sparklines group is exactly
@@ -528,7 +570,7 @@ export const insertGroups = (ctx: RibbonTabContext) => {
528
  badge with no such attribute as a plain command and never descends; these three now open
529
  a popover, so they have to say so or the key tip would flash and land nowhere. */}
530
  {group("Sparklines", (
531
- <span className="sheet-ribbon-slot">
532
  {control("sparkline-line", "Line sparkline", <IconSparkLine />,
533
  openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")}
534
  {control("sparkline-column", "Column sparkline", <IconSparkColumn />,
@@ -559,7 +601,7 @@ export const insertGroups = (ctx: RibbonTabContext) => {
559
  ))}
560
 
561
  {group("Links", (
562
- <span className="sheet-ribbon-slot">
563
  {control("link", "Link", <><IconLink />{word("Link")}</>,
564
  openPop("link"), false, open === "link", "I", "gallery")}
565
  {/* ⚠ MOUNTED CONDITIONALLY AND OUTSIDE THE FIELDSET, for the two reasons the Charts
@@ -584,7 +626,7 @@ export const insertGroups = (ctx: RibbonTabContext) => {
584
  ))}
585
 
586
  {group("Comments", (
587
- <span className="sheet-ribbon-slot">
588
  {control("comment", "Comment", <><IconComment />{word("Comment")}</>,
589
  openPop("comment"), false, open === "comment", "M", "gallery")}
590
  {open === "comment" && (
@@ -628,13 +670,13 @@ export const insertGroups = (ctx: RibbonTabContext) => {
628
  )}
629
  </span>
630
  ))}
631
- {group("Cell data", control("cell-data", "Cell database", <>
632
  <svg viewBox="0 0 16 16" stroke="currentColor" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
633
  <ellipse cx="8" cy="3.5" rx="5" ry="2" />
634
  <path d="M3 3.5v9c0 1.1 2.2 2 5 2s5-.9 5-2v-9M3 8c0 1.1 2.2 2 5 2s5-.9 5-2" />
635
  </svg>
636
  {word("Cell database")}
637
- </>, openCellData, undefined, undefined, "D"))}
638
  </fieldset>
639
  );
640
  };
 
54
  import { useState } from "react";
55
  import type { FormEvent } from "react";
56
  import type { RibbonTabContext } from "./Ribbon";
57
+ import {
58
+ IconChartColumn, IconChartBar, IconChartLine, IconChartArea,
59
+ IconChartPie, IconChartDonut, IconChartScatter, IconChartRecommended,
60
+ } from "./ribbonIcons";
61
+ // W59-T08 adds shortcuts into the same dialog; chart creation still uses its single commit door.
62
  // ⭐⭐ W54-T11 (ruling R5) — THE CHART GALLERY IS GONE AND A DIALOG STANDS WHERE IT STOOD. R5 reads
63
  // "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a database source is
64
  // a second tab in the same dialog. Ship both." A gallery of eight kinds cannot carry a second
 
95
  // imports its own. See the stylesheet's header for what it restates and why.
96
  import "../styles/wave54/ribbon-insert.css";
97
 
98
+ const CHART_SHORTCUTS = [
99
+ { key: "chart-column", moreKey: "chart-column-choices", kind: "column", label: "Column", Icon: IconChartColumn, kt: "V" },
100
+ { key: "chart-bar", moreKey: "chart-bar-choices", kind: "bar", label: "Bar", Icon: IconChartBar, kt: "B" },
101
+ { key: "chart-line", moreKey: "chart-line-choices", kind: "line", label: "Line", Icon: IconChartLine, kt: "L" },
102
+ { key: "chart-area", moreKey: "chart-area-choices", kind: "area", label: "Area", Icon: IconChartArea, kt: "A" },
103
+ { key: "chart-pie", moreKey: "chart-pie-choices", kind: "pie", label: "Pie", Icon: IconChartPie, kt: "P" },
104
+ { key: "chart-donut", moreKey: "chart-donut-choices", kind: "donut", label: "Donut", Icon: IconChartDonut, kt: "O" },
105
+ { key: "chart-scatter", moreKey: "chart-scatter-choices", kind: "scatter", label: "Scatter", Icon: IconChartScatter, kt: "X" },
106
+ ] as const;
107
+ const CHARTS = [
108
+ "chart", ...CHART_SHORTCUTS.flatMap(({ key, moreKey }) => [key, moreKey]), "chart-recommended",
109
+ ] as const;
110
  const SPARKLINES = ["sparkline-line", "sparkline-column", "sparkline-winloss"] as const;
111
  const LINKS = ["link"] as const;
112
  const COMMENTS = ["comment"] as const;
 
185
  }
186
 
187
  /**
188
+ * The large Chart opener stays a single command. Chart-kind split controls use a separate
189
+ * choices half to open the same dialog at that kind, without inserting before confirmation.
 
190
  */
191
 
192
  // ═════════════════════════════════════════════════════════════════════════════════════════════
 
401
  // oversight: the only menu this tab ever painted was the chart gallery, and the eight kinds are
402
  // buttons inside `ChartDialog` now. The shell still offers the helper to every tab.
403
  const { open, anchorEl, openPop, closePop, control, group, word, insert, act, openCellData } = ctx;
404
+ const chartShortcut = CHART_SHORTCUTS.find(({ key, moreKey }) => open === key || open === moreKey);
405
+ const chartOpen = open === "chart" || open === "chart-recommended" || !!chartShortcut;
406
+ const chartCaret = (
407
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-caret">
408
+ <path d="m4.5 6.5 3.5 3 3.5-3" />
409
+ </svg>
410
+ );
411
 
412
  /**
413
  * ⭐ THE ANCHOR CELL, IN SHEET COORDINATES. The door hands the selection over already translated
 
526
  `styles/wave54/ribbon-insert.css`. */
527
  <fieldset className="sheet-ribbon-insert-fence" disabled={!insert}>
528
  {group("Charts", (
529
+ <>
530
+ <span className="sheet-ribbon-slot sheet-ribbon-insert-large">
531
  {control("chart", "Chart", <><IconChart />{word("Chart")}</>,
532
+ openPop("chart"), false, open === "chart", "C", "gallery", undefined, "dialog")}
533
+ </span>
534
+ <span className="sheet-chart-gallery">
535
+ {CHART_SHORTCUTS.map(({ key, moreKey, label, Icon, kt }) => (
536
+ <span className="sheet-chart-kind" key={key}>
537
+ {control(key, `${label} chart`, <Icon />,
538
+ openPop(key), false, open === key, kt, "gallery", undefined, "dialog")}
539
+ <span className="sheet-chart-kind-caret">
540
+ {control(moreKey, `${label} chart choices`, chartCaret,
541
+ openPop(moreKey), false, open === moreKey, undefined, "gallery", undefined, "dialog")}
542
+ </span>
543
+ </span>
544
+ ))}
545
+ <span className="sheet-chart-kind sheet-chart-kind-recommended">
546
+ {control("chart-recommended", "Recommended charts", <IconChartRecommended />,
547
+ openPop("chart-recommended"), false, open === "chart-recommended", "R", "gallery", undefined, "dialog")}
548
+ </span>
549
+ </span>
550
  {/* ⚠ MOUNTED CONDITIONALLY, never rendered behind an `open` prop: `useOverlayLayer`
551
  claims Escape the moment it runs, so a hidden dialog would hold the key. The
552
  `insert` guard is belt and braces, and it is not the fieldset's job here: the
553
  dialog portals to the body and is therefore OUTSIDE the disabled fence. */}
554
+ {chartOpen && insert && (
555
  <ChartDialog
556
+ key={open}
557
  selection={insert.selection}
558
+ initialKind={chartShortcut?.kind}
559
  onClose={closePop}
560
  onCreate={createChart}
561
  />
562
  )}
563
+ </>
564
  ))}
565
 
566
  {/* ⭐ THREE CONTROLS RATHER THAN ONE WITH A GALLERY. Excel's Sparklines group is exactly
 
570
  badge with no such attribute as a plain command and never descends; these three now open
571
  a popover, so they have to say so or the key tip would flash and land nowhere. */}
572
  {group("Sparklines", (
573
+ <span className="sheet-ribbon-slot sheet-ribbon-insert-stack">
574
  {control("sparkline-line", "Line sparkline", <IconSparkLine />,
575
  openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")}
576
  {control("sparkline-column", "Column sparkline", <IconSparkColumn />,
 
601
  ))}
602
 
603
  {group("Links", (
604
+ <span className="sheet-ribbon-slot sheet-ribbon-insert-large">
605
  {control("link", "Link", <><IconLink />{word("Link")}</>,
606
  openPop("link"), false, open === "link", "I", "gallery")}
607
  {/* ⚠ MOUNTED CONDITIONALLY AND OUTSIDE THE FIELDSET, for the two reasons the Charts
 
626
  ))}
627
 
628
  {group("Comments", (
629
+ <span className="sheet-ribbon-slot sheet-ribbon-insert-large">
630
  {control("comment", "Comment", <><IconComment />{word("Comment")}</>,
631
  openPop("comment"), false, open === "comment", "M", "gallery")}
632
  {open === "comment" && (
 
670
  )}
671
  </span>
672
  ))}
673
+ {group("Cell data", <span className="sheet-ribbon-insert-large">{control("cell-data", "Cell database", <>
674
  <svg viewBox="0 0 16 16" stroke="currentColor" fill="none" aria-hidden="true" className="sheet-ribbon-icon">
675
  <ellipse cx="8" cy="3.5" rx="5" ry="2" />
676
  <path d="M3 3.5v9c0 1.1 2.2 2 5 2s5-.9 5-2v-9M3 8c0 1.1 2.2 2 5 2s5-.9 5-2" />
677
  </svg>
678
  {word("Cell database")}
679
+ </>, openCellData, undefined, undefined, "D")}</span>)}
680
  </fieldset>
681
  );
682
  };
web/src/sheet/shortcuts.ts CHANGED
@@ -154,9 +154,9 @@ export const SHORTCUTS: readonly Shortcut[] = [
154
  {
155
  id: "select-all",
156
  keys: "Ctrl+A",
157
- action: "Select every cell on the sheet",
158
- when: "The grid has the keyboard",
159
- owner: "canvas",
160
  },
161
  {
162
  id: "select-column",
@@ -829,6 +829,27 @@ export const currentRegion = (
829
  };
830
  };
831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
832
  /** The rectangle Ctrl+Space means: one whole column, in whatever coordinates it was handed. */
833
  export const columnBand = (col: number, rows: number) => ({
834
  col0: col, col1: col, row0: 0, row1: Math.max(0, rows - 1),
 
154
  {
155
  id: "select-all",
156
  keys: "Ctrl+A",
157
+ action: "Select the current region, then the whole sheet on a second press",
158
+ when: "The grid has the keyboard. With no filled neighbours, select the whole sheet immediately",
159
+ owner: "sheet",
160
  },
161
  {
162
  id: "select-column",
 
829
  };
830
  };
831
 
832
+ /**
833
+ * W59-T02 / R4: Ctrl+A selects the current region first, then the whole sheet.
834
+ * A one-cell region goes straight to the sheet, even when the anchor itself is filled:
835
+ * it is the absence of filled neighbours that matters. Counts are one based; zero and
836
+ * negative counts use the first-press rule too. The region walk stays in {@link currentRegion}.
837
+ */
838
+ export const selectAllTarget = (
839
+ anchor: { col: number; row: number },
840
+ extent: { cols: number; rows: number },
841
+ filled: (col: number, row: number) => boolean,
842
+ pressCount: number,
843
+ ): SelectionRect => {
844
+ const sheet = {
845
+ col0: 0, row0: 0,
846
+ col1: Math.max(0, extent.cols - 1), row1: Math.max(0, extent.rows - 1),
847
+ };
848
+ if (pressCount >= 2) return sheet;
849
+ const region = currentRegion(anchor, extent, filled);
850
+ return region.col0 === region.col1 && region.row0 === region.row1 ? sheet : region;
851
+ };
852
+
853
  /** The rectangle Ctrl+Space means: one whole column, in whatever coordinates it was handed. */
854
  export const columnBand = (col: number, rows: number) => ({
855
  col0: col, col1: col, row0: 0, row1: Math.max(0, rows - 1),
web/src/sheet/templates/TemplateGallery.tsx ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
+ import { ConfirmDialog } from "../../ui/ConfirmDialog";
3
+ import { applySheetTemplate, fetchSheetTemplates } from "./templatesApi";
4
+ import { CONNECTORS_ROUTE } from "../../shell/nav";
5
+ import type { SheetTemplate } from "./types";
6
+
7
+ export default function TemplateGallery({ open, onCancel, onOpened }: {
8
+ open: boolean;
9
+ onCancel: () => void;
10
+ onOpened: (workbookId: string) => void;
11
+ }) {
12
+ const [templates, setTemplates] = useState<SheetTemplate[]>([]);
13
+ const [phase, setPhase] = useState<"loading" | "loaded" | "failed">("loading");
14
+ const [fetchError, setFetchError] = useState("");
15
+ const [selectedKey, setSelectedKey] = useState("");
16
+ const [database, setDatabase] = useState("");
17
+ const [applyError, setApplyError] = useState("");
18
+ const [busy, setBusy] = useState(false);
19
+ const requestRef = useRef<AbortController | null>(null);
20
+ const applyingRef = useRef(false);
21
+ const selected = templates.find((template) => template.key === selectedKey);
22
+ const canCreate = phase === "loaded" && Boolean(
23
+ selected?.databases.some((option) => option.key === database),
24
+ );
25
+
26
+ const load = useCallback(() => {
27
+ const controller = new AbortController();
28
+ requestRef.current = controller;
29
+ applyingRef.current = false;
30
+ setTemplates([]);
31
+ setPhase("loading");
32
+ setFetchError("");
33
+ setSelectedKey("");
34
+ setDatabase("");
35
+ setApplyError("");
36
+ setBusy(false);
37
+ void fetchSheetTemplates(controller.signal).then((result) => {
38
+ if (controller.signal.aborted) return;
39
+ if (!result.ok) {
40
+ setFetchError(result.message);
41
+ setPhase("failed");
42
+ return;
43
+ }
44
+ // Preselect, so the primary button is never a control that refuses. R8: a
45
+ // fake affordance is worse than no affordance.
46
+ const offered = result.value.filter((template) => template.databases.length > 0);
47
+ const first = offered[0];
48
+ setTemplates(offered);
49
+ if (first) {
50
+ setSelectedKey(first.key);
51
+ setDatabase(first.databases.find((option) => option.key === first.databaseHint)?.key
52
+ ?? first.databases[0].key);
53
+ }
54
+ setPhase("loaded");
55
+ });
56
+ return () => controller.abort();
57
+ }, []);
58
+
59
+ // ⭐ THE RETRY GOES THROUGH STATE, NOT THROUGH A SECOND CALL TO `load`. The effect owns the
60
+ // AbortController's cleanup, so a dialog closed mid retry aborts the request it started rather
61
+ // than leaking it and setting state after unmount.
62
+ const [reloadKey, setReloadKey] = useState(0);
63
+
64
+ useEffect(() => {
65
+ if (!open) return undefined;
66
+ return load();
67
+ }, [open, load, reloadKey]);
68
+
69
+ const createWorkbook = async () => {
70
+ const controller = requestRef.current;
71
+ if (!canCreate || !selected || applyingRef.current || !controller || controller.signal.aborted) return;
72
+ applyingRef.current = true;
73
+ setBusy(true);
74
+ setApplyError("");
75
+ try {
76
+ const result = await applySheetTemplate(selected.key, database);
77
+ if (controller.signal.aborted) return;
78
+ if (result.ok) onOpened(result.value.id);
79
+ else setApplyError(result.message);
80
+ } finally {
81
+ if (!controller.signal.aborted) {
82
+ applyingRef.current = false;
83
+ setBusy(false);
84
+ }
85
+ }
86
+ };
87
+
88
+ // ⛔ THE SHARED KIT HAS NO `confirmDisabled`, and reaching into `.lp-dialog` to disable its
89
+ // button imperatively was the first draft of this file. That fights React and pins this
90
+ // component to another component's DOM. Instead the PRIMARY ACTION CHANGES WITH THE PHASE, so
91
+ // the button always does the one thing that makes sense where the person is standing.
92
+ const primary = phase === "failed"
93
+ ? { label: "Try again", run: () => { setReloadKey((n) => n + 1); } }
94
+ : templates.length === 0 && phase === "loaded"
95
+ ? { label: "Connect a source",
96
+ run: () => { onCancel(); window.location.hash = "#/" + CONNECTORS_ROUTE; } }
97
+ : { label: "Create workbook", run: () => { void createWorkbook(); } };
98
+
99
+ return (
100
+ <ConfirmDialog
101
+ open={open}
102
+ title="Sheet templates"
103
+ confirmLabel={primary.label}
104
+ tone="primary"
105
+ busy={busy}
106
+ onConfirm={primary.run}
107
+ onCancel={onCancel}
108
+ body={
109
+ <div className="sheet-template-gallery" aria-busy={busy || phase === "loading"}>
110
+ {phase === "loading" ? (
111
+ <div className="sheet-template-list" role="status" aria-label="Loading templates">
112
+ {[0, 1, 2].map((row) => (
113
+ <div key={row} className="sheet-template-skeleton" aria-hidden="true">
114
+ <span className="sheet-template-skeleton-title" />
115
+ <span className="sheet-template-skeleton-answer" />
116
+ </div>
117
+ ))}
118
+ </div>
119
+ ) : phase === "failed" ? (
120
+ <p className="sheet-template-error" role="alert">{fetchError}</p>
121
+ ) : templates.length === 0 ? (
122
+ <p className="sheet-template-note">No connector has published a database yet.</p>
123
+ ) : (
124
+ <>
125
+ <div className="sheet-template-list" role="group" aria-label="Templates">
126
+ {templates.map((template) => (
127
+ <button
128
+ key={template.key}
129
+ type="button"
130
+ className="sheet-template-row"
131
+ aria-pressed={template.key === selectedKey}
132
+ disabled={busy}
133
+ onClick={() => {
134
+ setSelectedKey(template.key);
135
+ setDatabase(template.databases.find((option) => option.key === template.databaseHint)?.key
136
+ ?? template.databases[0].key);
137
+ setApplyError("");
138
+ }}
139
+ >
140
+ <span className="sheet-template-title" title={template.title}>{template.title}</span>
141
+ <span className="sheet-template-answer" title={template.answers}>{template.answers}</span>
142
+ </button>
143
+ ))}
144
+ </div>
145
+ {selected ? (
146
+ <label className="sheet-template-database">
147
+ <span>Database</span>
148
+ <select
149
+ className="sheet-template-select"
150
+ value={database}
151
+ disabled={busy}
152
+ onChange={(event) => { setDatabase(event.target.value); setApplyError(""); }}
153
+ >
154
+ {selected.databases.map((option) => (
155
+ <option key={option.key} value={option.key}>{option.label}</option>
156
+ ))}
157
+ </select>
158
+ </label>
159
+ ) : null}
160
+ <p className="sheet-template-error" role="alert">{applyError}</p>
161
+ </>
162
+ )}
163
+ </div>
164
+ }
165
+ />
166
+ );
167
+ }
web/src/sheet/templates/templatesApi.ts ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { API_V1, CREDENTIALS } from "../../apiContract";
2
+ import { normalizeCellBinding } from "../types";
3
+ import type { Result } from "../sheetApi";
4
+ import type { Workbook } from "../types";
5
+ import type { SheetTemplate, SheetTemplateDatabase } from "./types";
6
+
7
+ const object = (value: unknown): value is Record<string, unknown> =>
8
+ value !== null && typeof value === "object" && !Array.isArray(value);
9
+
10
+ const text = (value: unknown): value is string =>
11
+ typeof value === "string" && value.trim().length > 0;
12
+
13
+ const database = (value: unknown): value is SheetTemplateDatabase =>
14
+ object(value) && text(value.key) && text(value.label);
15
+
16
+ const template = (value: unknown): value is SheetTemplate =>
17
+ object(value) && text(value.key) && text(value.title) && text(value.answers) &&
18
+ text(value.source) && text(value.databaseHint) && Array.isArray(value.databases) &&
19
+ value.databases.every(database);
20
+
21
+ const workbook = (value: unknown): value is Workbook =>
22
+ object(value) && text(value.id) && text(value.name) &&
23
+ typeof value.rev === "number" && Number.isInteger(value.rev) && value.rev > 0 &&
24
+ (value.refreshed_at === null || typeof value.refreshed_at === "string") &&
25
+ Array.isArray(value.sheets) && value.sheets.length > 0 && value.sheets.every((tab: unknown) =>
26
+ object(tab) && text(tab.id) && text(tab.name) && object(tab.cells) &&
27
+ Object.entries(tab.cells).every(([addr, cell]) =>
28
+ /^[A-Z]+[1-9][0-9]*$/.test(addr) && object(cell) &&
29
+ typeof cell.kind === "string" && ["literal", "formula", "bound", "empty"].includes(cell.kind) &&
30
+ typeof cell.state === "string" && ["fresh", "stale", "typed", "refused"].includes(cell.state) &&
31
+ (cell.kind !== "formula" || text(cell.formula)) &&
32
+ (cell.kind !== "bound" || (object(cell.binding) && text(cell.binding.database) &&
33
+ object(cell.binding.scope) && object(cell.binding.aggregate) &&
34
+ typeof cell.binding.aggregate.fn === "string" &&
35
+ ["sum", "count", "avg", "min", "max"].includes(cell.binding.aggregate.fn) &&
36
+ (cell.binding.aggregate.fn === "count" || text(cell.binding.aggregate.field))))));
37
+
38
+ const normalizedWorkbook = (book: Workbook): Workbook => ({
39
+ ...book,
40
+ sheets: book.sheets.map((tab) => ({
41
+ ...tab,
42
+ cells: Object.fromEntries(Object.entries(tab.cells).map(([addr, cell]) => [addr,
43
+ cell.binding ? { ...cell, binding: normalizeCellBinding(cell.binding) } : cell,
44
+ ])),
45
+ })),
46
+ });
47
+
48
+ async function call<T>(
49
+ path: string,
50
+ init: RequestInit,
51
+ parse: (body: Record<string, unknown>) => T | null,
52
+ ): Promise<Result<T>> {
53
+ let response: Response;
54
+ try {
55
+ response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
56
+ } catch {
57
+ return { ok: false, status: 0, code: "unreachable", message: "Cannot reach the server." };
58
+ }
59
+ const body: unknown = await response.json().catch(() => null);
60
+ if (!response.ok) {
61
+ const detail = object(body) && object(body.detail) ? body.detail : body;
62
+ const error = object(detail) && object(detail.error) ? detail.error : null;
63
+ return {
64
+ ok: false, status: response.status,
65
+ code: error && text(error.code) ? error.code : "unknown",
66
+ // Keep the server's sentence intact, including every missing field name.
67
+ message: error && text(error.message) ? error.message : "The sheet template request failed.",
68
+ };
69
+ }
70
+ const value = object(body) ? parse(body) : null;
71
+ return value === null
72
+ ? { ok: false, status: response.status, code: "invalid_response",
73
+ message: "The server returned an invalid sheet template response." }
74
+ : { ok: true, value };
75
+ }
76
+
77
+ export const fetchSheetTemplates = (signal?: AbortSignal): Promise<Result<SheetTemplate[]>> =>
78
+ call("/sheet-templates", { method: "GET", signal }, (body) =>
79
+ Array.isArray(body.templates) ? body.templates.filter(template) : null);
80
+
81
+ export const applySheetTemplate = (
82
+ key: string, database: string, name?: string,
83
+ ): Promise<Result<Workbook>> =>
84
+ call(`/sheet-templates/${encodeURIComponent(key)}/apply`, {
85
+ method: "POST", headers: { "Content-Type": "application/json" },
86
+ body: JSON.stringify({ database, ...(name === undefined ? {} : { name }) }),
87
+ }, (body) => workbook(body.workbook) ? normalizedWorkbook(body.workbook) : null);
web/src/sheet/templates/types.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface SheetTemplateDatabase {
2
+ key: string;
3
+ label: string;
4
+ }
5
+
6
+ export interface SheetTemplate {
7
+ key: string;
8
+ title: string;
9
+ answers: string;
10
+ source: string;
11
+ databaseHint: string;
12
+ databases: SheetTemplateDatabase[];
13
+ }
web/src/shell/LoginPage.tsx CHANGED
@@ -22,71 +22,12 @@
22
  import { useEffect, useRef, useState } from "react";
23
  import type { FormEvent } from "react";
24
  import { Brand } from "./Brand";
25
- import { changePassword, login, mfaEnrollConfirm, mfaEnrollStart, passwordPolicy } from "./session";
26
- import type { LoginOutcome, MFASetup, PasswordPolicy, SessionUser } from "./session";
27
- import { useEscapeClose } from "../ui/useEscapeClose";
28
  import "../styles/wave57/login-mfa.css";
29
 
30
- type Step = "credentials" | "expired" | "mfa" | "enrol" | "codes";
31
- type IssuedCodes = { user: SessionUser; recoveryCodes: string[] };
32
-
33
- /** W57-T36 / C12: one show-once treatment in both doors. Copy is a quiet,
34
- * explicit export to the person's clipboard, never persistence on their behalf.
35
- * Only the acknowledgement can dismiss this surface; Escape names what remains.
36
- * Browser reload/close can only be warned about, never made impossible by a page. */
37
- export function RecoveryCodes({ codes, onSaved, onError }: {
38
- codes: string[];
39
- onSaved: () => void;
40
- onError: (message: string) => void;
41
- }) {
42
- const [copied, setCopied] = useState<boolean>(false);
43
- const [copying, setCopying] = useState<boolean>(false);
44
- useEscapeClose(true, () => onError("Save your recovery codes before continuing."));
45
- useEffect(() => {
46
- const warn = (event: BeforeUnloadEvent) => {
47
- event.preventDefault();
48
- event.returnValue = "";
49
- };
50
- window.addEventListener("beforeunload", warn);
51
- return () => window.removeEventListener("beforeunload", warn);
52
- }, []);
53
-
54
- async function copy() {
55
- if (copying) return;
56
- setCopying(true);
57
- try {
58
- await navigator.clipboard.writeText(codes.join("\n"));
59
- setCopied(true);
60
- onError("");
61
- } catch {
62
- setCopied(false);
63
- onError("Copy did not work. Select the codes and copy them manually.");
64
- } finally {
65
- setCopying(false);
66
- }
67
- }
68
-
69
- return (
70
- <>
71
- <p className="login-mfa-help">This screen is the only place these recovery codes will ever be shown.</p>
72
- <p className="login-mfa-help">Save them somewhere safe; each code works once if you lose your authenticator.</p>
73
- <ul className="login-mfa-codes" aria-label="Recovery codes">
74
- {codes.map((code) => <li key={code}><code>{code}</code></li>)}
75
- </ul>
76
- <div className="login-mfa-copy-row">
77
- <button type="button" className="login-mfa-quiet" onClick={() => void copy()} disabled={copying}>
78
- {copying ? "Copying…" : "Copy codes"}
79
- </button>
80
- <span className="login-mfa-copy-status" role="status">{copied ? "Copied" : ""}</span>
81
- </div>
82
- {/* A type=button acknowledgement cannot be submitted by Enter left over
83
- from the previous code field. There is no Back or secondary exit. */}
84
- <button type="button" className="login-submit" onClick={onSaved} disabled={copying}>
85
- I have saved these codes
86
- </button>
87
- </>
88
- );
89
- }
90
 
91
  /** The reveal toggle the host's password field ships natively (BaseWeb's eye).
92
  * Two doors, one affordance. */
@@ -110,8 +51,6 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
110
  const [newPassword, setNewPassword] = useState<string>("");
111
  const [confirmPassword, setConfirmPassword] = useState<string>("");
112
  const [code, setCode] = useState<string>("");
113
- const [setup, setSetup] = useState<MFASetup | null>(null);
114
- const [issued, setIssued] = useState<IssuedCodes | null>(null);
115
  const [policy, setPolicy] = useState<PasswordPolicy | null>(null);
116
  const [policyLoading, setPolicyLoading] = useState<boolean>(false);
117
  const flight = useRef<boolean>(false);
@@ -136,21 +75,12 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
136
  // the new task to assistive tech, and focus the heading rather than a submit.
137
  useEffect(() => { stepHeading.current?.focus(); }, [step]);
138
 
139
- async function startEnrolment(currentPassword: string) {
140
- setSetup(null);
141
- setCode("");
142
- const result = await mfaEnrollStart(username, currentPassword);
143
- if (result.ok === false) setError(result.message);
144
- else setSetup({ secret: result.secret, otpauthUri: result.otpauthUri, issuer: result.issuer });
145
- }
146
-
147
  /** Correct credentials must survive a challenge. Clearing the password on
148
  * every 401 would make the second-factor POST an invalid-credentials loop.
149
  * It stays only in this mounted tree, and leaves with success or Back. */
150
- async function accept(result: LoginOutcome, currentPassword: string) {
151
  if (result.ok === true) {
152
  setPassword("");
153
- setSetup(null);
154
  setCode("");
155
  onSignedIn(result.user);
156
  return;
@@ -160,18 +90,15 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
160
  case "password_expired":
161
  setPolicyLoading(true);
162
  setStep("expired");
163
- setSetup(null);
164
  setCode("");
165
  break;
166
  case "mfa_required":
167
  case "mfa_invalid":
168
  setStep("mfa");
169
- setSetup(null);
170
  setCode("");
171
  break;
172
  case "mfa_enrolment_required":
173
  setStep("enrol");
174
- await startEnrolment(currentPassword);
175
  break;
176
  default:
177
  // Keep the current challenge on network/backoff errors so retry uses
@@ -182,7 +109,7 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
182
 
183
  async function submit(e: FormEvent) {
184
  e.preventDefault();
185
- if (flight.current || step === "codes") return;
186
  flight.current = true;
187
  setBusy(true);
188
  setError("");
@@ -203,26 +130,9 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
203
  setNewPassword("");
204
  setConfirmPassword("");
205
  setStep("credentials");
206
- await accept(await login(username, newPassword), newPassword);
207
- } else if (step === "enrol") {
208
- if (!setup) {
209
- await startEnrolment(password);
210
- return;
211
- }
212
- const confirmed = await mfaEnrollConfirm(username, password, setup.secret, code);
213
- if (confirmed.ok === false) {
214
- setError(confirmed.message);
215
- return;
216
- }
217
- // The server has minted a cookie, but this component does NOT open the
218
- // frame yet. C12 requires the person to save this one clear response.
219
- setIssued({ user: confirmed.user, recoveryCodes: confirmed.recoveryCodes });
220
- setSetup(null);
221
- setPassword("");
222
- setCode("");
223
- setStep("codes");
224
  } else {
225
- await accept(await login(username, password, step === "mfa" ? code : undefined), password);
226
  }
227
  } finally {
228
  flight.current = false;
@@ -231,14 +141,12 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
231
  }
232
 
233
  function back() {
234
- if (flight.current || step === "codes") return;
235
  setStep("credentials");
236
  setPassword("");
237
  setNewPassword("");
238
  setConfirmPassword("");
239
  setCode("");
240
- setSetup(null);
241
- setIssued(null);
242
  setReveal(false);
243
  setError("");
244
  }
@@ -272,14 +180,21 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
272
  ⚠ No dash of any kind (R6). A slogan is exactly where an em dash wants to appear. */}
273
  <p className="login-tagline">Every workflow, automated.</p>
274
 
275
- {/* One card and one anchor across all five steps. The extra content
276
  grows downward; no alternate width, position or brand lockup. */}
277
- {step !== "credentials" ? (
278
  <h2 className="login-mfa-heading" ref={stepHeading} tabIndex={-1}>
279
- {step === "expired" ? "New password" : step === "mfa" ? "Two step sign in"
280
- : step === "enrol" ? "Authenticator setup" : "Recovery codes"}
281
  </h2>
282
  ) : null}
 
 
 
 
 
 
 
 
283
  <form className="login-form" onSubmit={submit} noValidate>
284
  {step === "credentials" ? (
285
  <>
@@ -373,45 +288,14 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
373
  </>
374
  ) : null}
375
 
376
- {step === "enrol" ? (
377
- <>
378
- {/* Manual setup is deliberate: the pinned dependency set has no
379
- QR encoder, and T36 adds no dependency or external QR service. */}
380
- <p className="login-mfa-help">Type this setup code into any authenticator app.</p>
381
- {setup ? (
382
- <>
383
- <span className="login-mfa-label">{setup.issuer} setup code</span>
384
- <code className="login-mfa-secret">{setup.secret.match(/.{1,4}/g)?.join(" ")}</code>
385
- <span className="login-mfa-label">Authenticator setup link</span>
386
- <code className="login-mfa-uri">{setup.otpauthUri}</code>
387
- <label className="login-mfa-label" htmlFor="login-enrol-code">First authenticator code</label>
388
- <input id="login-enrol-code" className="login-input" type="text" inputMode="numeric"
389
- autoComplete="one-time-code" maxLength={6} value={code} onChange={edit(setCode)}
390
- disabled={busy} aria-invalid={error ? true : undefined} aria-describedby="login-message" />
391
- </>
392
- ) : <p className="login-mfa-help">{busy ? "Preparing your setup code…" : "Try setup again to get a code."}</p>}
393
- </>
394
- ) : null}
395
-
396
- {step === "codes" && issued ? (
397
- <RecoveryCodes codes={issued.recoveryCodes} onError={setError} onSaved={() => {
398
- const user = issued.user;
399
- setIssued(null);
400
- onSignedIn(user);
401
- }} />
402
- ) : null}
403
-
404
  {/* Disabled through THREE channels (the real attribute, the cursor and
405
  the opacity), never opacity alone — a control that only looks dead
406
  is a control that still takes the click. */}
407
- {step !== "codes" ? (
408
- <button className="login-submit" type="submit" disabled={busy}>
409
- {busy ? (step === "expired" ? "Updating password…" : step === "enrol" ? "Setting up…" : "Signing in…")
410
- : step === "expired" ? "Set new password" : step === "enrol" ? (setup ? "Confirm setup" : "Try setup again")
411
- : step === "mfa" ? "Verify and sign in" : "Log in"}
412
- </button>
413
- ) : null}
414
- {step !== "credentials" && step !== "codes" ? (
415
  <button type="button" className="login-mfa-quiet login-mfa-back" disabled={busy} onClick={back}>
416
  Back to sign in
417
  </button>
@@ -424,6 +308,8 @@ export default function LoginPage({ onSignedIn }: { onSignedIn: (user: SessionUs
424
  <p className="login-msg" id="login-message" role="status" aria-live="polite">
425
  {error}
426
  </p>
 
 
427
  </div>
428
  </div>
429
  );
 
22
  import { useEffect, useRef, useState } from "react";
23
  import type { FormEvent } from "react";
24
  import { Brand } from "./Brand";
25
+ import { changePassword, login, passwordPolicy } from "./session";
26
+ import type { LoginOutcome, PasswordPolicy, SessionUser } from "./session";
27
+ import SecurityPane from "../settings/SecurityPane";
28
  import "../styles/wave57/login-mfa.css";
29
 
30
+ type Step = "credentials" | "expired" | "mfa" | "enrol";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  /** The reveal toggle the host's password field ships natively (BaseWeb's eye).
33
  * Two doors, one affordance. */
 
51
  const [newPassword, setNewPassword] = useState<string>("");
52
  const [confirmPassword, setConfirmPassword] = useState<string>("");
53
  const [code, setCode] = useState<string>("");
 
 
54
  const [policy, setPolicy] = useState<PasswordPolicy | null>(null);
55
  const [policyLoading, setPolicyLoading] = useState<boolean>(false);
56
  const flight = useRef<boolean>(false);
 
75
  // the new task to assistive tech, and focus the heading rather than a submit.
76
  useEffect(() => { stepHeading.current?.focus(); }, [step]);
77
 
 
 
 
 
 
 
 
 
78
  /** Correct credentials must survive a challenge. Clearing the password on
79
  * every 401 would make the second-factor POST an invalid-credentials loop.
80
  * It stays only in this mounted tree, and leaves with success or Back. */
81
+ async function accept(result: LoginOutcome) {
82
  if (result.ok === true) {
83
  setPassword("");
 
84
  setCode("");
85
  onSignedIn(result.user);
86
  return;
 
90
  case "password_expired":
91
  setPolicyLoading(true);
92
  setStep("expired");
 
93
  setCode("");
94
  break;
95
  case "mfa_required":
96
  case "mfa_invalid":
97
  setStep("mfa");
 
98
  setCode("");
99
  break;
100
  case "mfa_enrolment_required":
101
  setStep("enrol");
 
102
  break;
103
  default:
104
  // Keep the current challenge on network/backoff errors so retry uses
 
109
 
110
  async function submit(e: FormEvent) {
111
  e.preventDefault();
112
+ if (flight.current) return;
113
  flight.current = true;
114
  setBusy(true);
115
  setError("");
 
130
  setNewPassword("");
131
  setConfirmPassword("");
132
  setStep("credentials");
133
+ await accept(await login(username, newPassword));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  } else {
135
+ await accept(await login(username, password, step === "mfa" ? code : undefined));
136
  }
137
  } finally {
138
  flight.current = false;
 
141
  }
142
 
143
  function back() {
144
+ if (flight.current) return;
145
  setStep("credentials");
146
  setPassword("");
147
  setNewPassword("");
148
  setConfirmPassword("");
149
  setCode("");
 
 
150
  setReveal(false);
151
  setError("");
152
  }
 
180
  ⚠ No dash of any kind (R6). A slogan is exactly where an em dash wants to appear. */}
181
  <p className="login-tagline">Every workflow, automated.</p>
182
 
183
+ {/* One card and one anchor across every step. The extra content
184
  grows downward; no alternate width, position or brand lockup. */}
185
+ {step === "expired" || step === "mfa" ? (
186
  <h2 className="login-mfa-heading" ref={stepHeading} tabIndex={-1}>
187
+ {step === "expired" ? "New password" : "Two step sign in"}
 
188
  </h2>
189
  ) : null}
190
+ {step === "enrol" ? (
191
+ <SecurityPane gate={{ username, password, onBack: back, onEnrolled: (user) => {
192
+ setPassword("");
193
+ setCode("");
194
+ onSignedIn(user);
195
+ } }} />
196
+ ) : (
197
+ <>
198
  <form className="login-form" onSubmit={submit} noValidate>
199
  {step === "credentials" ? (
200
  <>
 
288
  </>
289
  ) : null}
290
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  {/* Disabled through THREE channels (the real attribute, the cursor and
292
  the opacity), never opacity alone — a control that only looks dead
293
  is a control that still takes the click. */}
294
+ <button className="login-submit" type="submit" disabled={busy}>
295
+ {busy ? (step === "expired" ? "Updating password…" : "Signing in…")
296
+ : step === "expired" ? "Set new password" : step === "mfa" ? "Verify and sign in" : "Log in"}
297
+ </button>
298
+ {step !== "credentials" ? (
 
 
 
299
  <button type="button" className="login-mfa-quiet login-mfa-back" disabled={busy} onClick={back}>
300
  Back to sign in
301
  </button>
 
308
  <p className="login-msg" id="login-message" role="status" aria-live="polite">
309
  {error}
310
  </p>
311
+ </>
312
+ )}
313
  </div>
314
  </div>
315
  );
web/src/shell/Shell.tsx CHANGED
@@ -315,6 +315,11 @@ function ApplicationWizard({
315
  const [schema, setSchema] = useState<WizardLoad<SchemaPayload>>({ phase: "idle" });
316
  const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
317
  const [name, setName] = useState("");
 
 
 
 
 
318
  const [busy, setBusy] = useState(false);
319
  const [error, setError] = useState("");
320
  const schemaGeneration = useRef(0);
@@ -370,8 +375,43 @@ function ApplicationWizard({
370
  return () => { schemaGeneration.current += 1; };
371
  }, [sourceDatabase]);
372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  useApplicationWizardOverlay(panelRef, onClose);
374
 
 
 
 
 
 
 
375
  const template = templates.phase === "ready"
376
  ? templates.value.find((candidate) => candidate.kind === templateKind) ?? null
377
  : null;
@@ -393,7 +433,9 @@ function ApplicationWizard({
393
  ? !!sourceDatabase && schema.phase === "ready"
394
  : step === 2
395
  ? !missingRequired && !coordinatePairError && !routeLocationError
396
- : !!name.trim();
 
 
397
 
398
  const chooseTemplate = (candidate: ApplicationTemplate) => {
399
  setTemplateKind(candidate.kind);
@@ -429,6 +471,27 @@ function ApplicationWizard({
429
  body?.detail?.message ?? body?.detail ?? "The Application was not saved.",
430
  ));
431
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  onCreated(body.application as CreatedTemplateApplication);
433
  } catch (reason: unknown) {
434
  setError(reason instanceof Error ? reason.message : "The Application was not saved.");
@@ -437,7 +500,7 @@ function ApplicationWizard({
437
  }
438
  };
439
 
440
- const headings = ["Choose a template", "Choose a database", "Map the fields", "Review and create"];
441
  return (
442
  <div className="shell-newdb-scrim">
443
  <div
@@ -457,7 +520,7 @@ function ApplicationWizard({
457
  </button>
458
  </header>
459
  <ol className="app-wizard-steps" aria-label="Application setup progress">
460
- {["Template", "Database", "Fields", "Review"].map((label, index) => (
461
  <li key={label} className={index === step ? "is-current" : index < step ? "is-done" : ""}
462
  aria-current={index === step ? "step" : undefined}>
463
  <span>{index + 1}</span>{label}
@@ -551,7 +614,83 @@ function ApplicationWizard({
551
  </div>
552
  ) : null}
553
 
554
- {step === 3 && template ? (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
555
  <div className="app-wizard-review">
556
  <label className="app-wizard-field">
557
  <span>Application name</span>
@@ -560,6 +699,9 @@ function ApplicationWizard({
560
  <dl>
561
  <div><dt>Template</dt><dd>{template.label}</dd></div>
562
  <div><dt>Database</dt><dd>{schema.phase === "ready" ? schema.value.label : sourceDatabase}</dd></div>
 
 
 
563
  {template.fieldRoles.filter((role) => fieldMap[role.key]).map((role) => (
564
  <div key={role.key}><dt>{role.label}</dt><dd>{
565
  schema.phase === "ready"
@@ -583,7 +725,7 @@ function ApplicationWizard({
583
  {step > 0 ? (
584
  <button type="button" className="app-wizard-secondary" onClick={() => { setStep((current) => current - 1); setError(""); }} disabled={busy}>Back</button>
585
  ) : null}
586
- {step < 3 ? (
587
  <button type="button" className="login-submit" disabled={!canContinue || busy}
588
  onClick={() => { setStep((current) => current + 1); setError(""); }}>Continue</button>
589
  ) : (
@@ -611,8 +753,8 @@ import type { Inbox } from "../alerts/alertsModel";
611
  // dispatcher is a switch over two literals rather than a second copy of the route table.
612
  import { retryEmit, routeForTarget } from "../inbox/inboxModel";
613
  import ShareDialog from "./ShareDialog";
614
- import { SHARE_OPEN_EVENT, parseShareRequest } from "./shareModel";
615
- import type { ShareRequest } from "./shareModel";
616
  // WAVE 19 R8 — the chosen database mark. Read-only across the session fence.
617
  import { isAdmin, logout, me } from "./session";
618
  import type { SessionUser } from "./session";
 
315
  const [schema, setSchema] = useState<WizardLoad<SchemaPayload>>({ phase: "idle" });
316
  const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
317
  const [name, setName] = useState("");
318
+ const [shareEntries, setShareEntries] = useState<ShareEntry[]>([]);
319
+ const [sharePeople, setSharePeople] = useState<SharePerson[]>([]);
320
+ const [shareQuery, setShareQuery] = useState("");
321
+ const [sharePickRole, setSharePickRole] = useState<ShareRole>("view");
322
+ const [shareLoadPhase, setShareLoadPhase] = useState<"idle" | "loading" | "ready">("idle");
323
  const [busy, setBusy] = useState(false);
324
  const [error, setError] = useState("");
325
  const schemaGeneration = useRef(0);
 
375
  return () => { schemaGeneration.current += 1; };
376
  }, [sourceDatabase]);
377
 
378
+ useEffect(() => {
379
+ const controller = new AbortController();
380
+ setShareEntries([]);
381
+ setSharePeople([]);
382
+ setShareQuery("");
383
+ setSharePickRole("view");
384
+ if (!sourceDatabase) {
385
+ setShareLoadPhase("idle");
386
+ return () => controller.abort();
387
+ }
388
+ setShareLoadPhase("loading");
389
+ void fetch(`${API_V1}/share/database/${encodeURIComponent(sourceDatabase)}`, {
390
+ credentials: CREDENTIALS,
391
+ signal: controller.signal,
392
+ }).then(async (response) => {
393
+ const body = await response.json().catch(() => ({}));
394
+ if (!controller.signal.aborted) {
395
+ setSharePeople(response.ok ? parseShare(body).people : []);
396
+ setShareLoadPhase("ready");
397
+ }
398
+ }).catch(() => {
399
+ if (!controller.signal.aborted) {
400
+ setSharePeople([]);
401
+ setShareLoadPhase("ready");
402
+ }
403
+ });
404
+ return () => controller.abort();
405
+ }, [sourceDatabase]);
406
+
407
  useApplicationWizardOverlay(panelRef, onClose);
408
 
409
+ const shareOptions = addablePeople(sharePeople, shareEntries);
410
+ const shareRecipient = resolveShareRecipient(sharePeople, shareEntries, shareQuery);
411
+ const canAddEveryone = !shareEntries.some((entry) => entry.user === EVERYONE);
412
+ const shareNameOf = (user: string) => user === EVERYONE
413
+ ? EVERYONE_LABEL
414
+ : sharePeople.find((person) => person.user === user)?.name ?? user;
415
  const template = templates.phase === "ready"
416
  ? templates.value.find((candidate) => candidate.kind === templateKind) ?? null
417
  : null;
 
433
  ? !!sourceDatabase && schema.phase === "ready"
434
  : step === 2
435
  ? !missingRequired && !coordinatePairError && !routeLocationError
436
+ : step === 3
437
+ ? true
438
+ : !!name.trim();
439
 
440
  const chooseTemplate = (candidate: ApplicationTemplate) => {
441
  setTemplateKind(candidate.kind);
 
471
  body?.detail?.message ?? body?.detail ?? "The Application was not saved.",
472
  ));
473
  }
474
+ if (shareEntries.length > 0) {
475
+ try {
476
+ const shareResponse = await fetch(`${API_V1}/nav/applications/${encodeURIComponent(body.application.id)}`, {
477
+ method: "PATCH",
478
+ credentials: CREDENTIALS,
479
+ headers: { "Content-Type": "application/json" },
480
+ body: JSON.stringify({
481
+ share: shareEntries.some((entry) => entry.user === EVERYONE)
482
+ ? { mode: "tenant", users: [] }
483
+ : { mode: "users", users: shareEntries.map((entry) => entry.user) },
484
+ }),
485
+ });
486
+ await shareResponse.json().catch(() => ({}));
487
+ if (!shareResponse.ok) throw new Error("Sharing did not save.");
488
+ } catch {
489
+ const sharingError = "The app was created, but sharing did not save. You can share it from the App module.";
490
+ setError(sharingError);
491
+ // Creation closes the wizard, so the shell must also carry the partial result.
492
+ window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: sharingError }));
493
+ }
494
+ }
495
  onCreated(body.application as CreatedTemplateApplication);
496
  } catch (reason: unknown) {
497
  setError(reason instanceof Error ? reason.message : "The Application was not saved.");
 
500
  }
501
  };
502
 
503
+ const headings = ["Choose a template", "Choose a database", "Map the fields", "Choose who can open it", "Review and create"];
504
  return (
505
  <div className="shell-newdb-scrim">
506
  <div
 
520
  </button>
521
  </header>
522
  <ol className="app-wizard-steps" aria-label="Application setup progress">
523
+ {["Template", "Database", "Fields", "Share", "Review"].map((label, index) => (
524
  <li key={label} className={index === step ? "is-current" : index < step ? "is-done" : ""}
525
  aria-current={index === step ? "step" : undefined}>
526
  <span>{index + 1}</span>{label}
 
614
  </div>
615
  ) : null}
616
 
617
+ {step === 3 ? (
618
+ shareLoadPhase === "loading" ? (
619
+ <p className="shell-share-blurb" role="status">Loading people...</p>
620
+ ) : sharePeople.length === 0 ? (
621
+ <p className="shell-share-blurb">Only you can open this app for now. You can share it from the App module later.</p>
622
+ ) : (
623
+ <>
624
+ <div className="shell-share-list">
625
+ {shareEntries.length === 0 ? (
626
+ <div className="shell-share-empty">Not shared with anyone yet.</div>
627
+ ) : null}
628
+ {shareEntries.map((entry) => (
629
+ <div className="shell-share-row" key={entry.user}>
630
+ <span className="shell-share-who">{shareNameOf(entry.user)}</span>
631
+ <select
632
+ className="shell-share-select"
633
+ value={entry.role}
634
+ disabled={busy}
635
+ aria-label={`Role for ${shareNameOf(entry.user)}`}
636
+ onChange={(event) => setShareEntries((current) =>
637
+ withEntry(current, entry.user, event.target.value as ShareRole))}
638
+ >
639
+ {SHARE_ROLES.map((role) => (
640
+ <option key={role} value={role}>{role === "edit" ? "Can edit" : "Can view"}</option>
641
+ ))}
642
+ </select>
643
+ <button type="button" className="shell-share-revoke" disabled={busy}
644
+ onClick={() => setShareEntries((current) => withoutEntry(current, entry.user))}>
645
+ Remove
646
+ </button>
647
+ </div>
648
+ ))}
649
+ </div>
650
+ <div className="shell-share-add">
651
+ <input
652
+ className="shell-share-select"
653
+ type="search"
654
+ list="app-wizard-share-options"
655
+ value={shareQuery}
656
+ disabled={busy}
657
+ aria-label="Search people to share with"
658
+ placeholder="Search people"
659
+ onChange={(event) => setShareQuery(event.target.value)}
660
+ />
661
+ <datalist id="app-wizard-share-options">
662
+ {canAddEveryone ? <option value={EVERYONE_LABEL} /> : null}
663
+ {shareOptions.map((person) => (
664
+ <option key={person.user} value={`${person.name} (${person.user})`} />
665
+ ))}
666
+ </datalist>
667
+ <select
668
+ className="shell-share-select"
669
+ value={sharePickRole}
670
+ disabled={busy}
671
+ aria-label="Role for the person being added"
672
+ onChange={(event) => setSharePickRole(event.target.value as ShareRole)}
673
+ >
674
+ {SHARE_ROLES.map((role) => (
675
+ <option key={role} value={role}>{role === "edit" ? "Can edit" : "Can view"}</option>
676
+ ))}
677
+ </select>
678
+ <button type="button" className="login-submit shell-share-grant"
679
+ disabled={busy || !shareRecipient}
680
+ onClick={() => {
681
+ if (!shareRecipient) return;
682
+ setShareEntries((current) => withEntry(current, shareRecipient, sharePickRole));
683
+ setShareQuery("");
684
+ }}>
685
+ Grant access
686
+ </button>
687
+ </div>
688
+ <p className="shell-share-blurb">Everyone you add can open this app. Only you can change it.</p>
689
+ </>
690
+ )
691
+ ) : null}
692
+
693
+ {step === 4 && template ? (
694
  <div className="app-wizard-review">
695
  <label className="app-wizard-field">
696
  <span>Application name</span>
 
699
  <dl>
700
  <div><dt>Template</dt><dd>{template.label}</dd></div>
701
  <div><dt>Database</dt><dd>{schema.phase === "ready" ? schema.value.label : sourceDatabase}</dd></div>
702
+ <div><dt>Shared with</dt><dd>{shareEntries.length
703
+ ? shareEntries.map((entry) => shareNameOf(entry.user)).join(", ")
704
+ : "Only you"}</dd></div>
705
  {template.fieldRoles.filter((role) => fieldMap[role.key]).map((role) => (
706
  <div key={role.key}><dt>{role.label}</dt><dd>{
707
  schema.phase === "ready"
 
725
  {step > 0 ? (
726
  <button type="button" className="app-wizard-secondary" onClick={() => { setStep((current) => current - 1); setError(""); }} disabled={busy}>Back</button>
727
  ) : null}
728
+ {step < 4 ? (
729
  <button type="button" className="login-submit" disabled={!canContinue || busy}
730
  onClick={() => { setStep((current) => current + 1); setError(""); }}>Continue</button>
731
  ) : (
 
753
  // dispatcher is a switch over two literals rather than a second copy of the route table.
754
  import { retryEmit, routeForTarget } from "../inbox/inboxModel";
755
  import ShareDialog from "./ShareDialog";
756
+ import { EVERYONE, EVERYONE_LABEL, SHARE_OPEN_EVENT, SHARE_ROLES, addablePeople, parseShare, parseShareRequest, resolveShareRecipient, withEntry, withoutEntry } from "./shareModel";
757
+ import type { ShareEntry, SharePerson, ShareRequest, ShareRole } from "./shareModel";
758
  // WAVE 19 R8 — the chosen database mark. Read-only across the session fence.
759
  import { isAdmin, logout, me } from "./session";
760
  import type { SessionUser } from "./session";
web/src/shell/qrcode.ts ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Byte-mode QR, level M, with no runtime imports or browser state. The matrix
2
+ // excludes the quiet zone: every renderer must supply four light modules.
3
+ export type QrMatrix = { size: number; version: number; mask: number; modules: boolean[][] };
4
+
5
+ // ISO/IEC 18004 level-M block layouts, versions 1..10. Longer blocks follow
6
+ // shorter ones; the difference is one DATA byte, never an extra parity byte.
7
+ const BLOCKS = [
8
+ { parity: 10, data: [16] },
9
+ { parity: 16, data: [28] },
10
+ { parity: 26, data: [44] },
11
+ { parity: 18, data: [32, 32] },
12
+ { parity: 24, data: [43, 43] },
13
+ { parity: 16, data: [27, 27, 27, 27] },
14
+ { parity: 18, data: [31, 31, 31, 31] },
15
+ { parity: 22, data: [38, 38, 39, 39] },
16
+ { parity: 22, data: [36, 36, 36, 37, 37] },
17
+ { parity: 26, data: [43, 43, 43, 43, 44] },
18
+ ];
19
+ const ALIGNMENT = [[], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34],
20
+ [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50]];
21
+
22
+ function multiply(a: number, b: number): number {
23
+ let product = 0;
24
+ for (; b > 0; b >>>= 1) {
25
+ if (b & 1) product ^= a;
26
+ a <<= 1;
27
+ if (a & 0x100) a ^= 0x11d;
28
+ }
29
+ return product;
30
+ }
31
+
32
+ function generator(degree: number): number[] {
33
+ // QR uses roots alpha^0 through alpha^(degree-1) over GF(256), alpha=2.
34
+ // A wrong polynomial still makes a perfect-looking square that cannot scan.
35
+ let polynomial = [1];
36
+ let root = 1;
37
+ for (let i = 0; i < degree; i++) {
38
+ const next = Array<number>(polynomial.length + 1).fill(0);
39
+ polynomial.forEach((coefficient, j) => {
40
+ next[j] ^= coefficient;
41
+ next[j + 1] ^= multiply(coefficient, root);
42
+ });
43
+ polynomial = next;
44
+ root = multiply(root, 2);
45
+ }
46
+ return polynomial;
47
+ }
48
+
49
+ function interleave(data: number[], lengths: number[], parity: number): number[] {
50
+ const divisor = generator(parity);
51
+ let offset = 0;
52
+ const blocks = lengths.map((length) => {
53
+ const block = data.slice(offset, offset + length);
54
+ offset += length;
55
+ const remainder = Array<number>(parity).fill(0);
56
+ for (const value of block) {
57
+ const factor = value ^ remainder.shift()!;
58
+ remainder.push(0);
59
+ for (let j = 0; j < parity; j++) remainder[j] ^= multiply(divisor[j + 1], factor);
60
+ }
61
+ return { data: block, remainder };
62
+ });
63
+ // Interleave one column across ALL blocks, then the next. Concatenating
64
+ // complete blocks is tempting and fails only once a version has >1 block.
65
+ const result: number[] = [];
66
+ for (let i = 0; i < Math.max(...lengths); i++) {
67
+ for (const block of blocks) if (i < block.data.length) result.push(block.data[i]);
68
+ }
69
+ for (let i = 0; i < parity; i++) {
70
+ for (const block of blocks) result.push(block.remainder[i]);
71
+ }
72
+ return result;
73
+ }
74
+
75
+ function maskBit(mask: number, row: number, col: number): boolean {
76
+ const product = row * col;
77
+ switch (mask) {
78
+ case 0: return (row + col) % 2 === 0;
79
+ case 1: return row % 2 === 0;
80
+ case 2: return col % 3 === 0;
81
+ case 3: return (row + col) % 3 === 0;
82
+ case 4: return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0;
83
+ case 5: return product % 2 + product % 3 === 0;
84
+ case 6: return (product % 2 + product % 3) % 2 === 0;
85
+ case 7: return ((row + col) % 2 + product % 3) % 2 === 0;
86
+ default: throw new Error("Invalid QR mask");
87
+ }
88
+ }
89
+
90
+ function penalty(modules: boolean[][]): number {
91
+ const size = modules.length;
92
+ let score = 0;
93
+ let dark = 0;
94
+ const linePenalty = (line: boolean[]): number => {
95
+ let total = 0;
96
+ let run = 1;
97
+ for (let i = 1; i < size; i++) {
98
+ if (line[i] === line[i - 1]) run++;
99
+ else { if (run >= 5) total += run - 2; run = 1; }
100
+ }
101
+ if (run >= 5) total += run - 2; // N1: 3 for five, then 1 per extra module.
102
+ for (let i = 0; i <= size - 7; i++) {
103
+ if (line[i] && !line[i + 1] && line[i + 2] && line[i + 3]
104
+ && line[i + 4] && !line[i + 5] && line[i + 6]) {
105
+ // N3: a finder-like 1:1:3:1:1 run with four light modules on
106
+ // either side. The symbol edge abuts the caller's light quiet zone.
107
+ const before = line.slice(Math.max(0, i - 4), i).every((bit) => !bit);
108
+ const after = line.slice(i + 7, i + 11).every((bit) => !bit);
109
+ if (before || after) total += 40;
110
+ }
111
+ }
112
+ return total;
113
+ };
114
+ for (let row = 0; row < size; row++) {
115
+ score += linePenalty(modules[row]);
116
+ score += linePenalty(modules.map((line) => line[row]));
117
+ for (let col = 0; col < size; col++) {
118
+ if (modules[row][col]) dark++;
119
+ // N2: every solid 2x2 square, including overlapping squares.
120
+ if (row > 0 && col > 0 && modules[row][col] === modules[row - 1][col]
121
+ && modules[row][col] === modules[row][col - 1]
122
+ && modules[row][col] === modules[row - 1][col - 1]) score += 3;
123
+ }
124
+ }
125
+ // N4: ten points per full five-percentage-point departure from half dark.
126
+ return score + Math.floor(Math.abs(dark * 20 - size * size * 10) / (size * size)) * 10;
127
+ }
128
+
129
+ /** Encode UTF-8 bytes (setup URIs are ASCII/percent-encoded). Never truncate. */
130
+ export function encodeQr(text: string): QrMatrix {
131
+ const bytes = new TextEncoder().encode(text);
132
+ const index = BLOCKS.findIndex((block, i) =>
133
+ 4 + (i < 9 ? 8 : 16) + bytes.length * 8 <= block.data.reduce((a, b) => a + b, 0) * 8);
134
+ if (index < 0) throw new RangeError("QR data exceeds version 10-M capacity (213 bytes)");
135
+ const version = index + 1;
136
+ const size = 17 + 4 * version;
137
+ const layout = BLOCKS[index];
138
+ const capacity = layout.data.reduce((a, b) => a + b, 0) * 8;
139
+ const bits: number[] = [];
140
+ const append = (value: number, count: number) => {
141
+ for (let shift = count - 1; shift >= 0; shift--) bits.push((value >>> shift) & 1);
142
+ };
143
+ append(4, 4); // Byte mode; v10 widens the byte COUNT from 8 bits to 16.
144
+ append(bytes.length, version < 10 ? 8 : 16);
145
+ bytes.forEach((byte) => append(byte, 8));
146
+ append(0, Math.min(4, capacity - bits.length));
147
+ // The independent reference keeps a full zero alignment byte after an
148
+ // already aligned terminator. Preserve that convention when space permits;
149
+ // a capacity-bound payload must never gain a byte beyond its data blocks.
150
+ append(0, Math.min(8 - bits.length % 8, capacity - bits.length));
151
+ const data: number[] = [];
152
+ for (let i = 0; i < bits.length; i += 8) {
153
+ data.push(bits.slice(i, i + 8).reduce((value, bit) => (value << 1) | bit, 0));
154
+ }
155
+ for (let pad = 0; data.length < capacity / 8; pad++) data.push(pad % 2 === 0 ? 0xEC : 0x11);
156
+ const codewords = interleave(data, layout.data, layout.parity);
157
+ const modules = Array.from({ length: size }, () => Array<boolean>(size).fill(false));
158
+ const reserved = modules.map((row) => row.slice());
159
+ const set = (row: number, col: number, dark: boolean) => {
160
+ modules[row][col] = dark;
161
+ reserved[row][col] = true;
162
+ };
163
+ for (let i = 0; i < size; i++) {
164
+ set(6, i, i % 2 === 0);
165
+ set(i, 6, i % 2 === 0);
166
+ }
167
+ for (const [cy, cx] of [[3, 3], [3, size - 4], [size - 4, 3]]) {
168
+ for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
169
+ const row = cy + dy, col = cx + dx;
170
+ if (row < 0 || col < 0 || row >= size || col >= size) continue;
171
+ const distance = Math.max(Math.abs(dx), Math.abs(dy));
172
+ set(row, col, distance !== 2 && distance !== 4);
173
+ }
174
+ }
175
+ const centers = ALIGNMENT[index];
176
+ for (const row of centers) for (const col of centers) {
177
+ // Alignment can overwrite TIMING, but never any of the three finders.
178
+ if ((row === 6 && (col === 6 || col === size - 7)) || (col === 6 && row === size - 7)) continue;
179
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) {
180
+ set(row + dy, col + dx, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
181
+ }
182
+ }
183
+ const format = (value: number) => {
184
+ const bit = (i: number) => ((value >>> i) & 1) !== 0;
185
+ for (let i = 0; i <= 5; i++) set(i, 8, bit(i));
186
+ set(7, 8, bit(6)); set(8, 8, bit(7)); set(8, 7, bit(8));
187
+ for (let i = 9; i < 15; i++) set(8, 14 - i, bit(i));
188
+ for (let i = 0; i < 8; i++) set(8, size - 1 - i, bit(i));
189
+ for (let i = 8; i < 15; i++) set(size - 15 + i, 8, bit(i));
190
+ };
191
+ const versionInfo = (value: number) => {
192
+ if (version < 7) return;
193
+ for (let i = 0; i < 18; i++) {
194
+ const a = size - 11 + i % 3, b = Math.floor(i / 3);
195
+ set(b, a, ((value >>> i) & 1) !== 0);
196
+ set(a, b, ((value >>> i) & 1) !== 0);
197
+ }
198
+ };
199
+ format(0);
200
+ versionInfo(0);
201
+ set(size - 8, 8, false);
202
+ let cursor = 0;
203
+ let upward = true;
204
+ for (let right = size - 1; right >= 1; right -= 2) {
205
+ if (right === 6) right--;
206
+ for (let step = 0; step < size; step++) {
207
+ const row = upward ? size - 1 - step : step;
208
+ for (let offset = 0; offset < 2; offset++) {
209
+ const col = right - offset;
210
+ if (reserved[row][col]) continue;
211
+ // Remainder bits past the last codeword are light before masking.
212
+ modules[row][col] = cursor < codewords.length * 8
213
+ && ((codewords[cursor >>> 3] >>> (7 - cursor % 8)) & 1) !== 0;
214
+ cursor++;
215
+ }
216
+ }
217
+ upward = !upward;
218
+ }
219
+ // Choose, never fix, the mask using all four penalty rules. Reserve metadata
220
+ // as light while scoring; write the chosen format/version bits afterwards.
221
+ // Strictly-less keeps the lowest mask number when penalties tie.
222
+ let mask = 0;
223
+ let bestScore = Infinity;
224
+ for (let candidate = 0; candidate < 8; candidate++) {
225
+ const masked = modules.map((row, y) => row.map((dark, x) =>
226
+ reserved[y][x] ? dark : dark !== maskBit(candidate, y, x)));
227
+ const score = penalty(masked);
228
+ if (score < bestScore) { bestScore = score; mask = candidate; }
229
+ }
230
+ for (let row = 0; row < size; row++) for (let col = 0; col < size; col++) {
231
+ if (!reserved[row][col]) modules[row][col] = modules[row][col] !== maskBit(mask, row, col);
232
+ }
233
+ // M has format indicator 00; the remaining three data bits name the mask.
234
+ let formatRemainder = mask;
235
+ for (let i = 0; i < 10; i++) formatRemainder = (formatRemainder << 1) ^ ((formatRemainder >>> 9) * 0x537);
236
+ format(((mask << 10) | formatRemainder) ^ 0x5412);
237
+ set(size - 8, 8, true);
238
+ let versionRemainder = version;
239
+ for (let i = 0; i < 12; i++) versionRemainder = (versionRemainder << 1) ^ ((versionRemainder >>> 11) * 0x1f25);
240
+ versionInfo((version << 12) | versionRemainder);
241
+ return { size, version, mask, modules };
242
+ }
web/src/styles/wave52/ribbon.css CHANGED
@@ -69,6 +69,80 @@
69
  outline-offset: 2px;
70
  }
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  /* W52-T19 (owner instruction 21, ruling R7) — a shortcut a person has disabled from the settings
73
  pane, drawn in `ShortcutsPanel.tsx` (the Ctrl+/ list, which is also this feature's audit trail).
74
  Muted rather than removed: the row still names the action, so the list keeps explaining what a
 
69
  outline-offset: 2px;
70
  }
71
 
72
+ /* Trailing groups fold as a unit on every tab. The measurement copy contains only the
73
+ folded groups, so controls, fieldsets and component state are never duplicated. */
74
+ .sheet-ribbon-shell > .sheet-ribbon > .sheet-ribbon-scroll {
75
+ position: relative;
76
+ }
77
+
78
+ .sheet-ribbon-overflow-trigger {
79
+ display: inline-flex;
80
+ flex: 0 0 auto;
81
+ align-self: flex-start;
82
+ width: 80px;
83
+ margin-left: 8px;
84
+ }
85
+
86
+ .sheet-ribbon-overflow-trigger .sheet-ribbon-btn {
87
+ flex-direction: column;
88
+ gap: 4px;
89
+ width: 100%;
90
+ height: var(--sheet-ribbon-band);
91
+ padding: 4px;
92
+ }
93
+
94
+ .sheet-ribbon-overflow-trigger .sheet-ribbon-label {
95
+ font-size: var(--lp-fs-2xs);
96
+ white-space: nowrap;
97
+ }
98
+
99
+ .sheet-ribbon-overflow-trigger.is-measuring {
100
+ position: absolute;
101
+ left: 0;
102
+ top: 0;
103
+ visibility: hidden;
104
+ pointer-events: none;
105
+ margin: 0;
106
+ }
107
+
108
+ .sheet-ribbon.sheet-ribbon-overflow,
109
+ .sheet-ribbon.sheet-ribbon-overflow-measure {
110
+ width: max-content;
111
+ max-width: calc(100vw - 16px);
112
+ padding: 8px;
113
+ }
114
+
115
+ .sheet-ribbon.sheet-ribbon-overflow {
116
+ min-width: 0;
117
+ overflow: auto;
118
+ border: 1px solid var(--lp-line);
119
+ border-radius: var(--lp-r-sm);
120
+ background: var(--lp-surface);
121
+ color: var(--lp-ink);
122
+ box-shadow: var(--shell-shadow-overlay);
123
+ }
124
+
125
+ .sheet-ribbon-overflow-measure {
126
+ position: fixed;
127
+ left: 0;
128
+ top: 0;
129
+ visibility: hidden;
130
+ pointer-events: none;
131
+ }
132
+
133
+ .sheet-ribbon-overflow-content,
134
+ .sheet-ribbon-overflow-content > fieldset {
135
+ display: flex;
136
+ flex-wrap: wrap;
137
+ align-items: stretch;
138
+ row-gap: 8px;
139
+ max-width: 100%;
140
+ }
141
+
142
+ .sheet-ribbon-overflow-content .sheet-ribbon-group {
143
+ flex: 0 0 auto;
144
+ }
145
+
146
  /* W52-T19 (owner instruction 21, ruling R7) — a shortcut a person has disabled from the settings
147
  pane, drawn in `ShortcutsPanel.tsx` (the Ctrl+/ list, which is also this feature's audit trail).
148
  Muted rather than removed: the row still names the action, so the list keeps explaining what a
web/src/styles/wave54/ribbon-insert.css CHANGED
@@ -4,7 +4,8 @@
4
  `wave52/ribbon.css`'s own header sets out: `index.css` is shared across every lane and a line
5
  there is the trivial-but-collision-prone edit.
6
 
7
- ⚠ THE SHARED VOCABULARY IS NOT REDECLARED HERE. `.sheet-ribbon-btn`, `.sheet-ribbon-icon`,
 
8
  `.sheet-ribbon-caret`, `.sheet-ribbon-slot`, `.sheet-ribbon-group`, `.sheet-ribbon-group-name`,
9
  `.sheet-ribbon-group-controls`, `.sheet-ribbon-scroll` and `.sheet-ribbon-item` are painted by
10
  `styles/wave50/sheet.css` and `styles/wave51/sheet-engine.css` for EVERY tab, unscoped, so a
@@ -44,6 +45,38 @@
44
 
45
  .sheet-ribbon-insert .sheet-ribbon-label { white-space: nowrap; }
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  /* ── the disabled fence ───────────────────────────────────────────────────────────────────────
48
  ⛔ A `<fieldset>` IS THE ONLY NATIVE WAY TO DISABLE A WHOLE GROUP OF CONTROLS AT ONCE, and the
49
  Insert tab needs exactly that when the page has not wired its document doors (no fake
@@ -254,50 +287,46 @@
254
  color: var(--lp-muted);
255
  }
256
 
257
- /* ── the eight kinds ──────────────────────────────────────────────────────────────────────── */
258
- .sheet-chart-gallery {
259
  display: grid;
260
  grid-template-columns: repeat(4, minmax(0, 1fr));
261
- gap: 8px;
 
 
 
262
  }
263
 
264
- .sheet-chart-kind {
265
  display: flex;
266
- flex-direction: column;
267
  align-items: center;
268
- gap: 6px;
269
- padding: 10px 6px;
270
- background: var(--lp-surface);
271
- border: 1px solid var(--lp-line);
272
- border-radius: var(--lp-r-md);
273
- font: inherit;
274
- font-size: var(--lp-fs-3xs);
275
- color: var(--lp-ink);
276
- cursor: pointer;
277
- transition: border-color 150ms ease-out, background-color 150ms ease-out, color 150ms ease-out;
278
  }
279
 
280
- .sheet-chart-kind:hover {
281
- background: var(--lp-surface-2);
 
282
  }
283
 
284
- .sheet-chart-kind[aria-pressed="true"] {
285
- border-color: var(--lp-blue-solid);
286
- color: var(--lp-blue-solid);
287
  }
288
 
289
- .sheet-chart-kind:focus-visible {
290
- outline: 2px solid var(--lp-blue-deep);
291
- outline-offset: 1px;
 
292
  }
293
 
294
- .sheet-chart-kind:active {
295
- transform: scale(0.97);
296
  }
297
 
298
- .sheet-chart-kind-icon {
299
- width: 22px;
300
- height: 22px;
301
  fill: none;
302
  stroke: currentColor;
303
  stroke-width: 1.2;
@@ -306,7 +335,7 @@
306
  }
307
 
308
  /* A zero-length segment with a round cap IS the dot; heavier stroke is what gives it a radius. */
309
- .sheet-chart-kind-dots {
310
  stroke-width: 2.2;
311
  }
312
 
@@ -371,15 +400,13 @@
371
 
372
  @media (prefers-reduced-motion: reduce) {
373
  .sheet-chart-tab,
374
- .sheet-chart-kind,
375
  .sheet-chart-select,
376
  .sheet-chart-text,
377
  .sheet-chart-number {
378
  transition: none;
379
  }
380
 
381
- .sheet-chart-tab:active,
382
- .sheet-chart-kind:active {
383
  transform: none;
384
  }
385
 
 
4
  `wave52/ribbon.css`'s own header sets out: `index.css` is shared across every lane and a line
5
  there is the trivial-but-collision-prone edit.
6
 
7
+ The shared vocabulary is not redeclared globally here. Insert-only size overrides below
8
+ match Home's large Paste role. `.sheet-ribbon-btn`, `.sheet-ribbon-icon`,
9
  `.sheet-ribbon-caret`, `.sheet-ribbon-slot`, `.sheet-ribbon-group`, `.sheet-ribbon-group-name`,
10
  `.sheet-ribbon-group-controls`, `.sheet-ribbon-scroll` and `.sheet-ribbon-item` are painted by
11
  `styles/wave50/sheet.css` and `styles/wave51/sheet-engine.css` for EVERY tab, unscoped, so a
 
45
 
46
  .sheet-ribbon-insert .sheet-ribbon-label { white-space: nowrap; }
47
 
48
+ /* Large singles use Home's Paste icon box, caption token and shared control band. */
49
+ .sheet-ribbon-insert .sheet-ribbon-insert-large .sheet-ribbon-btn {
50
+ flex-direction: column;
51
+ justify-content: center;
52
+ gap: 4px;
53
+ min-width: 46px;
54
+ height: var(--sheet-ribbon-band);
55
+ padding: 4px;
56
+ }
57
+
58
+ .sheet-ribbon-insert .sheet-ribbon-insert-large .sheet-ribbon-icon {
59
+ width: 19px;
60
+ height: 19px;
61
+ }
62
+
63
+ .sheet-ribbon-insert .sheet-ribbon-insert-large .sheet-ribbon-label {
64
+ font-size: var(--lp-fs-2xs);
65
+ }
66
+
67
+ .sheet-ribbon-insert .sheet-ribbon-insert-stack {
68
+ flex-direction: column;
69
+ justify-content: center;
70
+ height: var(--sheet-ribbon-band);
71
+ }
72
+
73
+ .sheet-ribbon-insert .sheet-ribbon-insert-stack .sheet-ribbon-btn {
74
+ flex: 1 1 0;
75
+ width: 26px;
76
+ height: auto;
77
+ padding: 0 4px;
78
+ }
79
+
80
  /* ── the disabled fence ───────────────────────────────────────────────────────────────────────
81
  ⛔ A `<fieldset>` IS THE ONLY NATIVE WAY TO DISABLE A WHOLE GROUP OF CONTROLS AT ONCE, and the
82
  Insert tab needs exactly that when the page has not wired its document doors (no fake
 
287
  color: var(--lp-muted);
288
  }
289
 
290
+ /* The ribbon's chart shortcuts reuse the former, unused dialog gallery vocabulary. */
291
+ .sheet-ribbon-insert .sheet-chart-gallery {
292
  display: grid;
293
  grid-template-columns: repeat(4, minmax(0, 1fr));
294
+ grid-template-rows: repeat(2, minmax(0, 1fr));
295
+ height: var(--sheet-ribbon-band);
296
+ gap: 4px;
297
+ margin-left: 4px;
298
  }
299
 
300
+ .sheet-ribbon-insert .sheet-chart-kind {
301
  display: flex;
302
+ flex-direction: row;
303
  align-items: center;
304
+ border-radius: var(--lp-r-sm);
 
 
 
 
 
 
 
 
 
305
  }
306
 
307
+ .sheet-ribbon-insert .sheet-chart-kind .sheet-ribbon-btn {
308
+ height: 24px;
309
+ padding: 0 4px;
310
  }
311
 
312
+ .sheet-ribbon-insert .sheet-chart-kind-caret {
313
+ display: flex;
314
+ border-left: 1px solid var(--lp-line);
315
  }
316
 
317
+ .sheet-ribbon-insert .sheet-chart-kind-caret .sheet-ribbon-btn {
318
+ min-width: 16px;
319
+ width: 16px;
320
+ padding: 0;
321
  }
322
 
323
+ .sheet-ribbon-insert .sheet-chart-kind-recommended .sheet-ribbon-btn {
324
+ width: 100%;
325
  }
326
 
327
+ .sheet-ribbon-insert .sheet-chart-kind-icon {
328
+ width: 15px;
329
+ height: 15px;
330
  fill: none;
331
  stroke: currentColor;
332
  stroke-width: 1.2;
 
335
  }
336
 
337
  /* A zero-length segment with a round cap IS the dot; heavier stroke is what gives it a radius. */
338
+ .sheet-ribbon-insert .sheet-chart-kind-dots {
339
  stroke-width: 2.2;
340
  }
341
 
 
400
 
401
  @media (prefers-reduced-motion: reduce) {
402
  .sheet-chart-tab,
 
403
  .sheet-chart-select,
404
  .sheet-chart-text,
405
  .sheet-chart-number {
406
  transition: none;
407
  }
408
 
409
+ .sheet-chart-tab:active {
 
410
  transform: none;
411
  }
412
 
web/src/styles/wave55/apps.css CHANGED
@@ -76,10 +76,22 @@
76
  font-size: var(--lp-fs-2xs);
77
  }
78
 
79
- /* Routing and Catalog Application creation share one four-step dialog. */
 
 
 
 
 
 
 
 
 
 
 
 
80
  .shell-newdb.app-wizard {
81
  width: min(720px, calc(100vw - 32px));
82
- min-height: 548px;
83
  max-height: calc(100vh - 48px);
84
  padding: 0;
85
  display: grid;
@@ -150,7 +162,7 @@
150
 
151
  .app-wizard-steps {
152
  display: grid;
153
- grid-template-columns: repeat(4, 1fr);
154
  gap: 8px;
155
  margin: 0;
156
  padding: 12px 24px;
@@ -201,11 +213,12 @@
201
  .app-wizard-template-grid {
202
  display: grid;
203
  grid-template-columns: repeat(2, minmax(0, 1fr));
204
- gap: 12px;
 
205
  }
206
 
207
  .app-wizard-template {
208
- min-height: 144px;
209
  display: flex;
210
  align-items: flex-start;
211
  gap: 16px;
@@ -265,7 +278,7 @@
265
  }
266
 
267
  .app-wizard-template strong {
268
- margin: 2px 0 6px;
269
  font-size: var(--lp-fs-sm);
270
  }
271
 
@@ -358,11 +371,11 @@
358
  .app-wizard-loading {
359
  display: grid;
360
  grid-template-columns: repeat(2, minmax(0, 1fr));
361
- gap: 12px;
362
  }
363
 
364
  .app-wizard-loading span {
365
- height: 144px;
366
  border-radius: var(--lp-r-lg);
367
  background: var(--lp-wash);
368
  animation: app-wizard-pulse 1.1s ease-in-out infinite alternate;
@@ -381,6 +394,12 @@
381
  height: 36px;
382
  }
383
 
 
 
 
 
 
 
384
  .app-wizard-secondary {
385
  padding: 0 12px;
386
  border: 1px solid var(--lp-line-strong);
@@ -415,6 +434,25 @@
415
  display: none;
416
  }
417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  .cg-app-catalog-head {
419
  display: flex;
420
  align-items: center;
@@ -619,7 +657,7 @@
619
  }
620
 
621
  .shell-newdb.app-wizard {
622
- min-height: min(548px, calc(100vh - 24px));
623
  }
624
 
625
  .app-wizard-template-grid,
 
76
  font-size: var(--lp-fs-2xs);
77
  }
78
 
79
+ /* Reachability floor for Share and New database, whose geometry lives in index.css.
80
+ The full geometry fix belongs to a ticket that owns that file. */
81
+ .shell-newdb-scrim:has(.shell-newdb) {
82
+ overflow-y: auto;
83
+ }
84
+
85
+ .shell-newdb-scrim:has(.app-wizard) {
86
+ align-items: center;
87
+ padding: 24px 16px;
88
+ overflow-y: auto;
89
+ }
90
+
91
+ /* Routing and Catalog Application creation share one five-step dialog. */
92
  .shell-newdb.app-wizard {
93
  width: min(720px, calc(100vw - 32px));
94
+ min-height: min(548px, calc(100vh - 48px));
95
  max-height: calc(100vh - 48px);
96
  padding: 0;
97
  display: grid;
 
162
 
163
  .app-wizard-steps {
164
  display: grid;
165
+ grid-template-columns: repeat(5, 1fr);
166
  gap: 8px;
167
  margin: 0;
168
  padding: 12px 24px;
 
213
  .app-wizard-template-grid {
214
  display: grid;
215
  grid-template-columns: repeat(2, minmax(0, 1fr));
216
+ grid-auto-rows: 1fr;
217
+ gap: 16px;
218
  }
219
 
220
  .app-wizard-template {
221
+ min-height: 104px;
222
  display: flex;
223
  align-items: flex-start;
224
  gap: 16px;
 
278
  }
279
 
280
  .app-wizard-template strong {
281
+ margin: 0 0 4px;
282
  font-size: var(--lp-fs-sm);
283
  }
284
 
 
371
  .app-wizard-loading {
372
  display: grid;
373
  grid-template-columns: repeat(2, minmax(0, 1fr));
374
+ gap: 16px;
375
  }
376
 
377
  .app-wizard-loading span {
378
+ height: 104px;
379
  border-radius: var(--lp-r-lg);
380
  background: var(--lp-wash);
381
  animation: app-wizard-pulse 1.1s ease-in-out infinite alternate;
 
394
  height: 36px;
395
  }
396
 
397
+ .app-wizard-actions .login-submit {
398
+ width: auto;
399
+ margin-top: 0;
400
+ padding: 0 16px;
401
+ }
402
+
403
  .app-wizard-secondary {
404
  padding: 0 12px;
405
  border: 1px solid var(--lp-line-strong);
 
434
  display: none;
435
  }
436
 
437
+ /* W59-T28: Toolbar.tsx is SHARED and deliberately outside this ticket's fence.
438
+ Filter and Sort have computed aria-labels, so the tone class is the stable hook.
439
+ Bubble size also wears cg-tb-btn--sort; scope to .cg-toolbar to preserve Map settings. */
440
+ .cg-main:has(.cg-app-catalog, .cg-app-route-surface) .cg-toolbar .cg-pop-wrap:not(:has(> .cg-tb-btn--filter)),
441
+ .cg-main:has(.cg-app-catalog, .cg-app-route-surface) .cg-toolbar > .cg-tb-btn {
442
+ display: none;
443
+ }
444
+
445
+ /* D-710: the view rail must not stand beside an addressed App. It is a SIBLING of
446
+ .cg-main, not a descendant, so the scope starts one level up at .cg-shell.
447
+ MEASURED 2026-09-13: on an addressed App the rail is already absent from the DOM,
448
+ because CustomerGrid's `hideViews` happens to be true there. That derivation reads
449
+ `!hostWorkspace || payload?.workspace?.hideViews === true` and knows nothing about app
450
+ addressing, so the absence is incidental. This rule is the scope-correct guard that
451
+ keeps the rail away if that derivation ever changes; it is a no-op today by design. */
452
+ .cg-shell:has(.cg-main .cg-app-catalog, .cg-main .cg-app-route-surface) .cg-views {
453
+ display: none;
454
+ }
455
+
456
  .cg-app-catalog-head {
457
  display: flex;
458
  align-items: center;
 
657
  }
658
 
659
  .shell-newdb.app-wizard {
660
+ min-height: min(548px, calc(100vh - 48px));
661
  }
662
 
663
  .app-wizard-template-grid,
web/src/styles/wave59/binding.css ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ---------------------------------------------------------------------------
2
+ styles/wave59/binding.css - sequential navigation for the cell binding panel.
3
+
4
+ W59-T11 (instruction 13) renames the Rows section to Filter and gates the rail
5
+ in form order. BindingEditor imports this sheet directly beside the panel's
6
+ existing styles. Keep blocked buttons visible with one short hint below the
7
+ label; the rail's geometry and native button reset stay in wave57's base rule.
8
+ --------------------------------------------------------------------------- */
9
+
10
+ .sheet-binding-rail-item:disabled {
11
+ opacity: 0.42;
12
+ cursor: not-allowed;
13
+ }
14
+
15
+ .sheet-binding-rail-item:disabled:hover {
16
+ background: transparent;
17
+ }
18
+
19
+ .sheet-binding-rail-hint {
20
+ display: block;
21
+ margin-top: 4px;
22
+ color: var(--lp-muted);
23
+ font-size: var(--lp-fs-3xs);
24
+ font-weight: 400;
25
+ white-space: nowrap;
26
+ }
27
+
28
+ /* The house date inputs share the narrow rail's width and a single baseline. */
29
+ .sheet-field-row.sheet-period-dates {
30
+ gap: 8px;
31
+ align-items: baseline;
32
+ }
33
+
34
+ .sheet-period-dates .sheet-field {
35
+ min-width: 0;
36
+ }
37
+
38
+ .sheet-period-dates input {
39
+ box-sizing: border-box;
40
+ width: 100%;
41
+ min-width: 0;
42
+ height: 32px;
43
+ }
web/src/styles/wave59/chart-dialog.css ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The chooser shares one surface; the rail is separated only by a hairline. */
2
+ .sheet-chart-chooser {
3
+ min-width: 0;
4
+ }
5
+
6
+ .sheet-chart-chooser-tabs {
7
+ display: flex;
8
+ gap: 8px;
9
+ border-bottom: 1px solid var(--lp-line);
10
+ padding-bottom: 8px;
11
+ }
12
+
13
+ .sheet-chart-chooser-tab,
14
+ .sheet-chart-thumbnail {
15
+ border: 0;
16
+ background: transparent;
17
+ font: inherit;
18
+ color: inherit;
19
+ border-radius: var(--lp-r-sm);
20
+ padding: 8px;
21
+ cursor: pointer;
22
+ font-size: var(--lp-fs-xs);
23
+ text-align: left;
24
+ }
25
+
26
+ .sheet-chart-chooser-tab[aria-selected="true"],
27
+ .sheet-chart-thumbnail[aria-selected="true"] {
28
+ background: var(--lp-blue-tint);
29
+ outline: 2px solid var(--lp-blue-deep);
30
+ outline-offset: -2px;
31
+ font-weight: 600;
32
+ }
33
+
34
+ .sheet-chart-chooser-tab:focus-visible,
35
+ .sheet-chart-thumbnail:focus-visible,
36
+ .sheet-chart-formatting > summary:focus-visible {
37
+ outline: 2px solid var(--lp-blue-deep);
38
+ outline-offset: 2px;
39
+ }
40
+
41
+ @media (hover: hover) and (pointer: fine) {
42
+ .sheet-chart-chooser-tab:hover,
43
+ .sheet-chart-thumbnail:hover {
44
+ background: var(--lp-wash);
45
+ }
46
+
47
+ .sheet-chart-chooser-tab[aria-selected="true"]:hover,
48
+ .sheet-chart-thumbnail[aria-selected="true"]:hover {
49
+ background: var(--lp-blue-tint);
50
+ }
51
+ }
52
+
53
+ .sheet-chart-chooser-body {
54
+ display: grid;
55
+ grid-template-columns: 168px minmax(0, 1fr);
56
+ gap: 24px;
57
+ padding-top: 16px;
58
+ min-width: 0;
59
+ }
60
+
61
+ .sheet-chart-thumbnail-rail {
62
+ display: flex;
63
+ flex-direction: column;
64
+ gap: 8px;
65
+ max-height: min(448px, 52dvh);
66
+ overflow-y: auto;
67
+ overscroll-behavior: contain;
68
+ border-right: 1px solid var(--lp-line);
69
+ padding: 4px 12px 4px 4px;
70
+ }
71
+
72
+ .sheet-chart-thumbnail {
73
+ display: flex;
74
+ flex: 0 0 auto;
75
+ flex-direction: column;
76
+ gap: 4px;
77
+ width: 100%;
78
+ min-width: 0;
79
+ }
80
+
81
+ .sheet-chart-thumbnail-name {
82
+ font-size: var(--lp-fs-2xs);
83
+ }
84
+
85
+ .sheet-chart-thumbnail-drawing {
86
+ display: block;
87
+ height: 96px;
88
+ width: 100%;
89
+ pointer-events: none;
90
+ }
91
+
92
+ /* The renderer keeps multi-series legends mandatory; only miniature furniture is hidden. */
93
+ .sheet-chart-thumbnail-drawing .sheet-chart-legend,
94
+ .sheet-chart-thumbnail-drawing .sheet-chart-title {
95
+ display: none;
96
+ }
97
+
98
+ .sheet-chart-thumbnail-error {
99
+ font-size: var(--lp-fs-2xs);
100
+ font-weight: 400;
101
+ color: var(--lp-muted);
102
+ line-height: 1.4;
103
+ }
104
+
105
+ .sheet-chart-live-preview {
106
+ min-width: 0;
107
+ }
108
+
109
+ .sheet-chart-live-heading {
110
+ margin: 0 0 8px;
111
+ font-size: var(--lp-fs-sm);
112
+ font-weight: 600;
113
+ color: var(--lp-ink);
114
+ }
115
+
116
+ .sheet-chart-live-description {
117
+ margin: 0;
118
+ font-size: var(--lp-fs-xs);
119
+ color: var(--lp-muted);
120
+ line-height: 1.4;
121
+ }
122
+
123
+ .sheet-chart-live-drawing {
124
+ height: clamp(240px, 40dvh, 360px);
125
+ margin-top: 16px;
126
+ min-width: 0;
127
+ }
128
+
129
+ .sheet-chart-formatting > summary {
130
+ cursor: pointer;
131
+ font-size: var(--lp-fs-xs);
132
+ color: var(--lp-muted);
133
+ }
134
+
135
+ .sheet-chart-formatting[open] > summary {
136
+ margin-bottom: 16px;
137
+ }
138
+
139
+ @media (max-width: 560px) {
140
+ .sheet-chart-chooser-body {
141
+ grid-template-columns: 104px minmax(0, 1fr);
142
+ gap: 8px;
143
+ }
144
+
145
+ .sheet-chart-thumbnail-rail {
146
+ padding-right: 8px;
147
+ }
148
+
149
+ .sheet-chart-thumbnail-drawing {
150
+ height: 64px;
151
+ }
152
+
153
+ .sheet-chart-chooser-tabs {
154
+ gap: 4px;
155
+ }
156
+ }
web/src/styles/wave59/connectors.css ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* W59-T15, DESIGN.md §§2,3,4,5: one error line and a quiet retry using existing tokens. */
2
+ .conn-modal-error {
3
+ display: flex;
4
+ flex-wrap: wrap;
5
+ align-items: baseline;
6
+ gap: 4px 8px;
7
+ color: var(--lp-red-deep);
8
+ font-size: var(--lp-fs-2xs);
9
+ line-height: var(--lp-lh);
10
+ }
11
+ .conn-modal-error p { margin: 0; }
12
+ .conn-modal-retry {
13
+ appearance: none;
14
+ border: 0;
15
+ background: transparent;
16
+ font: inherit;
17
+ color: var(--lp-ink);
18
+ border-radius: var(--lp-r-sm);
19
+ padding: 4px 8px;
20
+ text-decoration: underline;
21
+ cursor: pointer;
22
+ }
23
+ .conn-modal-retry:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
24
+ @media (hover: hover) and (pointer: fine) {
25
+ .conn-modal-retry:hover { background: var(--lp-wash); }
26
+ }
27
+
28
+ /* W59-T16, R12 and DESIGN.md sections 2 to 5: the pen follows the name on its baseline. */
29
+ .conn-db-name-line {
30
+ display: flex;
31
+ align-items: baseline;
32
+ gap: 4px;
33
+ }
34
+ .conn-db-pen {
35
+ appearance: none;
36
+ flex: 0 0 auto;
37
+ border: 0;
38
+ background: transparent;
39
+ font: inherit;
40
+ color: var(--lp-muted);
41
+ height: 20px;
42
+ padding: 0 4px;
43
+ margin: 0;
44
+ border-radius: var(--lp-r-sm);
45
+ cursor: pointer;
46
+ }
47
+ .conn-db-pen:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
48
+ @media (hover: hover) and (pointer: fine) {
49
+ .conn-db-pen:hover { background: var(--lp-wash); color: var(--lp-ink); }
50
+ }
51
+
52
+ /* W59-T17, DESIGN.md section 4: keep the quiet action on the Count rows baseline. */
53
+ .conn-db-head:has(> .conn-db-count-action + .conn-db-link) { align-items: baseline; }
54
+ .conn-db-count-action + .conn-db-link {
55
+ flex-shrink: 0;
56
+ white-space: nowrap;
57
+ margin-top: 0;
58
+ line-height: 1.5;
59
+ }
60
+
61
+ /* W59-T23, DESIGN.md sections 2 to 5: attention until expiry, negative once expired. */
62
+ .conn-kc-rotation {
63
+ display: flex;
64
+ flex-wrap: wrap;
65
+ align-items: baseline;
66
+ gap: 4px 8px;
67
+ margin-top: 4px;
68
+ padding: 8px;
69
+ border-radius: var(--lp-r-sm);
70
+ background: var(--lp-yellow-tint);
71
+ color: var(--lp-yellow-deep);
72
+ font-size: var(--lp-fs-2xs);
73
+ line-height: var(--lp-lh);
74
+ font-variant-numeric: tabular-nums;
75
+ }
76
+ .conn-kc-rotation.is-urgent { font-weight: 600; }
77
+ .conn-kc-rotation.is-expired,
78
+ .conn-modal-pill.is-expired {
79
+ background: var(--lp-red-tint);
80
+ color: var(--lp-red-deep);
81
+ }
82
+ .conn-kc-rotation-action {
83
+ appearance: none;
84
+ border: 0;
85
+ background: transparent;
86
+ font: inherit;
87
+ color: inherit;
88
+ border-radius: var(--lp-r-sm);
89
+ padding: 0 4px;
90
+ white-space: nowrap;
91
+ text-decoration: underline;
92
+ cursor: pointer;
93
+ }
94
+ .conn-kc-rotation-action:focus-visible {
95
+ outline: 2px solid var(--lp-blue-deep);
96
+ outline-offset: 2px;
97
+ }
98
+ .conn-kc-rotation-action:disabled { opacity: 0.5; cursor: not-allowed; }
99
+ @media (hover: hover) and (pointer: fine) {
100
+ .conn-kc-rotation-action:hover:enabled { background: var(--lp-wash); }
101
+ }
web/src/styles/wave59/security.css ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The existing enrollment form supplies containment and selectable URI text.
2
+ Keep the QR above that text in both the sign-in card and Settings modal. */
3
+ .security-qr-setup {
4
+ display: flex;
5
+ flex-direction: column;
6
+ align-items: flex-start;
7
+ min-width: 0;
8
+ max-width: 100%;
9
+ }
10
+
11
+ .security-qr-image {
12
+ display: block;
13
+ width: min(100%, clamp(160px, 45vw, 220px));
14
+ height: auto;
15
+ aspect-ratio: 1;
16
+ flex: none;
17
+ margin: 0 0 8px;
18
+ color: var(--lp-ink);
19
+ }
20
+
21
+ .security-qr-field { fill: var(--lp-surface); }
22
+
23
+ .security-qr-help {
24
+ margin: 0 0 8px;
25
+ font-size: var(--lp-fs-xs);
26
+ line-height: var(--lp-lh);
27
+ color: var(--lp-muted);
28
+ }
29
+
30
+ .security-compliance-download {
31
+ border: 0;
32
+ background: transparent;
33
+ font: inherit;
34
+ color: inherit;
35
+ padding: 8px;
36
+ margin: 0 0 8px -8px;
37
+ border-radius: var(--lp-r-sm);
38
+ cursor: pointer;
39
+ }
40
+
41
+ @media (hover: hover) and (pointer: fine) {
42
+ .security-compliance-download:hover:not(:disabled) { background: var(--lp-wash); }
43
+ }
44
+
45
+ .security-compliance-download:focus-visible {
46
+ outline: 2px solid var(--lp-blue-deep);
47
+ outline-offset: 2px;
48
+ }
49
+
50
+ .security-compliance-download:disabled { opacity: 0.5; cursor: not-allowed; }
51
+ .security-compliance-group { margin: 16px 0 0; }
52
+ .security-compliance-heading { margin: 0 0 8px; font: inherit; font-weight: 600; }
53
+ .security-compliance-list { list-style: none; margin: 0; padding: 0; }
54
+ .security-compliance-row { padding: 12px 0; border-top: 1px solid var(--lp-line); }
55
+ .security-compliance-claim { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
56
+ .security-compliance-claim > :first-child { min-width: 0; overflow-wrap: anywhere; }
57
+ .security-compliance-evidence { margin: 4px 0 0; color: var(--lp-muted); line-height: var(--lp-lh); }
58
+ .security-compliance-state { flex: none; padding: 4px 8px; border-radius: var(--lp-r-sm); white-space: nowrap; }
59
+ .security-compliance-state.is-met { background: var(--lp-green-tint); color: var(--lp-green-deep); font-weight: 400; }
60
+ .security-compliance-state.is-not-met { background: var(--lp-red-tint); color: var(--lp-red-deep); font-weight: 600; }
61
+ .security-compliance-state.is-unproven { background: var(--lp-yellow-tint); color: var(--lp-yellow-deep); font-weight: 600; }
web/src/styles/wave59/templates.css ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* W59-T30: scoped by :has() rather than by a class this component adds to another
2
+ component's panel at runtime. The kit's dialog owns its own markup. */
3
+ .lp-dialog:has(.sheet-template-gallery) {
4
+ width: min(640px, calc(100vw - 32px));
5
+ overflow: hidden;
6
+ }
7
+
8
+ .lp-dialog:has(.sheet-template-gallery) > .lp-dialog-head,
9
+ .lp-dialog:has(.sheet-template-gallery) > .lp-dialog-actions {
10
+ flex-shrink: 0;
11
+ }
12
+
13
+ .lp-dialog:has(.sheet-template-gallery) > .lp-dialog-body {
14
+ display: flex;
15
+ flex-direction: column;
16
+ min-height: 0;
17
+ }
18
+
19
+ .sheet-template-gallery {
20
+ display: flex;
21
+ flex-direction: column;
22
+ gap: 16px;
23
+ min-height: 0;
24
+ color: var(--lp-ink);
25
+ font-size: var(--lp-fs-sm);
26
+ line-height: var(--lp-lh);
27
+ }
28
+
29
+ .sheet-template-list {
30
+ display: flex;
31
+ flex-direction: column;
32
+ height: 216px;
33
+ min-height: 0;
34
+ overflow: auto;
35
+ overscroll-behavior: contain;
36
+ }
37
+
38
+ .sheet-template-row {
39
+ appearance: none;
40
+ border: 0;
41
+ background: transparent;
42
+ font: inherit;
43
+ color: inherit;
44
+ cursor: pointer;
45
+ text-align: left;
46
+ }
47
+
48
+ .sheet-template-row,
49
+ .sheet-template-skeleton {
50
+ display: flex;
51
+ flex: 0 0 72px;
52
+ flex-direction: column;
53
+ justify-content: center;
54
+ gap: 4px;
55
+ width: 100%;
56
+ min-width: 0;
57
+ height: 72px;
58
+ padding: 12px;
59
+ border-bottom: 1px solid var(--lp-line);
60
+ }
61
+
62
+ .sheet-template-row[aria-pressed="true"] {
63
+ background: var(--lp-blue-tint);
64
+ color: var(--lp-ink);
65
+ }
66
+
67
+ .sheet-template-title,
68
+ .sheet-template-answer {
69
+ display: block;
70
+ overflow: hidden;
71
+ text-overflow: ellipsis;
72
+ white-space: nowrap;
73
+ }
74
+
75
+ .sheet-template-title {
76
+ font-size: var(--lp-fs-sm);
77
+ font-weight: 500;
78
+ }
79
+
80
+ .sheet-template-answer {
81
+ color: var(--lp-muted);
82
+ font-size: var(--lp-fs-xs);
83
+ }
84
+
85
+ .sheet-template-skeleton-title,
86
+ .sheet-template-skeleton-answer {
87
+ display: block;
88
+ height: 20px;
89
+ border-radius: var(--lp-r-md);
90
+ background: var(--lp-surface-2);
91
+ }
92
+
93
+ .sheet-template-skeleton-title {
94
+ width: 40%;
95
+ }
96
+
97
+ .sheet-template-skeleton-answer {
98
+ width: 88%;
99
+ }
100
+
101
+ .sheet-template-database {
102
+ display: flex;
103
+ flex: 0 0 auto;
104
+ flex-direction: column;
105
+ gap: 8px;
106
+ }
107
+
108
+ .sheet-template-select {
109
+ width: 100%;
110
+ min-width: 0;
111
+ height: 40px;
112
+ padding: 8px 12px;
113
+ border: 1px solid var(--lp-line);
114
+ border-radius: var(--lp-r-md);
115
+ background: var(--lp-surface);
116
+ color: var(--lp-ink);
117
+ font: inherit;
118
+ }
119
+
120
+ .sheet-template-row:focus-visible,
121
+ .sheet-template-select:focus-visible,
122
+
123
+ .sheet-template-row:disabled,
124
+ .sheet-template-select:disabled,
125
+ .lp-dialog:has(.sheet-template-gallery) .lp-dialog-btn:disabled {
126
+ opacity: 0.55;
127
+ cursor: not-allowed;
128
+ }
129
+
130
+
131
+ .sheet-template-note,
132
+ .sheet-template-error {
133
+ margin: 0;
134
+ color: var(--lp-muted);
135
+ font-size: var(--lp-fs-sm);
136
+ }
137
+
138
+ .sheet-template-error {
139
+ flex-shrink: 0;
140
+ min-height: 1lh;
141
+ color: var(--lp-red-deep);
142
+ overflow-wrap: anywhere;
143
+ }
144
+
145
+
146
+ @media (hover: hover) and (pointer: fine) {
147
+ .sheet-template-row:hover:not(:disabled):not([aria-pressed="true"]) {
148
+ background: var(--lp-surface-2);
149
+ }
150
+ }