fsanyoto commited on
Commit
c8a9b67
Β·
verified Β·
1 Parent(s): 638e60b

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,449 +1,4 @@
1
  {
2
- "current": "823ea84",
3
- "releases": [
4
- {
5
- "version": "v75",
6
- "sha": "2c51469",
7
- "date": "2026-09-19",
8
- "subject": "release v75"
9
- },
10
- {
11
- "version": "v74",
12
- "sha": "40dceba",
13
- "date": "2026-09-14",
14
- "subject": "release v74: waves 58+59 incl. the Amazon credential door (W59-T21/22/23) and sync producer (W59-T42); hotfix promote so"
15
- },
16
- {
17
- "version": "v73",
18
- "sha": "bb94de5",
19
- "date": "2026-09-13",
20
- "subject": "release v73"
21
- },
22
- {
23
- "version": "v71",
24
- "sha": "96143dc",
25
- "date": "2026-09-04",
26
- "subject": "release v71 - wave 51, QA'd 24 PASS / 6 FAIL / 5 UNPROVEN"
27
- },
28
- {
29
- "version": "v70",
30
- "sha": "eedfb6a",
31
- "date": "2026-09-03",
32
- "subject": "release v70 - wave 50 (grid analytics, the Sheet as a spreadsheet, view trash and audit)"
33
- },
34
- {
35
- "version": "v69",
36
- "sha": "8598f56",
37
- "date": "2026-09-02",
38
- "subject": "release v69: wave48-continuation validated + hotfixes v67/v68/d4e3e31 + go-live QA repairs (Supplier option limit, optio"
39
- },
40
- {
41
- "version": "v68",
42
- "sha": "62b065a",
43
- "date": "2026-09-01",
44
- "subject": "release v68: unified holiday date offsets"
45
- },
46
- {
47
- "version": "v67",
48
- "sha": "3b22419",
49
- "date": "2026-09-01",
50
- "subject": "release v67"
51
- },
52
- {
53
- "version": "v66",
54
- "sha": "73c94f0",
55
- "date": "2026-08-31",
56
- "subject": "release v66"
57
- },
58
- {
59
- "version": "v65",
60
- "sha": "9f6cfed",
61
- "date": "2026-08-31",
62
- "subject": "release v65"
63
- },
64
- {
65
- "version": "v64",
66
- "sha": "bb8985c",
67
- "date": "2026-08-31",
68
- "subject": "release v64"
69
- },
70
- {
71
- "version": "v63",
72
- "sha": "ec75cb8",
73
- "date": "2026-08-31",
74
- "subject": "release v63"
75
- },
76
- {
77
- "version": "v62",
78
- "sha": "2c8f702",
79
- "date": "2026-08-31",
80
- "subject": "release v62"
81
- },
82
- {
83
- "version": "v61",
84
- "sha": "bbc4c07",
85
- "date": "2026-08-30",
86
- "subject": "v61 - wave 46 hotfix: D-590 schema overlay reaches the grid read (all three assemblies), D-599 route to zone association"
87
- },
88
- {
89
- "version": "v60",
90
- "sha": "dd1b062",
91
- "date": "2026-08-30",
92
- "subject": "v60 - wave 46"
93
- },
94
- {
95
- "version": "v59",
96
- "sha": "3cb73ce",
97
- "date": "2026-08-29",
98
- "subject": "release v59"
99
- },
100
- {
101
- "version": "v58",
102
- "sha": "c526ced",
103
- "date": "2026-08-29",
104
- "subject": "release v58"
105
- },
106
- {
107
- "version": "v57",
108
- "sha": "4859c03",
109
- "date": "2026-08-29",
110
- "subject": "release v57"
111
- },
112
- {
113
- "version": "v56",
114
- "sha": "2970b72",
115
- "date": "2026-08-28",
116
- "subject": "release v56"
117
- },
118
- {
119
- "version": "v55",
120
- "sha": "b766b90",
121
- "date": "2026-08-28",
122
- "subject": "release v55"
123
- },
124
- {
125
- "version": "v54",
126
- "sha": "6a8e99a",
127
- "date": "2026-08-27",
128
- "subject": "release v54"
129
- },
130
- {
131
- "version": "v53",
132
- "sha": "89ed2cb",
133
- "date": "2026-08-24",
134
- "subject": "release v53"
135
- },
136
- {
137
- "version": "v52",
138
- "sha": "8263493",
139
- "date": "2026-08-23",
140
- "subject": "release v52"
141
- },
142
- {
143
- "version": "v51",
144
- "sha": "5740d20",
145
- "date": "2026-08-23",
146
- "subject": "release v51"
147
- },
148
- {
149
- "version": "v50",
150
- "sha": "8027c83",
151
- "date": "2026-08-23",
152
- "subject": "release v50"
153
- },
154
- {
155
- "version": "v49",
156
- "sha": "9a14c01",
157
- "date": "2026-08-23",
158
- "subject": "release v49"
159
- },
160
- {
161
- "version": "v48",
162
- "sha": "3c69fd9",
163
- "date": "2026-08-23",
164
- "subject": "release v48"
165
- },
166
- {
167
- "version": "v47",
168
- "sha": "917f9a0",
169
- "date": "2026-08-23",
170
- "subject": "release v47"
171
- },
172
- {
173
- "version": "v46",
174
- "sha": "a8dc531",
175
- "date": "2026-08-23",
176
- "subject": "release v46"
177
- },
178
- {
179
- "version": "v45",
180
- "sha": "0b2b501",
181
- "date": "2026-08-23",
182
- "subject": "release v45"
183
- },
184
- {
185
- "version": "v44",
186
- "sha": "a7877aa",
187
- "date": "2026-08-23",
188
- "subject": "Hotfix: allow renaming the active Map view"
189
- },
190
- {
191
- "version": "v43",
192
- "sha": "e2ba461",
193
- "date": "2026-08-23",
194
- "subject": "release v43"
195
- },
196
- {
197
- "version": "v42",
198
- "sha": "25b885e",
199
- "date": "2026-08-23",
200
- "subject": "release v42"
201
- },
202
- {
203
- "version": "v41",
204
- "sha": "1d6adcc",
205
- "date": "2026-08-22",
206
- "subject": "v41 vertical route navigation"
207
- },
208
- {
209
- "version": "v40",
210
- "sha": "1451837",
211
- "date": "2026-08-22",
212
- "subject": "release v40 route UI correction"
213
- },
214
- {
215
- "version": "v39",
216
- "sha": "a78bdf0",
217
- "date": "2026-08-21",
218
- "subject": "W39 clean stale migration targets"
219
- },
220
- {
221
- "version": "v38",
222
- "sha": "a556631",
223
- "date": "2026-08-21",
224
- "subject": "W39 reversible Live store cutover"
225
- },
226
- {
227
- "version": "v37",
228
- "sha": "1ddd8cf",
229
- "date": "2026-08-21",
230
- "subject": "W39: coalesce derived workspace reads"
231
- },
232
- {
233
- "version": "v36",
234
- "sha": "51db3b7",
235
- "date": "2026-08-21",
236
- "subject": "W39 share-field oid repair"
237
- },
238
- {
239
- "version": "v35",
240
- "sha": "0f64212",
241
- "date": "2026-08-21",
242
- "subject": "W39 visual QA fixture"
243
- },
244
- {
245
- "version": "v34",
246
- "sha": "cb4caa1",
247
- "date": "2026-08-21",
248
- "subject": "W39 Staging PostgreSQL egress controls"
249
- },
250
- {
251
- "version": "v33",
252
- "sha": "2b115e5",
253
- "date": "2026-08-21",
254
- "subject": "W39: stop nonproduction Postgres background egress"
255
- },
256
- {
257
- "version": "v32",
258
- "sha": "b47b27c",
259
- "date": "2026-08-21",
260
- "subject": "W39: repair Staging Postgres projection"
261
- },
262
- {
263
- "version": "v31",
264
- "sha": "8880a49",
265
- "date": "2026-08-21",
266
- "subject": "v31: Wave 39 staging candidate"
267
- },
268
- {
269
- "version": "v30",
270
- "sha": "71776ca",
271
- "date": "2026-08-20",
272
- "subject": "v30: W39-T29 Member-owned View first-share hotfix"
273
- },
274
- {
275
- "version": "v29",
276
- "sha": "55ced50",
277
- "date": "2026-08-18",
278
- "subject": "v29: the build staging has been running since 2026-08-18 (55ced50)."
279
- },
280
- {
281
- "version": "v28",
282
- "sha": "2793e4b",
283
- "date": "2026-08-18",
284
- "subject": "release v28"
285
- },
286
- {
287
- "version": "v27",
288
- "sha": "c05a794",
289
- "date": "2026-08-18",
290
- "subject": "release v27"
291
- },
292
- {
293
- "version": "v25",
294
- "sha": "bc24829",
295
- "date": "2026-08-14",
296
- "subject": "v25 - wave 32's LIVE build (deployed 2026-08-13, bc24829)"
297
- },
298
- {
299
- "version": "v26",
300
- "sha": "6a642e1",
301
- "date": "2026-08-14",
302
- "subject": "v26 - wave 33's build (deployed 2026-08-14, 6a642e1)"
303
- },
304
- {
305
- "version": "v24",
306
- "sha": "514d829",
307
- "date": "2026-08-09",
308
- "subject": "release v24"
309
- },
310
- {
311
- "version": "v23",
312
- "sha": "44cc283",
313
- "date": "2026-08-09",
314
- "subject": "release v23"
315
- },
316
- {
317
- "version": "v22",
318
- "sha": "f14e199",
319
- "date": "2026-08-09",
320
- "subject": "release v22"
321
- },
322
- {
323
- "version": "v21",
324
- "sha": "5fdffce",
325
- "date": "2026-08-09",
326
- "subject": "release v21"
327
- },
328
- {
329
- "version": "v20",
330
- "sha": "442e4a1",
331
- "date": "2026-08-09",
332
- "subject": "release v20"
333
- },
334
- {
335
- "version": "v19",
336
- "sha": "94cb4a4",
337
- "date": "2026-08-09",
338
- "subject": "release v19"
339
- },
340
- {
341
- "version": "v18",
342
- "sha": "0106ef9",
343
- "date": "2026-08-09",
344
- "subject": "release v18"
345
- },
346
- {
347
- "version": "v17",
348
- "sha": "308240c",
349
- "date": "2026-08-09",
350
- "subject": "release v17"
351
- },
352
- {
353
- "version": "v16",
354
- "sha": "a804df5",
355
- "date": "2026-08-09",
356
- "subject": "release v16"
357
- },
358
- {
359
- "version": "v15",
360
- "sha": "6b84d72",
361
- "date": "2026-08-09",
362
- "subject": "release v15"
363
- },
364
- {
365
- "version": "v14",
366
- "sha": "bee5eaf",
367
- "date": "2026-08-07",
368
- "subject": "release v14"
369
- },
370
- {
371
- "version": "v13",
372
- "sha": "314c0e3",
373
- "date": "2026-08-06",
374
- "subject": "release v13"
375
- },
376
- {
377
- "version": "v12",
378
- "sha": "4908f39",
379
- "date": "2026-08-06",
380
- "subject": "release v12"
381
- },
382
- {
383
- "version": "v11",
384
- "sha": "3126617",
385
- "date": "2026-08-05",
386
- "subject": "release v11"
387
- },
388
- {
389
- "version": "v10",
390
- "sha": "43f8042",
391
- "date": "2026-08-05",
392
- "subject": "release v10"
393
- },
394
- {
395
- "version": "v9",
396
- "sha": "2e26f57",
397
- "date": "2026-08-05",
398
- "subject": "release v9"
399
- },
400
- {
401
- "version": "v8",
402
- "sha": "8073b3e",
403
- "date": "2026-08-05",
404
- "subject": "release v8"
405
- },
406
- {
407
- "version": "v7",
408
- "sha": "b1c5a7e",
409
- "date": "2026-08-05",
410
- "subject": "release v7"
411
- },
412
- {
413
- "version": "v6",
414
- "sha": "a344020",
415
- "date": "2026-08-05",
416
- "subject": "release v6"
417
- },
418
- {
419
- "version": "v5",
420
- "sha": "c0b0fbb",
421
- "date": "2026-08-05",
422
- "subject": "release v5"
423
- },
424
- {
425
- "version": "v4",
426
- "sha": "de5037f",
427
- "date": "2026-08-05",
428
- "subject": "release v4"
429
- },
430
- {
431
- "version": "v3",
432
- "sha": "6b9fa62",
433
- "date": "2026-08-05",
434
- "subject": "release v3"
435
- },
436
- {
437
- "version": "v2",
438
- "sha": "fd05861",
439
- "date": "2026-08-04",
440
- "subject": "release v2"
441
- },
442
- {
443
- "version": "v1",
444
- "sha": "5b4e2c4",
445
- "date": "2026-08-04",
446
- "subject": "release v1"
447
- }
448
- ]
449
  }
 
1
  {
2
+ "current": "43f98c8",
3
+ "releases": []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 823ea84
 
1
+ 43f98c8
api/application_registry.py CHANGED
@@ -74,6 +74,34 @@ def finance_applications(may_open=None):
74
  return _finance_applications(may_open=may_open)
75
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  _FINANCE_SCOPES = {"business_unit", "hq_consolidated", "all_channel_inventory"}
78
 
79
 
@@ -425,6 +453,21 @@ def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starre
425
  return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
426
 
427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
429
  allowed_databases=None):
430
  payload=payload if isinstance(payload,dict) else {}
 
74
  return _finance_applications(may_open=may_open)
75
 
76
 
77
+ # R6: Finance records are read-only projections of finance_apps.py, never validated, created,
78
+ # mutated, or persisted. Adding "finance" to APPLICATION_TYPES buys nothing and weakens
79
+ # validate_application's governed type vocabulary.
80
+ def finance_application_records(may_open=None):
81
+ """Project the grant-filtered Finance catalogue as seeded Application records."""
82
+ return [
83
+ {"id": f"finance_{app['key']}",
84
+ "key": app["key"],
85
+ "name": app["navLabel"],
86
+ "type": "finance",
87
+ "templateKind": None,
88
+ "origin": "finance",
89
+ "permissionKey": app["permissionKey"],
90
+ "mode": app["mode"],
91
+ "question": app["question"],
92
+ "deepLink": app["deepLink"],
93
+ "compatibleDatabases": [],
94
+ "navPlacement": {"section": "finance", "order": index},
95
+ "openTarget": {"kind": "finance", "id": f"finance_{app['key']}", "type": "finance",
96
+ "database": None},
97
+ "capabilities": {"read": True, "edit": False, "share": False, "delete": False,
98
+ "duplicate": False, "star": False, "default": False},
99
+ "starred": False,
100
+ "isDefault": False}
101
+ for index, app in enumerate(finance_applications(may_open=may_open))
102
+ ]
103
+
104
+
105
  _FINANCE_SCOPES = {"business_unit", "hq_consolidated", "all_channel_inventory"}
106
 
107
 
 
453
  return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
454
 
455
 
456
+ def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_databases=None):
457
+ """The ONE generic navigation read for stored and seeded Application records (R6)."""
458
+ rows = [{"id": app["id"], "name": app.get("name"),
459
+ "type": app.get("type"), "templateKind": app.get("templateKind"),
460
+ "origin": "tenant",
461
+ "compatibleDatabases": app.get("compatibleDatabases") or [],
462
+ "openTarget": app.get("openTarget"),
463
+ "navPlacement": app.get("navPlacement") or {"section": "app", "order": index},
464
+ "capabilities": app.get("capabilities"), "starred": app.get("starred"),
465
+ "isDefault": app.get("isDefault")}
466
+ for index, app in enumerate(list_apps(runtime, user, is_admin,
467
+ allowed_databases=allowed_databases))]
468
+ return rows + finance_application_records(may_open=may_open)
469
+
470
+
471
  def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
472
  allowed_databases=None):
473
  payload=payload if isinstance(payload,dict) else {}
api/automation_engine.py CHANGED
@@ -62,36 +62,24 @@ AGENT_CONTRACT_KEY = "agent_contracts"
62
  AGENT_EVENT_TYPES = ("transcript", "message", "gathered_data", "run", "consent")
63
  AGENT_ACTIONS = ("read", "create", "update", "overwrite", "delete")
64
 
65
- # SDLC63 / C2 β€” one native preset, with two server-owned trigger shapes. These names are
66
- # deliberately separate from ``TRIGGER_KEYS``: the Sheet trigger is an application commit event,
67
- # not a choice in the general Automation builder, and the client must not be able to substitute a
68
- # third trigger merely by retaining this preset id.
69
- CUSTOMER_INTELLIGENCE_PRESET = "customer_intelligence"
70
- CUSTOMER_INTELLIGENCE_TRIGGER_KINDS = ("enters_view", "sheet_insight_changed")
71
- CUSTOMER_INTELLIGENCE_ACTION_KINDS = ("agent_insight", "slack")
72
- CUSTOMER_INTELLIGENCE_WATCH_CAP = 64
73
- CUSTOMER_INTELLIGENCE_BATCH_CAP = 128
74
- CUSTOMER_INTELLIGENCE_DIGEST_ROWS = 12
75
- CUSTOMER_INTELLIGENCE_RESULT_KEY = "_customerIntelligence"
76
-
77
-
78
- def customer_intelligence_contract():
79
- """The frozen C2 payload that View and Sheet settings mount independently."""
80
- return {
81
- "preset": CUSTOMER_INTELLIGENCE_PRESET,
82
- "triggers": [
83
- {"kind": "enters_view", "required": ["viewId"], "fixed": True},
84
- {"kind": "sheet_insight_changed",
85
- "required": ["workbookId", "sheetId", "watch"],
86
- "watch": {"ranges": "string[]", "bindings": "string[]"}, "fixed": True},
87
- ],
88
- "actions": [
89
- {"kind": "agent_insight", "required": ["agentId"]},
90
- {"kind": "slack", "required": ["destinationId"], "optional": True},
91
- ],
92
- "enabledByDefault": False,
93
- "dryRunDispatches": False,
94
- }
95
  #: ⭐⭐ W47-T21 / R3 β€” THE THREE NAMED REASONS AN AGENT'S ROW FILTER REFUSES WITH.
96
  #:
97
  #: R3, verbatim: an agent's row filter is *"its whole world: it may neither read nor write a
@@ -2236,85 +2224,6 @@ def _drop_ig_seeds(flow_raw, table, enrich_kind="enrich_instagram"):
2236
  return {**flow, "actions": kept}
2237
 
2238
 
2239
- def _customer_intelligence_watch(raw, label):
2240
- """One bounded, de-duplicated C2 watch list, or a user-facing validation sentence."""
2241
- if raw in (None, ""):
2242
- return [], None
2243
- if not isinstance(raw, list):
2244
- return None, f"the Sheet insight {label} watch must be a list"
2245
- out = []
2246
- for value in raw:
2247
- token = _s(value, 160).strip()
2248
- if token and token not in out:
2249
- out.append(token)
2250
- if len(out) > CUSTOMER_INTELLIGENCE_WATCH_CAP:
2251
- return None, (f"a Sheet insight trigger watches at most "
2252
- f"{CUSTOMER_INTELLIGENCE_WATCH_CAP} {label}")
2253
- return out, None
2254
-
2255
-
2256
- def clean_customer_intelligence_trigger(raw, previous=None):
2257
- """Validate C2's fixed trigger without widening the general trigger picker vocabulary."""
2258
- if not isinstance(raw, dict):
2259
- return None, "the customer-intelligence trigger must be an object"
2260
- prev = previous if isinstance(previous, dict) else {}
2261
- key = _s(raw.get("kind") or raw.get("key") or prev.get("kind") or prev.get("key"),
2262
- 40).strip()
2263
- if key not in CUSTOMER_INTELLIGENCE_TRIGGER_KINDS:
2264
- return None, ("customer intelligence has exactly two fixed triggers: "
2265
- + ", ".join(CUSTOMER_INTELLIGENCE_TRIGGER_KINDS))
2266
- prior_key = _s(prev.get("kind") or prev.get("key"), 40).strip()
2267
- if prior_key and prior_key != key:
2268
- return None, "a native customer-intelligence setting cannot change its fixed trigger"
2269
- # New presets are OFF even if the generic trigger default is on. A later explicit enable is
2270
- # accepted only after the action/source completeness check in ``clean_definition``.
2271
- enabled = (bool(raw.get("enabled")) if "enabled" in raw else
2272
- (bool(prev.get("enabled")) if prev else False))
2273
- out = {"kind": key, "key": key, "enabled": enabled,
2274
- "paused": bool(raw.get("paused")) if "paused" in raw else bool(prev.get("paused"))}
2275
- if key == "enters_view":
2276
- out["viewId"] = _s(raw.get("viewId") if "viewId" in raw else prev.get("viewId"),
2277
- 80).strip()
2278
- if prev.get("viewId") and out["viewId"] != prev.get("viewId"):
2279
- return None, "a View-native customer-intelligence setting cannot move to another View"
2280
- else:
2281
- for name in ("workbookId", "sheetId"):
2282
- out[name] = _s(raw.get(name) if name in raw else prev.get(name), 120).strip()
2283
- if prev.get(name) and out[name] != prev.get(name):
2284
- return None, ("a Sheet-native customer-intelligence setting cannot move to "
2285
- f"another {name[:-2]}")
2286
- watch_raw = raw.get("watch") if "watch" in raw else prev.get("watch")
2287
- watch_raw = watch_raw if isinstance(watch_raw, dict) else {}
2288
- ranges, problem = _customer_intelligence_watch(watch_raw.get("ranges"), "ranges")
2289
- if problem:
2290
- return None, problem
2291
- bindings, problem = _customer_intelligence_watch(watch_raw.get("bindings"), "bindings")
2292
- if problem:
2293
- return None, problem
2294
- out["watch"] = {"ranges": ranges, "bindings": bindings}
2295
- out["configured"] = False # refined after config + actions are validated
2296
- return out, None
2297
-
2298
-
2299
- def _customer_intelligence_complete(trigger, config, flow):
2300
- actions = list((flow or {}).get("actions") or [])
2301
- if not actions or actions[0].get("kind") != "agent_insight":
2302
- return False
2303
- agent_id = str((actions[0].get("config") or {}).get("agentId") or "").strip()
2304
- if not agent_id:
2305
- return False
2306
- slack = actions[1] if len(actions) > 1 else None
2307
- if slack and slack.get("enabled", True) and not str(
2308
- (slack.get("config") or {}).get("destinationId") or "").strip():
2309
- return False
2310
- key = str((trigger or {}).get("kind") or (trigger or {}).get("key") or "")
2311
- if key == "enters_view":
2312
- return bool(trigger.get("viewId") and (config or {}).get("targetTable"))
2313
- watch = trigger.get("watch") or {}
2314
- return bool(trigger.get("workbookId") and trigger.get("sheetId")
2315
- and (watch.get("ranges") or watch.get("bindings")))
2316
-
2317
-
2318
  def ig_action_pinned(defn, index):
2319
  """Is this action the one that cannot be removed? Derived, never stored β€” a stored `pinned`
2320
  flag is a second copy of the rule, and the copy is what a hand-written PATCH omits."""
@@ -2329,27 +2238,23 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
2329
  raw = raw if isinstance(raw, dict) else {}
2330
  prev = previous or {}
2331
  preset = _s(raw.get("preset") if "preset" in raw else prev.get("preset"), 60).strip()
2332
- if preset and preset != CUSTOMER_INTELLIGENCE_PRESET:
 
 
2333
  return None, f"unknown automation preset {preset!r}"
2334
- if prev.get("preset") and preset != prev.get("preset"):
2335
- return None, "an automation cannot change or remove its native preset"
2336
  # ⭐ WAVE 24 Β· C-TRIG β€” THE TRIGGER IS RESOLVED FIRST NOW, because law 1 makes it the thing
2337
  # that CHOOSES the kind. Reading `raw["trigger"]["key"]` here instead would be a second
2338
  # reader of the trigger vocabulary, free to disagree with `clean_trigger` about which keys
2339
  # exist and which are refused. Gate-visible consequence, recorded in AMENDMENT A1: a payload
2340
  # invalid in BOTH its trigger and its config now answers with the trigger's sentence.
2341
  trigger_raw = raw.get("trigger") if "trigger" in raw else prev.get("trigger")
2342
- trigger, terr = (clean_customer_intelligence_trigger(trigger_raw, prev.get("trigger"))
2343
- if preset == CUSTOMER_INTELLIGENCE_PRESET
2344
- else clean_trigger(trigger_raw, prev.get("trigger")))
2345
  if terr:
2346
  return None, terr
2347
  # C-TRIG law 2 (wave 24): a definition that names no kind is a `plain` one. Before R6 this
2348
  # refused with "unknown automation kind ''" β€” correct while a wizard always sent one, and a
2349
  # dead end the moment the wizard was deleted and the client's create body became {name}.
2350
  kind = _s(raw.get("kind") or prev.get("kind"), 40) or DEFAULT_KIND
2351
- if preset == CUSTOMER_INTELLIGENCE_PRESET and kind != DEFAULT_KIND:
2352
- return None, "customer intelligence uses the existing plain action executor"
2353
  drop_ig_seeds = False
2354
  if (trigger or {}).get("key") == "ig_profile_match":
2355
  # LAW 1: the trigger IS how `discover_instagram` gets chosen now. Unconditional rather
@@ -2517,25 +2422,6 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
2517
  flow, ferr = clean_flow(flow_raw, prev.get("flow"), notes=notes, rt=rt)
2518
  if ferr:
2519
  return None, ferr
2520
- if preset != CUSTOMER_INTELLIGENCE_PRESET and any(
2521
- action.get("kind") in CUSTOMER_INTELLIGENCE_ACTION_KINDS
2522
- for action in walk_actions(flow.get("actions") or [])):
2523
- return None, "agent_insight and governed Slack are available only in customer intelligence"
2524
- if preset == CUSTOMER_INTELLIGENCE_PRESET:
2525
- actions = list(flow.get("actions") or [])
2526
- kinds = [str(action.get("kind") or "") for action in actions]
2527
- if not actions or actions[0].get("kind") != "agent_insight" \
2528
- or len(actions) > 2 or any(kind not in CUSTOMER_INTELLIGENCE_ACTION_KINDS
2529
- for kind in kinds) \
2530
- or (len(actions) == 2 and actions[1].get("kind") != "slack"):
2531
- return None, ("customer intelligence needs one agent_insight action followed only "
2532
- "by an optional governed slack action")
2533
- if schedule.get("enabled"):
2534
- return None, "customer intelligence runs only from its fixed event trigger"
2535
- trigger["configured"] = _customer_intelligence_complete(trigger, config, flow)
2536
- if trigger.get("enabled") and not trigger["configured"]:
2537
- return None, ("choose the source watch, Agent, and any enabled Slack destination "
2538
- "before enabling customer intelligence")
2539
  # ⭐ WAVE 30 β€” widened with the seeder above: TikTok now HAS a pinned step 1, so the rule that
2540
  # its `config.table` is authoritative has to reach it, or the two fields that name one database
2541
  # would disagree on exactly the network that just gained the card.
@@ -2625,7 +2511,6 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
2625
  # ⚠ Same shape and same reason as the pre-set FIELD flag, which DESIGN.md Β§4 already
2626
  # describes as "sticky across a PATCH". One idea, one behaviour, two objects.
2627
  **({"system": _s(prev.get("system"), 40)} if prev.get("system") else {}),
2628
- **({"preset": preset} if preset else {}),
2629
  }, None
2630
 
2631
 
@@ -2758,6 +2643,56 @@ def retire_automation_board_state(rt, tables=None):
2758
  return {"definitions": len(plan), **fields}
2759
 
2760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2761
  #: ⭐⭐ WAVE 31 Β· T35 (D-134) β€” the definitions memo, and the two things that make it safe.
2762
  #: `tenant -> (monotonic_at, defs)`. Read ONLY through `all_definitions(..., cached=True)`, which
2763
  #: exactly one caller uses (`grid_hook`).
@@ -2835,7 +2770,8 @@ def all_definitions(rt, cached=False):
2835
  raw = dict(rt.get(STORE_KEY) or {})
2836
  except Exception:
2837
  return {}
2838
- out = {str(aid): _without_retired_board(defn)[0] for aid, defn in raw.items()}
 
2839
  if cached:
2840
  _DEFS_MEMO[str(getattr(rt, "key", "") or "")] = (time.monotonic(), out)
2841
  return out
@@ -2953,8 +2889,8 @@ def agent_contract_dto(rt, agent_id):
2953
 
2954
  def authorize_agent_principal(rt, agent_id, actor, is_admin=False):
2955
  rec = _agent_contracts(rt).get(str(agent_id or ""))
2956
- # An admin may read a live private Agent; that role cannot resurrect a deleted selection
2957
- # or replace the user identity needed by a background customer-intelligence run.
2958
  if not str(actor or "").strip() or not isinstance(rec, dict) or not rec:
2959
  raise PermissionError("this Agent or its principal is no longer available")
2960
  sharing = rec.get("sharing") or {}
@@ -3270,241 +3206,6 @@ def governed_agent_query_dry_run(rt, agent_id, workflow_id, table, field, prompt
3270
  return {"query": copy.deepcopy(result), "noProviderCalls": True, "providerCalls": 0}
3271
 
3272
 
3273
- # C2 generation must be mounted before execution. A change-count summary is not an Agent insight
3274
- # and must never create a successful run event or authorize a success notification.
3275
- _CUSTOMER_INTELLIGENCE_INSIGHT = [None]
3276
-
3277
-
3278
- def _customer_intelligence_actions(defn):
3279
- actions = list(((defn or {}).get("flow") or {}).get("actions") or [])
3280
- insight = actions[0] if actions and actions[0].get("kind") == "agent_insight" else None
3281
- slack = actions[1] if len(actions) > 1 and actions[1].get("kind") == "slack" else None
3282
- return insight, slack
3283
-
3284
-
3285
- def customer_intelligence_authorized(rt, defn, actor="", is_admin=False):
3286
- """Re-resolve the creator, selected Agent and source immediately before execution."""
3287
- insight, _slack = _customer_intelligence_actions(defn)
3288
- cfg = (insight or {}).get("config") or {}
3289
- agent_id = str(cfg.get("agentId") or "").strip()
3290
- owner = str(actor or (defn or {}).get("createdBy") or "").strip()
3291
- if not agent_id or not owner:
3292
- raise PermissionError("customer intelligence has no active Agent principal")
3293
-
3294
- # Resolve both background owners and interactive actors at this boundary. A previously
3295
- # authenticated caller's role hint cannot outlive account, role or database revocation.
3296
- import core.users as user_registry
3297
- import core.perms as permission_rules
3298
- import core.perm_scope as permission_scope
3299
- raw = (user_registry.registry() or {}).get(owner)
3300
- if not isinstance(raw, dict) or raw.get("active", True) is False:
3301
- raise PermissionError("the customer-intelligence owner is inactive or unavailable")
3302
- public = user_registry._public(owner, raw)
3303
- tenant = str(public.get("tenant") or "").strip().lower()
3304
- if not tenant or tenant != str(getattr(rt, "key", "") or "").strip().lower():
3305
- raise PermissionError("the customer-intelligence owner is outside this workspace")
3306
- is_admin = permission_rules.is_admin(public)
3307
- authorize_agent_principal(rt, agent_id, owner, is_admin=is_admin)
3308
-
3309
- trigger = (defn or {}).get("trigger") or {}
3310
- key = str(trigger.get("kind") or trigger.get("key") or "")
3311
- if key == "enters_view":
3312
- table = _flow_table(defn)
3313
- if not table or not permission_scope.may_read(public, table, st=rt):
3314
- raise PermissionError("View source permission was revoked before Agent execution")
3315
- elif key == "sheet_insight_changed":
3316
- from core import sheets
3317
- try:
3318
- book = sheets.get_workbook(rt, trigger.get("workbookId"))
3319
- except sheets.SheetRefusal as exc:
3320
- raise PermissionError("the watched workbook is no longer readable") from exc
3321
- role = sheets.workbook_role(rt, book, owner, is_admin=bool(is_admin))
3322
- if not sheets.may_read_workbook(book, role):
3323
- raise PermissionError("Sheet permission was revoked before Agent execution")
3324
- try:
3325
- sheets.find_tab(book, trigger.get("sheetId"))
3326
- except sheets.SheetRefusal as exc:
3327
- raise PermissionError("the watched Sheet no longer exists") from exc
3328
- else:
3329
- raise PermissionError("customer intelligence has an unsupported trigger")
3330
- return True
3331
-
3332
-
3333
- def customer_intelligence_execute(rt, defn, rows=None, *, dry_run=False,
3334
- permission_check=None, insight_generator=None):
3335
- """Run C2's Agent action once. Slack remains a later, separately authorized run door."""
3336
- if (defn or {}).get("preset") != CUSTOMER_INTELLIGENCE_PRESET:
3337
- raise ValueError("this is not a customer-intelligence automation")
3338
- check = permission_check or (lambda d: customer_intelligence_authorized(rt, d))
3339
- if check(defn) is False:
3340
- raise PermissionError("customer-intelligence permission was revoked before execution")
3341
- insight_action, _slack = _customer_intelligence_actions(defn)
3342
- cfg = (insight_action or {}).get("config") or {}
3343
- if not cfg.get("agentId"):
3344
- raise PermissionError("choose an Agent before customer intelligence can run")
3345
- trigger = (defn or {}).get("trigger") or {}
3346
- event = dict(((defn or {}).get("state") or {}).get("customerIntelligenceEvent") or {})
3347
- context = {
3348
- "automationId": str((defn or {}).get("id") or ""),
3349
- "agentId": str(cfg.get("agentId") or ""),
3350
- "workflowId": str(cfg.get("workflowId") or "wf_main"),
3351
- "triggerKind": str(trigger.get("kind") or trigger.get("key") or ""),
3352
- "rowIds": [str(value) for value in (rows or [])][:CUSTOMER_INTELLIGENCE_DIGEST_ROWS],
3353
- "batchId": str(event.get("batchId") or ""),
3354
- "recordCount": max(0, int(event.get("recordCount") or len(rows or []))),
3355
- "changedRanges": list(event.get("ranges") or [])[:CUSTOMER_INTELLIGENCE_WATCH_CAP],
3356
- "changedBindings": list(event.get("bindings") or [])[:CUSTOMER_INTELLIGENCE_WATCH_CAP],
3357
- }
3358
- generator = insight_generator or _CUSTOMER_INTELLIGENCE_INSIGHT[0]
3359
- if callable(generator):
3360
- generated = generator(str(cfg.get("prompt") or ""), copy.deepcopy(context))
3361
- if isinstance(generated, dict):
3362
- text = str(generated.get("text") or generated.get("insight") or "").strip()
3363
- else:
3364
- text = str(generated or "").strip()
3365
- if not text:
3366
- raise ValueError("the selected Agent returned no insight")
3367
- else:
3368
- raise ValueError("The selected Agent's insight generator is unavailable.")
3369
- text = " ".join(text.split())[:2000]
3370
- if not dry_run:
3371
- append_agent_event(rt, cfg.get("agentId"), "run", {
3372
- "state": "ok", "workflowId": cfg.get("workflowId") or "wf_main",
3373
- "evidence": "customer_intelligence",
3374
- }, actor=str((defn or {}).get("createdBy") or "automation"))
3375
- return {"insight": text, "agentId": str(cfg.get("agentId") or ""),
3376
- "workflowId": str(cfg.get("workflowId") or "wf_main"),
3377
- "dryRun": bool(dry_run), "context": context}
3378
-
3379
-
3380
- def customer_intelligence_preview(rt, defn, *, rows=None, permission_check=None,
3381
- insight_generator=None):
3382
- """C2 preview: exercise validation/generation and prove the dispatch door was not called."""
3383
- result = customer_intelligence_execute(
3384
- rt, defn, rows=rows, dry_run=True, permission_check=permission_check,
3385
- insight_generator=insight_generator)
3386
- return {**result, "receipt": {"dryRun": True, "noDispatch": True,
3387
- "dispatchCount": 0, "providerCalls": 0}}
3388
-
3389
-
3390
- _A1_RANGE = re.compile(r"^\$?([A-Z]{1,4})\$?([1-9][0-9]*)(?::\$?([A-Z]{1,4})\$?([1-9][0-9]*))?$")
3391
-
3392
-
3393
- def _a1_column(value):
3394
- out = 0
3395
- for char in str(value or ""):
3396
- out = out * 26 + ord(char) - 64
3397
- return out
3398
-
3399
-
3400
- def _a1_box(value):
3401
- found = _A1_RANGE.fullmatch(str(value or "").strip().upper())
3402
- if not found:
3403
- return None
3404
- c0, r0 = _a1_column(found.group(1)), int(found.group(2))
3405
- c1 = _a1_column(found.group(3) or found.group(1))
3406
- r1 = int(found.group(4) or found.group(2))
3407
- return min(c0, c1), min(r0, r1), max(c0, c1), max(r0, r1)
3408
-
3409
-
3410
- def _ranges_overlap(left, right):
3411
- a, b = _a1_box(left), _a1_box(right)
3412
- return bool(a and b and a[0] <= b[2] and b[0] <= a[2]
3413
- and a[1] <= b[3] and b[1] <= a[3])
3414
-
3415
-
3416
- def _customer_intelligence_event_matches(trigger, event):
3417
- kinds = {str(value).strip().lower() for value in (event.get("changeKinds") or [])}
3418
- if event.get("changeKind"):
3419
- kinds.add(str(event.get("changeKind")).strip().lower())
3420
- if not event.get("committed") or not (kinds & {"value", "binding"}):
3421
- return False
3422
- watch = trigger.get("watch") or {}
3423
- changed_ranges = [str(v) for v in (event.get("ranges") or event.get("changedRanges") or [])]
3424
- changed_bindings = {str(v) for v in
3425
- (event.get("bindings") or event.get("changedBindings") or [])}
3426
- range_hit = "value" in kinds and any(
3427
- _ranges_overlap(watched, changed)
3428
- for watched in (watch.get("ranges") or []) for changed in changed_ranges)
3429
- binding_hit = "binding" in kinds and bool(
3430
- set(str(v) for v in (watch.get("bindings") or [])) & changed_bindings)
3431
- return bool(range_hit or binding_hit)
3432
-
3433
-
3434
- def _claim_customer_intelligence_batch(rt, auto_id, event):
3435
- """Atomically accept a committed Sheet batch once, before any Agent/Slack work can start."""
3436
- accepted = [False]
3437
- batch_id = str(event.get("batchId") or "").strip()
3438
- if not batch_id:
3439
- return False
3440
-
3441
- def update(cur):
3442
- cur = cur if isinstance(cur, dict) else {}
3443
- definition = cur.get(str(auto_id))
3444
- if not isinstance(definition, dict):
3445
- return cur
3446
- state = dict(definition.get("state") or {})
3447
- seen = [str(v) for v in (state.get("customerIntelligenceBatches") or [])]
3448
- if batch_id in seen:
3449
- return cur
3450
- state["customerIntelligenceBatches"] = [*seen, batch_id][-CUSTOMER_INTELLIGENCE_BATCH_CAP:]
3451
- state["customerIntelligenceEvent"] = {
3452
- "batchId": batch_id,
3453
- "recordCount": max(0, int(event.get("recordCount") or 0)),
3454
- "ranges": [str(v) for v in (event.get("ranges") or event.get("changedRanges") or [])
3455
- ][:CUSTOMER_INTELLIGENCE_WATCH_CAP],
3456
- "bindings": [str(v) for v in
3457
- (event.get("bindings") or event.get("changedBindings") or [])
3458
- ][:CUSTOMER_INTELLIGENCE_WATCH_CAP],
3459
- }
3460
- definition["state"] = state
3461
- accepted[0] = True
3462
- return cur
3463
-
3464
- _store_update(rt, update, flush="sync")
3465
- return accepted[0]
3466
-
3467
-
3468
- def sheet_insight_committed(rt, event, *, permission_check=None, fire=None, log=print):
3469
- """Adapt one settled Sheet commit/import/refresh to at most one run per matching preset."""
3470
- body = event if isinstance(event, dict) else {}
3471
- workbook = str(body.get("workbookId") or "").strip()
3472
- sheet = str(body.get("sheetId") or "").strip()
3473
- batch = str(body.get("batchId") or "").strip()
3474
- if not workbook or not sheet or not batch:
3475
- return {"started": [], "deduplicated": [], "ignored": "incomplete_event",
3476
- "definitionReads": 0, "runCount": 0}
3477
- definitions = all_definitions(rt) # exactly once, including a 20,000-record batch
3478
- started, deduped = [], []
3479
- tenant = str(getattr(rt, "key", "") or "royal-imports")
3480
- launch = fire or (lambda aid: trigger_fire(rt, tenant, aid, log=log))
3481
- for aid, definition in definitions.items():
3482
- if (definition or {}).get("preset") != CUSTOMER_INTELLIGENCE_PRESET:
3483
- continue
3484
- trigger = (definition or {}).get("trigger") or {}
3485
- if str(trigger.get("kind") or trigger.get("key") or "") != "sheet_insight_changed" \
3486
- or trigger.get("paused") or not trigger.get("enabled") \
3487
- or not trigger.get("configured") \
3488
- or str(trigger.get("workbookId") or "") != workbook \
3489
- or str(trigger.get("sheetId") or "") != sheet \
3490
- or not _customer_intelligence_event_matches(trigger, body):
3491
- continue
3492
- if permission_check is not None and permission_check(definition) is False:
3493
- continue
3494
- if not _claim_customer_intelligence_batch(rt, aid, body):
3495
- deduped.append(str(aid))
3496
- continue
3497
- if launch(str(aid)):
3498
- started.append(str(aid))
3499
- return {"started": started, "deduplicated": deduped, "definitionReads": 1,
3500
- "runCount": len(started)}
3501
-
3502
-
3503
- def workbook_insight_committed(rt, events):
3504
- """The core workbook writer's injected consumer, shared by HTTP, import and SDK writes."""
3505
- return [sheet_insight_committed(rt, event) for event in events]
3506
-
3507
-
3508
  def set_semantic_readiness(rt, agent_id, fields):
3509
  rows = fields if isinstance(fields, list) else []
3510
  clean = [{"database": str(row.get("database") or ""), "field": str(row.get("field") or ""),
@@ -9287,13 +8988,6 @@ def run_plain(rt, defn, username="automation", log=print, step=_no_step, rows=No
9287
  # `apply_actions` arm.
9288
  if is_statement_flow(defn):
9289
  return run_statements(rt, defn, username=username, log=log, step=step)
9290
- if (defn or {}).get("preset") == CUSTOMER_INTELLIGENCE_PRESET:
9291
- # The event adapter already selected the settled rows/batch. The ordinary action executor
9292
- # below remains the one action door; this runner must not expand a Sheet event into a
9293
- # table walk merely because a plain automation normally does.
9294
- affected = [str(value) for value in (rows or [])]
9295
- return ("ok", "Customer intelligence processed one settled event.",
9296
- {"events": 1}, affected, {})
9297
  table = _flow_table(defn)
9298
  if not table:
9299
  return ("partial",
@@ -10163,7 +9857,6 @@ WEB_REQUIRED = {
10163
  #: that read off this route; putting it back to draw a label would undo the wave before this one).
10164
  ACTION_REQUIRED = dict(WEB_REQUIRED)
10165
  ACTION_REQUIRED["voice_agent"] = (("a Voice agent", "voiceAgentId"),)
10166
- ACTION_REQUIRED["agent_insight"] = (("an Agent", "agentId"),)
10167
  #: ⭐ W31-T38 (C5) β€” the web step's own clamps. `20000` matches the default E's seam documents;
10168
  #: the ceiling exists because this blocks the record walk (~9-32 s of cold start ALREADY), and an
10169
  #: automation that can be configured to wait ten minutes per record is a stalled run, not a slow one.
@@ -10231,11 +9924,6 @@ ACTION_CATALOG = [
10231
  # hidden row's label is still rendered on a STORED step's card, so leaving the six captions in
10232
  # place would have kept them on screen for exactly the people who already use them. They now
10233
  # name the mechanism instead, and no old caption survives as a substring in any case.
10234
- # C2's action is hidden from the general builder: it is created only by the native View/Sheet
10235
- # preset, while remaining a real catalog kind so the ordinary validator and executor own it.
10236
- {"kind": "agent_insight", "label": "Generate customer insight", "group": "Agent",
10237
- "ready": True, "menu": False,
10238
- "detail": "Run the selected governed Agent once for a native customer-intelligence event"},
10239
  {"kind": "ai_agent", "label": "Web agent", "group": "Agent", "ready": True,
10240
  "detail": "Describe a job on a website in words; the agent works out the steps, runs them in "
10241
  "a browser and reports what it actually did"},
@@ -10349,9 +10037,6 @@ ACTION_CATALOG = [
10349
  "ready": True, "menu": False,
10350
  "detail": "Fill an AI column for the records this flow walks. Configured on the column, not "
10351
  "here"},
10352
- {"kind": "slack", "label": "Send governed Slack digest", "group": "Connected",
10353
- "ready": True, "menu": False,
10354
- "detail": "Send one permission-filtered digest through an explicitly granted Slack agent"},
10355
  # ── 4. ADVANCED LOGIC ────────────────────────────────────────────────────────────────────
10356
  # `group` is relabelled "If / then" (C-ACT): "Conditional logic" described the mechanism,
10357
  # and R8 made it a FORK with lettered branches, which is a thing people already have a name
@@ -10950,22 +10635,6 @@ def _clean_action_config(kind, cfg, depth, seen, count, notes=None, rt=None):
10950
  if voice_id and not re.fullmatch(r"va_[A-Za-z0-9_\-]{4,110}", voice_id):
10951
  return None, "select a Voice agent from Loopable rather than entering a provider id"
10952
  return {"voiceAgentId": voice_id}, None
10953
- if kind == "agent_insight":
10954
- # A stored Agent id is a local reference, never a provider/model id. Blank is the native
10955
- # setting's visible-but-off draft; ACTION_REQUIRED and the preset activation wall refuse
10956
- # execution until it is selected.
10957
- agent_id = _s(cfg.get("agentId"), 120).strip()
10958
- workflow_id = _s(cfg.get("workflowId"), 120).strip() or "wf_main"
10959
- prompt = " ".join(_s(cfg.get("prompt"), 1000).split())
10960
- return {"agentId": agent_id, "workflowId": workflow_id, "prompt": prompt}, None
10961
- if kind == "slack":
10962
- destination = _s(cfg.get("destinationId"), 120).strip()
10963
- try:
10964
- cap = int(cfg.get("digestRows") or CUSTOMER_INTELLIGENCE_DIGEST_ROWS)
10965
- except (TypeError, ValueError):
10966
- return None, "the Slack digest row cap must be a whole number"
10967
- return {"destinationId": destination,
10968
- "digestRows": max(1, min(cap, CUSTOMER_INTELLIGENCE_DIGEST_ROWS))}, None
10969
  if kind == "ai_agent":
10970
  # ⭐⭐ W33-T56 β€” THE FUZZY STEP'S CONFIG. Same posture as the web arm below in every
10971
  # respect that matters: an ALLOWLIST, a shape test on the url, a clamped timeout, and an
@@ -11687,22 +11356,6 @@ def apply_actions(rt, defn, table_key, row_ids, username="automation", log=print
11687
  # cannot report a refusal.
11688
  counts = {"actionsRun": 0, "updated": 0, "created": 0, "found": 0,
11689
  "webRead": 0, "webBlocked": 0}
11690
- if (defn or {}).get("preset") == CUSTOMER_INTELLIGENCE_PRESET:
11691
- # A native event is one insight action, regardless of how many records/cells were in its
11692
- # settled batch. Keeping this inside ``apply_actions`` reuses the one action executor that
11693
- # every run already reaches; it also prevents a 20,000-record import from becoming 20,000
11694
- # Agent calls.
11695
- try:
11696
- generated = customer_intelligence_execute(rt, defn, rows=row_ids)
11697
- except (PermissionError, ValueError) as exc:
11698
- log(f"[aios-auto] customer intelligence refused: {exc}")
11699
- counts["insightBlocked"] = 1
11700
- counts[RUN_NOTES_KEY] = [str(exc)[:240]]
11701
- return counts
11702
- counts["actionsRun"] = 1
11703
- counts["insightGenerated"] = 1
11704
- counts[CUSTOMER_INTELLIGENCE_RESULT_KEY] = generated
11705
- return counts
11706
  #: W31-T38 β€” the once-per-run markers the web arm uses, so an unconfigured step says so ONCE
11707
  #: rather than once per record. Same shape as the enrich accumulators' `notes`.
11708
  web_notes = []
@@ -16297,19 +15950,6 @@ def dispatch_authorized_slack_automation(rt, defn, result=None, *, post=None):
16297
  stored = all_definitions(rt).get(aid)
16298
  if not isinstance(stored, dict):
16299
  return {"sent": False, "reason": "unknown_automation"}
16300
- if stored.get("preset") == CUSTOMER_INTELLIGENCE_PRESET:
16301
- # The runner also reaches delivery after an action refuses. Verify the actual result
16302
- # before reading a recipient's data or composing a sentence claiming generation succeeded.
16303
- action, _slack = _customer_intelligence_actions(stored)
16304
- cfg = (action or {}).get("config") or {}
16305
- generated = (result or {}).get("insight")
16306
- if (str((result or {}).get("state") or "") != "ok"
16307
- or not isinstance(generated, dict)
16308
- or generated.get("dryRun") is not False
16309
- or not str(generated.get("insight") or "").strip()
16310
- or generated.get("agentId") != cfg.get("agentId")
16311
- or generated.get("workflowId") != (cfg.get("workflowId") or "wf_main")):
16312
- return {"sent": False, "reason": "insight_not_generated"}
16313
  trigger = stored.get("trigger") if isinstance(stored.get("trigger"), dict) else {}
16314
  schedule = stored.get("schedule") if isinstance(stored.get("schedule"), dict) else {}
16315
  trigger_key = str(trigger.get("key") or "").strip()
@@ -16326,37 +15966,7 @@ def dispatch_authorized_slack_automation(rt, defn, result=None, *, post=None):
16326
  context = routes_slack.automation_answer_context(rt, aid)
16327
  if context is None:
16328
  return {"sent": False, "reason": "not_authorized"}
16329
- if stored.get("preset") == CUSTOMER_INTELLIGENCE_PRESET:
16330
- _insight_action, slack_action = _customer_intelligence_actions(stored)
16331
- slack_cfg = (slack_action or {}).get("config") or {}
16332
- if not slack_action or slack_action.get("enabled", True) is False:
16333
- return {"sent": False, "reason": "not_configured"}
16334
- destination = str(slack_cfg.get("destinationId") or "").strip()
16335
- if not destination or destination != str(context.get("agentId") or ""):
16336
- return {"sent": False, "reason": "not_authorized"}
16337
- trigger = stored.get("trigger") or {}
16338
- trigger_kind = str(trigger.get("kind") or trigger.get("key") or "")
16339
- fields, rows, module, links = [], [], "", []
16340
- if trigger_kind == "enters_view":
16341
- module = _flow_table(stored)
16342
- table = ut_get(rt, module) or {}
16343
- fields = list(table.get("fields") or [])
16344
- row_ids = [str(value) for value in ((result or {}).get("rowIds") or [])]
16345
- source_rows = table.get("rows") or {}
16346
- rows = [{"pid": rid, **dict(source_rows.get(rid) or {})} for rid in row_ids]
16347
- links = [f"#/data?database={quote(module, safe='')}&view="
16348
- f"{quote(str(trigger.get('viewId') or ''), safe='')}"]
16349
- else:
16350
- links = [f"#/sheet?wb={quote(str(trigger.get('workbookId') or ''), safe='')}"
16351
- f"&tab={quote(str(trigger.get('sheetId') or ''), safe='')}"]
16352
- text = routes_slack.permission_safe_automation_digest(
16353
- rt, context, module=module, fields=fields, rows=rows,
16354
- summary="Customer intelligence generated one permission-filtered insight.",
16355
- links=links, limit=slack_cfg.get("digestRows") or CUSTOMER_INTELLIGENCE_DIGEST_ROWS)
16356
- if not text:
16357
- return {"sent": False, "reason": "not_authorized"}
16358
- else:
16359
- text = _automation_slack_reply_text(result)
16360
  return routes_slack.deliver_channel_reply(
16361
  rt, context["channel"], text, principal=context["principal"], automation_id=aid,
16362
  provenance={"basis": "model_guidance", "citationIds": [], "modelGuidance": False},
@@ -16455,20 +16065,15 @@ def run_now(rt, tenant, auto_id, username="automation", log=print, rows=None):
16455
  # NOTHING β€” the branch where every candidate was a known-dead handle, i.e. exactly the
16456
  # run a person stares at wondering why the automation stopped doing anything.
16457
  run_notes = list((counts or {}).pop(RUN_NOTES_KEY, None) or [])
16458
- customer_insight = None
16459
  try:
16460
  a_counts = apply_actions(rt, defn, _flow_table(defn), affected or [],
16461
  username=username, log=log,
16462
  step=lambda text: _step(tenant, auto_id, text))
16463
- customer_insight = a_counts.pop(CUSTOMER_INTELLIGENCE_RESULT_KEY, None)
16464
  # ⭐⭐ D-103 β€” POPPED BEFORE THE MERGE. The per-record reasons ride inside `counts` so
16465
  # the runner contract keeps its shape, and they must leave before the merge or they
16466
  # would be a "count" everywhere downstream.
16467
  run_notes += list(a_counts.pop(RUN_NOTES_KEY, None) or [])
16468
  counts = {**(counts or {}), **{k: v for k, v in a_counts.items() if v}}
16469
- if a_counts.get("insightBlocked"):
16470
- state = "partial" if state != "error" else state
16471
- summary += ". The insight could not be generated; see the run notes"
16472
  if a_counts.get("enrichMetricBatchesPending"):
16473
  batches = int(a_counts["enrichMetricBatchesPending"])
16474
  state = "partial" if state != "error" else state
@@ -16538,11 +16143,9 @@ def run_now(rt, tenant, auto_id, username="automation", log=print, rows=None):
16538
  try:
16539
  dispatch_authorized_slack_automation(
16540
  rt, defn, {"state": state, "summary": summary,
16541
- "insight": customer_insight, "rowIds": affected or []})
16542
  except Exception as e: # noqa: BLE001
16543
  log(f"[aios-auto] Slack notification for {auto_id} failed: {type(e).__name__}: {e}")
16544
- if defn.get("preset") == CUSTOMER_INTELLIGENCE_PRESET:
16545
- set_state(rt, auto_id, {"customerIntelligenceEvent": None})
16546
  return _commit_run(rt, auto_id, state, summary, counts, state != "error", affected,
16547
  steps, notes=run_notes)
16548
  finally:
 
62
  AGENT_EVENT_TYPES = ("transcript", "message", "gathered_data", "run", "consent")
63
  AGENT_ACTIONS = ("read", "create", "update", "overwrite", "delete")
64
 
65
+ #: MIGRATION NOTE (SDLC 64 / R3, 2026-09-21) β€” the only surviving occurrence of the
66
+ #: removed preset name. D-295 records why this must remain: a person's stored automation
67
+ #: must be dropped with a named reason, not refused on every save forever. Every read
68
+ #: drops these definitions; `retire_preset_automations` also sweeps them from the store.
69
+ RETIRED_PRESETS = {
70
+ "customer_intelligence": (
71
+ "Customer intelligence has been removed from Loopable. This automation's trigger and "
72
+ "its insight action no longer exist, so it can no longer run and has been removed."),
73
+ }
74
+
75
+
76
+ def retired_preset_reason(definition):
77
+ """The sentence to show for a stored definition whose preset is gone, else ``""``."""
78
+ if not isinstance(definition, dict):
79
+ return ""
80
+ return RETIRED_PRESETS.get(str(definition.get("preset") or "").strip(), "")
81
+
82
+
 
 
 
 
 
 
 
 
 
 
 
 
83
  #: ⭐⭐ W47-T21 / R3 β€” THE THREE NAMED REASONS AN AGENT'S ROW FILTER REFUSES WITH.
84
  #:
85
  #: R3, verbatim: an agent's row filter is *"its whole world: it may neither read nor write a
 
2224
  return {**flow, "actions": kept}
2225
 
2226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2227
  def ig_action_pinned(defn, index):
2228
  """Is this action the one that cannot be removed? Derived, never stored β€” a stored `pinned`
2229
  flag is a second copy of the rule, and the copy is what a hand-written PATCH omits."""
 
2238
  raw = raw if isinstance(raw, dict) else {}
2239
  prev = previous or {}
2240
  preset = _s(raw.get("preset") if "preset" in raw else prev.get("preset"), 60).strip()
2241
+ if preset in RETIRED_PRESETS:
2242
+ return None, RETIRED_PRESETS[preset]
2243
+ if preset:
2244
  return None, f"unknown automation preset {preset!r}"
 
 
2245
  # ⭐ WAVE 24 Β· C-TRIG β€” THE TRIGGER IS RESOLVED FIRST NOW, because law 1 makes it the thing
2246
  # that CHOOSES the kind. Reading `raw["trigger"]["key"]` here instead would be a second
2247
  # reader of the trigger vocabulary, free to disagree with `clean_trigger` about which keys
2248
  # exist and which are refused. Gate-visible consequence, recorded in AMENDMENT A1: a payload
2249
  # invalid in BOTH its trigger and its config now answers with the trigger's sentence.
2250
  trigger_raw = raw.get("trigger") if "trigger" in raw else prev.get("trigger")
2251
+ trigger, terr = clean_trigger(trigger_raw, prev.get("trigger"))
 
 
2252
  if terr:
2253
  return None, terr
2254
  # C-TRIG law 2 (wave 24): a definition that names no kind is a `plain` one. Before R6 this
2255
  # refused with "unknown automation kind ''" β€” correct while a wizard always sent one, and a
2256
  # dead end the moment the wizard was deleted and the client's create body became {name}.
2257
  kind = _s(raw.get("kind") or prev.get("kind"), 40) or DEFAULT_KIND
 
 
2258
  drop_ig_seeds = False
2259
  if (trigger or {}).get("key") == "ig_profile_match":
2260
  # LAW 1: the trigger IS how `discover_instagram` gets chosen now. Unconditional rather
 
2422
  flow, ferr = clean_flow(flow_raw, prev.get("flow"), notes=notes, rt=rt)
2423
  if ferr:
2424
  return None, ferr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2425
  # ⭐ WAVE 30 β€” widened with the seeder above: TikTok now HAS a pinned step 1, so the rule that
2426
  # its `config.table` is authoritative has to reach it, or the two fields that name one database
2427
  # would disagree on exactly the network that just gained the card.
 
2511
  # ⚠ Same shape and same reason as the pre-set FIELD flag, which DESIGN.md Β§4 already
2512
  # describes as "sticky across a PATCH". One idea, one behaviour, two objects.
2513
  **({"system": _s(prev.get("system"), 40)} if prev.get("system") else {}),
 
2514
  }, None
2515
 
2516
 
 
2643
  return {"definitions": len(plan), **fields}
2644
 
2645
 
2646
+ def _no_preset_retirement():
2647
+ """The receipt when nothing was retired: the SAME keys the success path answers with.
2648
+
2649
+ A FUNCTION rather than a module constant, because the receipt is handed to a caller and a
2650
+ shared literal would let one caller's edit reach the next one.
2651
+ """
2652
+ return {"definitions": 0, "ids": [], "reasons": {}, "removed": []}
2653
+
2654
+
2655
+ def retire_preset_automations(rt):
2656
+ """Persist retired-definition removal and name each removed automation in the log.
2657
+
2658
+ ⭐⭐ THE RECEIPT CARRIES `removed` SO THE CALLER NEEDS NO SECOND READ. `list_automations` has
2659
+ to tell the reader WHICH automation went and why, and the obvious way to get the names β€” read
2660
+ the bucket again beside the sweep β€” is the defect the WAVE 30 Β· T12 comment block above that
2661
+ call site is the tombstone of: a whole-tenant document re-serialised under the store lock on
2662
+ every single request, to report something that is empty on all but one of them. This function
2663
+ has already read every row it removed, so it hands them back.
2664
+ """
2665
+ try:
2666
+ stored = dict(rt.get(STORE_KEY) or {})
2667
+ except Exception:
2668
+ return _no_preset_retirement()
2669
+ plan = {aid for aid, definition in stored.items() if retired_preset_reason(definition)}
2670
+ if not plan:
2671
+ return _no_preset_retirement()
2672
+ removed = {}
2673
+
2674
+ def _up(cur):
2675
+ cur = cur if isinstance(cur, dict) else {}
2676
+ # A store retry replays this callback. Report only the successful attempt, and
2677
+ # recheck each row so an intervening edit to a live definition is preserved.
2678
+ removed.clear()
2679
+ for aid in sorted(plan):
2680
+ definition = cur.get(aid)
2681
+ reason = retired_preset_reason(definition)
2682
+ if reason:
2683
+ removed[str(aid)] = (str(definition.get("name") or "Unnamed automation"), reason)
2684
+ cur.pop(aid)
2685
+ return cur
2686
+
2687
+ _store_update(rt, _up, flush="sync")
2688
+ for aid, (name, reason) in removed.items():
2689
+ print(f"[aios-auto] removed automation {aid!r} ({name!r}): {reason}")
2690
+ return {"definitions": len(removed), "ids": list(removed),
2691
+ "reasons": {aid: reason for aid, (_name, reason) in removed.items()},
2692
+ "removed": [{"id": aid, "name": name, "reason": reason}
2693
+ for aid, (name, reason) in removed.items()]}
2694
+
2695
+
2696
  #: ⭐⭐ WAVE 31 Β· T35 (D-134) β€” the definitions memo, and the two things that make it safe.
2697
  #: `tenant -> (monotonic_at, defs)`. Read ONLY through `all_definitions(..., cached=True)`, which
2698
  #: exactly one caller uses (`grid_hook`).
 
2770
  raw = dict(rt.get(STORE_KEY) or {})
2771
  except Exception:
2772
  return {}
2773
+ out = {str(aid): _without_retired_board(defn)[0] for aid, defn in raw.items()
2774
+ if not retired_preset_reason(defn)}
2775
  if cached:
2776
  _DEFS_MEMO[str(getattr(rt, "key", "") or "")] = (time.monotonic(), out)
2777
  return out
 
2889
 
2890
  def authorize_agent_principal(rt, agent_id, actor, is_admin=False):
2891
  rec = _agent_contracts(rt).get(str(agent_id or ""))
2892
+ # An admin may read a live private Agent; that role cannot resurrect a deleted Agent
2893
+ # or replace the user identity required for authorization.
2894
  if not str(actor or "").strip() or not isinstance(rec, dict) or not rec:
2895
  raise PermissionError("this Agent or its principal is no longer available")
2896
  sharing = rec.get("sharing") or {}
 
3206
  return {"query": copy.deepcopy(result), "noProviderCalls": True, "providerCalls": 0}
3207
 
3208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3209
  def set_semantic_readiness(rt, agent_id, fields):
3210
  rows = fields if isinstance(fields, list) else []
3211
  clean = [{"database": str(row.get("database") or ""), "field": str(row.get("field") or ""),
 
8988
  # `apply_actions` arm.
8989
  if is_statement_flow(defn):
8990
  return run_statements(rt, defn, username=username, log=log, step=step)
 
 
 
 
 
 
 
8991
  table = _flow_table(defn)
8992
  if not table:
8993
  return ("partial",
 
9857
  #: that read off this route; putting it back to draw a label would undo the wave before this one).
9858
  ACTION_REQUIRED = dict(WEB_REQUIRED)
9859
  ACTION_REQUIRED["voice_agent"] = (("a Voice agent", "voiceAgentId"),)
 
9860
  #: ⭐ W31-T38 (C5) β€” the web step's own clamps. `20000` matches the default E's seam documents;
9861
  #: the ceiling exists because this blocks the record walk (~9-32 s of cold start ALREADY), and an
9862
  #: automation that can be configured to wait ten minutes per record is a stalled run, not a slow one.
 
9924
  # hidden row's label is still rendered on a STORED step's card, so leaving the six captions in
9925
  # place would have kept them on screen for exactly the people who already use them. They now
9926
  # name the mechanism instead, and no old caption survives as a substring in any case.
 
 
 
 
 
9927
  {"kind": "ai_agent", "label": "Web agent", "group": "Agent", "ready": True,
9928
  "detail": "Describe a job on a website in words; the agent works out the steps, runs them in "
9929
  "a browser and reports what it actually did"},
 
10037
  "ready": True, "menu": False,
10038
  "detail": "Fill an AI column for the records this flow walks. Configured on the column, not "
10039
  "here"},
 
 
 
10040
  # ── 4. ADVANCED LOGIC ────────────────────────────────────────────────────────────────────
10041
  # `group` is relabelled "If / then" (C-ACT): "Conditional logic" described the mechanism,
10042
  # and R8 made it a FORK with lettered branches, which is a thing people already have a name
 
10635
  if voice_id and not re.fullmatch(r"va_[A-Za-z0-9_\-]{4,110}", voice_id):
10636
  return None, "select a Voice agent from Loopable rather than entering a provider id"
10637
  return {"voiceAgentId": voice_id}, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10638
  if kind == "ai_agent":
10639
  # ⭐⭐ W33-T56 β€” THE FUZZY STEP'S CONFIG. Same posture as the web arm below in every
10640
  # respect that matters: an ALLOWLIST, a shape test on the url, a clamped timeout, and an
 
11356
  # cannot report a refusal.
11357
  counts = {"actionsRun": 0, "updated": 0, "created": 0, "found": 0,
11358
  "webRead": 0, "webBlocked": 0}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11359
  #: W31-T38 β€” the once-per-run markers the web arm uses, so an unconfigured step says so ONCE
11360
  #: rather than once per record. Same shape as the enrich accumulators' `notes`.
11361
  web_notes = []
 
15950
  stored = all_definitions(rt).get(aid)
15951
  if not isinstance(stored, dict):
15952
  return {"sent": False, "reason": "unknown_automation"}
 
 
 
 
 
 
 
 
 
 
 
 
 
15953
  trigger = stored.get("trigger") if isinstance(stored.get("trigger"), dict) else {}
15954
  schedule = stored.get("schedule") if isinstance(stored.get("schedule"), dict) else {}
15955
  trigger_key = str(trigger.get("key") or "").strip()
 
15966
  context = routes_slack.automation_answer_context(rt, aid)
15967
  if context is None:
15968
  return {"sent": False, "reason": "not_authorized"}
15969
+ text = _automation_slack_reply_text(result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15970
  return routes_slack.deliver_channel_reply(
15971
  rt, context["channel"], text, principal=context["principal"], automation_id=aid,
15972
  provenance={"basis": "model_guidance", "citationIds": [], "modelGuidance": False},
 
16065
  # NOTHING β€” the branch where every candidate was a known-dead handle, i.e. exactly the
16066
  # run a person stares at wondering why the automation stopped doing anything.
16067
  run_notes = list((counts or {}).pop(RUN_NOTES_KEY, None) or [])
 
16068
  try:
16069
  a_counts = apply_actions(rt, defn, _flow_table(defn), affected or [],
16070
  username=username, log=log,
16071
  step=lambda text: _step(tenant, auto_id, text))
 
16072
  # ⭐⭐ D-103 β€” POPPED BEFORE THE MERGE. The per-record reasons ride inside `counts` so
16073
  # the runner contract keeps its shape, and they must leave before the merge or they
16074
  # would be a "count" everywhere downstream.
16075
  run_notes += list(a_counts.pop(RUN_NOTES_KEY, None) or [])
16076
  counts = {**(counts or {}), **{k: v for k, v in a_counts.items() if v}}
 
 
 
16077
  if a_counts.get("enrichMetricBatchesPending"):
16078
  batches = int(a_counts["enrichMetricBatchesPending"])
16079
  state = "partial" if state != "error" else state
 
16143
  try:
16144
  dispatch_authorized_slack_automation(
16145
  rt, defn, {"state": state, "summary": summary,
16146
+ "rowIds": affected or []})
16147
  except Exception as e: # noqa: BLE001
16148
  log(f"[aios-auto] Slack notification for {auto_id} failed: {type(e).__name__}: {e}")
 
 
16149
  return _commit_run(rt, auto_id, state, summary, counts, state != "error", affected,
16150
  steps, notes=run_notes)
16151
  finally:
api/deps.py CHANGED
The diff for this file is too large to render. See raw diff
 
api/main.py CHANGED
@@ -82,10 +82,7 @@ import routes_feedback # noqa: E402 (wave 35 R8/C6 β€” feedback to the operato
82
  import routes_agent_harness # noqa: E402 (wave 36 R8/C4 β€” the agent harness store; E's router)
83
  import routes_geo # noqa: E402 (wave 37 R14/A11 β€” the keyless map provider seam; D's router)
84
  from core import grid_events # noqa: E402
85
- from core import sheet_events # noqa: E402
86
 
87
- # Inject the upper-layer consumer into the shared persistence door without a core -> API import.
88
- sheet_events.COMMIT_OBSERVER = routes_automation.engine.workbook_insight_committed
89
  # D-315 / D-305 (2026-08-18) β€” the two store REFUSALS get their own app-level handlers below.
90
  # ⚠ Neither is a `StoreUnavailable` subclass, on purpose: routes that degrade a store outage into a
91
  # session fallback must NOT degrade a refusal, or the user is told a change was saved that was not.
@@ -1218,8 +1215,12 @@ def _rebuild_odoo_relational(why, previous_meta_fingerprint=None, meta_state_out
1218
  # β€” and under `STORE_BACKEND=pg` the store is key -> whole-JSONB-document, so each of
1219
  # those is the ENTIRE tenant workspace (~28 MB for tenant #0) coming back through Neon's
1220
  # public proxy. Eight tables meant EIGHT full reads per rebuild before a single cell was
1221
- # computed, and sixteen when they all changed, because the `persist` write re-read the
1222
- # document a second time.
 
 
 
 
1223
  #
1224
  # β›” AND EGRESS IS THE HALF THAT IS BILLED. Neon's public network transfer is defined as
1225
  # *"data sent from your databases through the Neon proxy to clients"* β€” outbound only.
 
82
  import routes_agent_harness # noqa: E402 (wave 36 R8/C4 β€” the agent harness store; E's router)
83
  import routes_geo # noqa: E402 (wave 37 R14/A11 β€” the keyless map provider seam; D's router)
84
  from core import grid_events # noqa: E402
 
85
 
 
 
86
  # D-315 / D-305 (2026-08-18) β€” the two store REFUSALS get their own app-level handlers below.
87
  # ⚠ Neither is a `StoreUnavailable` subclass, on purpose: routes that degrade a store outage into a
88
  # session fallback must NOT degrade a refusal, or the user is told a change was saved that was not.
 
1215
  # β€” and under `STORE_BACKEND=pg` the store is key -> whole-JSONB-document, so each of
1216
  # those is the ENTIRE tenant workspace (~28 MB for tenant #0) coming back through Neon's
1217
  # public proxy. Eight tables meant EIGHT full reads per rebuild before a single cell was
1218
+ # computed, and up to sixteen in the worst case, because each table that HAS source
1219
+ # rollups and finds a changed cell re-reads the document in its `persist` write.
1220
+ # ⚠ EIGHT IS THE MEASURED FLOOR AND SIXTEEN IS A CEILING, NOT AN OBSERVATION: `compute()`
1221
+ # takes its read BEFORE it checks `source_fields(tdef)`, so every table pays the read even
1222
+ # when it returns immediately β€” but only a table WITH source rollups can reach the write.
1223
+ # Two of the eight (`order_lines`, `gl_lines`) are read-through grains with no stored rows.
1224
  #
1225
  # β›” AND EGRESS IS THE HALF THAT IS BILLED. Neon's public network transfer is defined as
1226
  # *"data sent from your databases through the Neon proxy to clients"* β€” outbound only.
api/routes_applications.py CHANGED
@@ -8,7 +8,8 @@ from modules import finance_spine
8
  from pages import resolve_bu
9
 
10
 
11
- router = APIRouter(prefix="/api/v1/finance", tags=["finance"])
 
12
 
13
 
14
  def _may_open(session, permission_key):
@@ -39,7 +40,7 @@ def _require_fact(session, key):
39
  return finance_spine.fact_spec(key)
40
 
41
 
42
- @router.get("/applications")
43
  def list_finance_applications(session: Session = Depends(require_session)):
44
  """One Finance group containing only the applications this session may open."""
45
  apps = application_registry.finance_applications(
@@ -50,7 +51,7 @@ def list_finance_applications(session: Session = Depends(require_session)):
50
  return {"group": application_registry.finance_group(), "applications": apps}
51
 
52
 
53
- @router.get("/applications/{app_key}")
54
  def get_finance_application(app_key: str, bu: str | None = None,
55
  date_from: str | None = None, date_to: str | None = None,
56
  session: Session = Depends(require_session)):
@@ -76,7 +77,7 @@ def get_finance_application(app_key: str, bu: str | None = None,
76
  "businessUnit": team_id, "state": state, "facts": facts, "kpis": kpis}
77
 
78
 
79
- @router.get("/facts/{fact_key}/records")
80
  def get_finance_fact_records(fact_key: str, bu: str | None = None,
81
  date_from: str | None = None, date_to: str | None = None,
82
  limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0),
@@ -101,7 +102,7 @@ def get_finance_fact_records(fact_key: str, bu: str | None = None,
101
  "total_count": None, "aggregates": {}}
102
 
103
 
104
- @router.get("/facts/{fact_key}/reconciliation")
105
  def reconcile_finance_fact(fact_key: str, bu: str | None = None,
106
  date_from: str | None = None, date_to: str | None = None,
107
  session: Session = Depends(require_session)):
@@ -121,3 +122,24 @@ def reconcile_finance_fact(fact_key: str, bu: str | None = None,
121
  return {"state": "warming", "message": "The tenant mirror is still warming."}
122
  return finance_spine.reconcile(
123
  fact_key, date_from=date_from, date_to=date_to, team_id=team_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from pages import resolve_bu
9
 
10
 
11
+ finance_router = APIRouter(prefix="/api/v1/finance", tags=["finance"])
12
+ nav_router = APIRouter(prefix="/api/v1", tags=["applications"])
13
 
14
 
15
  def _may_open(session, permission_key):
 
40
  return finance_spine.fact_spec(key)
41
 
42
 
43
+ @finance_router.get("/applications")
44
  def list_finance_applications(session: Session = Depends(require_session)):
45
  """One Finance group containing only the applications this session may open."""
46
  apps = application_registry.finance_applications(
 
51
  return {"group": application_registry.finance_group(), "applications": apps}
52
 
53
 
54
+ @finance_router.get("/applications/{app_key}")
55
  def get_finance_application(app_key: str, bu: str | None = None,
56
  date_from: str | None = None, date_to: str | None = None,
57
  session: Session = Depends(require_session)):
 
77
  "businessUnit": team_id, "state": state, "facts": facts, "kpis": kpis}
78
 
79
 
80
+ @finance_router.get("/facts/{fact_key}/records")
81
  def get_finance_fact_records(fact_key: str, bu: str | None = None,
82
  date_from: str | None = None, date_to: str | None = None,
83
  limit: int = Query(100, ge=1, le=500), offset: int = Query(0, ge=0),
 
102
  "total_count": None, "aggregates": {}}
103
 
104
 
105
+ @finance_router.get("/facts/{fact_key}/reconciliation")
106
  def reconcile_finance_fact(fact_key: str, bu: str | None = None,
107
  date_from: str | None = None, date_to: str | None = None,
108
  session: Session = Depends(require_session)):
 
122
  return {"state": "warming", "message": "The tenant mirror is still warming."}
123
  return finance_spine.reconcile(
124
  fact_key, date_from=date_from, date_to=date_to, team_id=team_id)
125
+
126
+
127
+ @nav_router.get("/nav/applications")
128
+ def list_nav_applications(session: Session = Depends(require_session)):
129
+ """Every Application this session may open, in ONE generic navigation shape (R6).
130
+
131
+ Finance's six arrive here as seeded Application records rather than as new template kinds,
132
+ so the App module reaches them by the same path Routing and Catalog ride.
133
+ """
134
+ if not session.runtime.available():
135
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
136
+ return {"applications": application_registry.nav_applications(
137
+ session.runtime, session.uname, session.admin,
138
+ may_open=lambda permission: _may_open(session, permission))}
139
+
140
+
141
+ # main.py includes exactly one object named router. These two sub-routers keep
142
+ # /nav/applications outside the Finance prefix while every Finance URL stays unchanged.
143
+ router = APIRouter()
144
+ router.include_router(finance_router)
145
+ router.include_router(nav_router)
api/routes_automation.py CHANGED
@@ -1190,23 +1190,6 @@ def warm_default(rt):
1190
  return value
1191
 
1192
 
1193
- def _customer_intelligence_options(session):
1194
- agents = []
1195
- for agent_id, contract in engine._agent_contracts(session.runtime).items():
1196
- if not isinstance(contract, dict):
1197
- continue
1198
- try:
1199
- engine.authorize_agent_principal(
1200
- session.runtime, agent_id, session.uname, is_admin=session.admin)
1201
- except PermissionError:
1202
- continue
1203
- agents.append({
1204
- "id": agent_id, "label": contract.get("displayName") or "Unnamed Agent",
1205
- "ready": engine.setup_interview(contract).get("state") == "configured",
1206
- })
1207
- return {"agents": agents}
1208
-
1209
-
1210
  @router.get("/automations")
1211
  def list_automations(session: Session = Depends(_GATE)):
1212
  """`{automations: [...], kinds: [...], cronPresets: [...]}` β€” the rail's whole payload.
@@ -1228,8 +1211,9 @@ def list_automations(session: Session = Depends(_GATE)):
1228
  #
1229
  # β›” WHY SKIPPING THE SCAN ON CALLS 2..N IS SAFE, and it is not "because it is idempotent":
1230
  # `all_definitions` STRIPS retired board state on every read (`automation_engine.py`'s
1231
- # `_without_retired_board`), so the persist step is hygiene, not correctness. No client can
1232
- # ever be shown state this skip left behind. Nothing writes new `stage_auto_` cells either β€”
 
1233
  # wave 26's R6 deleted the board that made them.
1234
  # ⭐⭐ WAVE 30 Β· T12 (owner items 4/5, the complaint that has now survived TWO waves).
1235
  # β›” W29-T01 GUARDED THE SCAN AND NOT THE READ, and that is the whole of what was left. The
@@ -1239,6 +1223,13 @@ def list_automations(session: Session = Depends(_GATE)):
1239
  # behind each other) β€” while on calls 2..N the result was DISCARDED: `tables` had exactly two
1240
  # consumers, the `_BOARD_RETIRED` scan (skipped after call 1) and a picker DEFAULT STRING.
1241
  # A whole-tenant document, per request, to render a rail showing a name and a toggle.
 
 
 
 
 
 
 
1242
  tables = None
1243
  if session.runtime.available() and session.tenant not in _BOARD_RETIRED:
1244
  tables = engine.ut_all(session.runtime)
@@ -1246,6 +1237,7 @@ def list_automations(session: Session = Depends(_GATE)):
1246
  # Idempotent Board retirement removes only engine-marked stage fields and legacy Board
1247
  # state. User-created Status/Stage columns remain intact.
1248
  engine.retire_automation_board_state(session.runtime, tables=tables)
 
1249
  # ⭐⭐ WAVE 35 Β· T37 / OWNER RULING R10 β€” ROYAL IMPORTS' STATEMENTS AGENT EXISTS BEFORE ANYBODY
1250
  # ASKS FOR IT. It is minted ONCE, by the container, SWITCHED OFF; every subsequent call finds
1251
  # it present and returns immediately. See `engine.seed_statements_agent` for why this one is
@@ -1272,8 +1264,7 @@ def list_automations(session: Session = Depends(_GATE)):
1272
  items = sorted(items + _field_agent_rows(session) + _sys_rows,
1273
  key=lambda r: str(r.get("name") or "").lower())
1274
  return {"automations": items,
1275
- "customerIntelligence": _customer_intelligence_options(session),
1276
- "customerIntelligencePreset": engine.customer_intelligence_contract(),
1277
  # ⭐ WAVE 24 β€” DERIVED from the engine's public `PICKER_KINDS`, not a hand-written trio. It was
1278
  # three literals that happened to match, which is a second copy of a server
1279
  # vocabulary; R6 has just made two of them uncreatable and `plain` has joined, so a
@@ -2084,49 +2075,6 @@ def ai_transport(session: Session = Depends(_GATE)):
2084
  "lastTransport": ai_review.LAST_ANTHROPIC_TRANSPORT or None}
2085
 
2086
 
2087
- @router.get("/automations/customer-intelligence/contract")
2088
- def customer_intelligence_contract(session: Session = Depends(_GATE)):
2089
- """The one server-owned payload both native settings surfaces render."""
2090
- return engine.customer_intelligence_contract()
2091
-
2092
-
2093
- @router.post("/automations/customer-intelligence/events")
2094
- def customer_intelligence_event(body: dict = Body(default=None),
2095
- session: Session = Depends(_GATE)):
2096
- """One committed Sheet value/binding batch; formatting/paint events are inert."""
2097
- body = body if isinstance(body, dict) else {}
2098
- if body.get("kind") not in (None, "sheet_insight_changed"):
2099
- raise err(400, "customer_intelligence_event",
2100
- "the native Sheet event kind is fixed to sheet_insight_changed")
2101
- from core import sheets
2102
- import routes_sheet
2103
- try:
2104
- book = sheets.get_workbook(routes_sheet._store(session), body.get("workbookId"))
2105
- routes_sheet._require_editor(session, book)
2106
- sheets.find_tab(book, body.get("sheetId"))
2107
- except sheets.SheetRefusal as exc:
2108
- raise routes_sheet._refuse(exc)
2109
- return engine.sheet_insight_committed(session.runtime, body)
2110
-
2111
-
2112
- @router.post("/automations/{auto_id}/customer-intelligence/dry-run")
2113
- def customer_intelligence_dry_run(auto_id: str, session: Session = Depends(_GATE)):
2114
- """Resolve live authority and generate a preview without entering the Slack send door."""
2115
- definition = engine.all_definitions(session.runtime).get(str(auto_id))
2116
- if not isinstance(definition, dict) \
2117
- or definition.get("preset") != engine.CUSTOMER_INTELLIGENCE_PRESET:
2118
- raise err(404, "unknown_automation", "no customer-intelligence setting has that id")
2119
- try:
2120
- return engine.customer_intelligence_preview(
2121
- session.runtime, definition,
2122
- permission_check=lambda row: engine.customer_intelligence_authorized(
2123
- session.runtime, row, actor=session.uname, is_admin=session.admin))
2124
- except PermissionError as exc:
2125
- raise err(403, "customer_intelligence_permission", str(exc))
2126
- except ValueError as exc:
2127
- raise err(400, "customer_intelligence_preview", str(exc))
2128
-
2129
-
2130
  @router.get("/automations/{auto_id}")
2131
  def get_automation(auto_id: str, session: Session = Depends(_GATE)):
2132
  """One automation, by id.
@@ -2162,64 +2110,6 @@ def get_automation(auto_id: str, session: Session = Depends(_GATE)):
2162
  return {"automation": _wire(defn, session.tenant, rt=session.runtime)}
2163
 
2164
 
2165
- def _customer_intelligence_body(session, body, previous=None):
2166
- """Bind C2's exact trigger to its native source and validate selected local principals."""
2167
- raw = dict(body or {})
2168
- prev = previous if isinstance(previous, dict) else {}
2169
- preset = str(raw.get("preset") if "preset" in raw else prev.get("preset") or "")
2170
- if preset != engine.CUSTOMER_INTELLIGENCE_PRESET:
2171
- return raw
2172
- trigger = raw.get("trigger") if isinstance(raw.get("trigger"), dict) else prev.get("trigger")
2173
- trigger = dict(trigger or {})
2174
- key = str(trigger.get("kind") or trigger.get("key") or "")
2175
- config = dict(prev.get("config") or {})
2176
- if isinstance(raw.get("config"), dict):
2177
- config.update(raw.get("config") or {})
2178
- if key == "enters_view" and not str(config.get("targetTable") or ""):
2179
- view_id = str(trigger.get("viewId") or "")
2180
- matches = []
2181
- for table in _automation_table_rows(session):
2182
- if any(str(view.get("id") or "") == view_id for view in (table.get("views") or [])):
2183
- matches.append(str(table.get("key") or ""))
2184
- if len(matches) != 1:
2185
- raise err(400, "customer_intelligence_source",
2186
- "the fixed View trigger must resolve to one readable saved View")
2187
- config["targetTable"] = matches[0]
2188
- raw["config"] = config
2189
- elif key == "sheet_insight_changed":
2190
- # Reuse Sheet's own owner/editor resolver. A native setting is itself workbook state and
2191
- # cannot be configured by a viewer merely because they can call Automation routes.
2192
- from core import sheets
2193
- import routes_sheet
2194
- try:
2195
- book = sheets.get_workbook(routes_sheet._store(session), trigger.get("workbookId"))
2196
- routes_sheet._require_editor(session, book)
2197
- sheets.find_tab(book, trigger.get("sheetId"))
2198
- except sheets.SheetRefusal as exc:
2199
- raise routes_sheet._refuse(exc)
2200
-
2201
- actions = list(((raw.get("flow") if isinstance(raw.get("flow"), dict)
2202
- else prev.get("flow") or {}).get("actions") or []))
2203
- insight = actions[0] if actions and isinstance(actions[0], dict) else {}
2204
- agent_id = str((insight.get("config") or {}).get("agentId") or "").strip()
2205
- if agent_id:
2206
- _stored_agent_or_404(session, agent_id)
2207
- try:
2208
- engine.authorize_agent_principal(
2209
- session.runtime, agent_id, session.uname, is_admin=session.admin)
2210
- except PermissionError as exc:
2211
- raise err(403, "agent_principal_refused", str(exc))
2212
- slack = actions[1] if len(actions) > 1 and isinstance(actions[1], dict) else {}
2213
- destination = str((slack.get("config") or {}).get("destinationId") or "").strip()
2214
- if destination:
2215
- import routes_slack
2216
- agent = (routes_slack._agents(session.runtime) or {}).get(destination)
2217
- if not isinstance(agent, dict) or agent.get("active", True) is False:
2218
- raise err(400, "customer_intelligence_destination",
2219
- "choose an active governed Slack destination")
2220
- return raw
2221
-
2222
-
2223
  @router.post("/automations")
2224
  def create_automation(body: dict = Body(default=None), session: Session = Depends(_GATE)):
2225
  """Create an automation. ⭐ WAVE 23 (C2): the body may carry
@@ -2234,7 +2124,6 @@ def create_automation(body: dict = Body(default=None), session: Session = Depend
2234
  # anybody being TOLD, so a person saved a flow and got a different one with nothing said.
2235
  # ⚠ It rides the SAVE's own response, beside `unconfigured`, because that is the moment the
2236
  # person is looking β€” a note in a log they never open is the same silence with extra steps.
2237
- body = _customer_intelligence_body(session, body or {})
2238
  _notes = []
2239
  defn, error = engine.create(session.runtime, body, username=session.uname,
2240
  notes=_notes)
@@ -2282,7 +2171,6 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
2282
  # step and permits an ordinary save of a flow that merely contains one.
2283
  _agent_owned_guard(session, auto_id, body or {})
2284
  previous = engine.all_definitions(session.runtime).get(str(auto_id))
2285
- body = _customer_intelligence_body(session, body or {}, previous=previous)
2286
  _notes = []
2287
  defn, error = engine.patch(session.runtime, auto_id, body, username=session.uname,
2288
  notes=_notes)
 
1190
  return value
1191
 
1192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1193
  @router.get("/automations")
1194
  def list_automations(session: Session = Depends(_GATE)):
1195
  """`{automations: [...], kinds: [...], cronPresets: [...]}` β€” the rail's whole payload.
 
1211
  #
1212
  # β›” WHY SKIPPING THE SCAN ON CALLS 2..N IS SAFE, and it is not "because it is idempotent":
1213
  # `all_definitions` STRIPS retired board state on every read (`automation_engine.py`'s
1214
+ # `_without_retired_board`) and drops retired presets, so persistence is hygiene, not
1215
+ # correctness. No client can see state this skip left behind. Nothing writes new
1216
+ # `stage_auto_` cells either β€”
1217
  # wave 26's R6 deleted the board that made them.
1218
  # ⭐⭐ WAVE 30 Β· T12 (owner items 4/5, the complaint that has now survived TWO waves).
1219
  # β›” W29-T01 GUARDED THE SCAN AND NOT THE READ, and that is the whole of what was left. The
 
1223
  # behind each other) β€” while on calls 2..N the result was DISCARDED: `tables` had exactly two
1224
  # consumers, the `_BOARD_RETIRED` scan (skipped after call 1) and a picker DEFAULT STRING.
1225
  # A whole-tenant document, per request, to render a rail showing a name and a toggle.
1226
+ # β›”β›” AND THE REMOVAL NOTICE OBEYS THE SAME RULE, which is why it is built HERE and not above.
1227
+ # The first draft of this read the whole `automations` document on EVERY request to name the
1228
+ # retired rows, and then a SECOND time to fetch their names β€” the defect this very comment
1229
+ # block is the tombstone of, re-introduced two lines under it. The sweep has already read
1230
+ # every row it removed, so its receipt carries them: calls 2..N report nothing and read
1231
+ # nothing, which is correct as well as cheap, because after the sweep no retired row exists.
1232
+ retired = []
1233
  tables = None
1234
  if session.runtime.available() and session.tenant not in _BOARD_RETIRED:
1235
  tables = engine.ut_all(session.runtime)
 
1237
  # Idempotent Board retirement removes only engine-marked stage fields and legacy Board
1238
  # state. User-created Status/Stage columns remain intact.
1239
  engine.retire_automation_board_state(session.runtime, tables=tables)
1240
+ retired = engine.retire_preset_automations(session.runtime)["removed"]
1241
  # ⭐⭐ WAVE 35 Β· T37 / OWNER RULING R10 β€” ROYAL IMPORTS' STATEMENTS AGENT EXISTS BEFORE ANYBODY
1242
  # ASKS FOR IT. It is minted ONCE, by the container, SWITCHED OFF; every subsequent call finds
1243
  # it present and returns immediately. See `engine.seed_statements_agent` for why this one is
 
1264
  items = sorted(items + _field_agent_rows(session) + _sys_rows,
1265
  key=lambda r: str(r.get("name") or "").lower())
1266
  return {"automations": items,
1267
+ "retired": retired,
 
1268
  # ⭐ WAVE 24 β€” DERIVED from the engine's public `PICKER_KINDS`, not a hand-written trio. It was
1269
  # three literals that happened to match, which is a second copy of a server
1270
  # vocabulary; R6 has just made two of them uncreatable and `plain` has joined, so a
 
2075
  "lastTransport": ai_review.LAST_ANTHROPIC_TRANSPORT or None}
2076
 
2077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2078
  @router.get("/automations/{auto_id}")
2079
  def get_automation(auto_id: str, session: Session = Depends(_GATE)):
2080
  """One automation, by id.
 
2110
  return {"automation": _wire(defn, session.tenant, rt=session.runtime)}
2111
 
2112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2113
  @router.post("/automations")
2114
  def create_automation(body: dict = Body(default=None), session: Session = Depends(_GATE)):
2115
  """Create an automation. ⭐ WAVE 23 (C2): the body may carry
 
2124
  # anybody being TOLD, so a person saved a flow and got a different one with nothing said.
2125
  # ⚠ It rides the SAVE's own response, beside `unconfigured`, because that is the moment the
2126
  # person is looking β€” a note in a log they never open is the same silence with extra steps.
 
2127
  _notes = []
2128
  defn, error = engine.create(session.runtime, body, username=session.uname,
2129
  notes=_notes)
 
2171
  # step and permits an ordinary save of a flow that merely contains one.
2172
  _agent_owned_guard(session, auto_id, body or {})
2173
  previous = engine.all_definitions(session.runtime).get(str(auto_id))
 
2174
  _notes = []
2175
  defn, error = engine.patch(session.runtime, auto_id, body, username=session.uname,
2176
  notes=_notes)
api/routes_connectors.py CHANGED
The diff for this file is too large to render. See raw diff
 
api/routes_customers.py CHANGED
@@ -22,8 +22,10 @@ owner-blocked on B-3), and no test here may claim read-your-writes ACROSS runtim
22
  proof is single-process and would report green on exactly the thing that is still broken.
23
  """
24
  import datetime as _dt
 
25
  import hashlib
26
  import json
 
27
  import time
28
 
29
  from fastapi import APIRouter, Body, Depends
@@ -39,6 +41,14 @@ MODULE = "customer_data"
39
 
40
  _CACHE_TTL = 900 # the pool build is slow (Odoo + reconciliation); 15 min, as before
41
 
 
 
 
 
 
 
 
 
42
 
43
  def _pool_rows(session: Session):
44
  """The reconciled Odoo pool for this session's SCOPE β€” the slow part, and the only part that
@@ -304,6 +314,65 @@ def _mark_offerability(fields):
304
 
305
  def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
306
  consume_corrections: bool = True):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  """ONE assembly of this session's grid state, shared by `/customers`, `/workspace` and the
308
  events route (2026-07-31 β€” the standalone measure gap, owner item 1).
309
 
@@ -330,6 +399,10 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
330
 
331
  import core.perm_scope as perm_scope
332
 
 
 
 
 
333
  rt = session.runtime
334
  team_id, agent = _team_agent(session)
335
  rows_src = _pool_for(rt, team_id, agent)
 
22
  proof is single-process and would report green on exactly the thing that is still broken.
23
  """
24
  import datetime as _dt
25
+ from copy import deepcopy
26
  import hashlib
27
  import json
28
+ import threading
29
  import time
30
 
31
  from fastapi import APIRouter, Body, Depends
 
41
 
42
  _CACHE_TTL = 900 # the pool build is slow (Odoo + reconciliation); 15 min, as before
43
 
44
+ # A slow producer must not indefinitely hold another threadpool request; timeout recomputes.
45
+ _GRID_ASSEMBLY_WAIT_SECONDS = 10.0
46
+ _grid_assembly_lock = threading.Lock()
47
+ _grid_assembly_inflight = {}
48
+ _grid_assembly_enabled = True
49
+ grid_assembly_computed = 0
50
+ grid_assembly_shared = 0
51
+
52
 
53
  def _pool_rows(session: Session):
54
  """The reconciled Odoo pool for this session's SCOPE β€” the slow part, and the only part that
 
314
 
315
  def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
316
  consume_corrections: bool = True):
317
+ """Share only overlapping assemblies of the same user's grid, never completed results."""
318
+ global grid_assembly_shared
319
+ rt = session.runtime
320
+ team_id, agent = _team_agent(session)
321
+ key = (session.tenant, session.uname, session.admin, team_id, agent, scope,
322
+ consume_corrections, _pool_stamp(rt, team_id, agent),
323
+ # A changed permission record must not borrow an assembly from the old record.
324
+ # β›” `default=str` IS NOT TIDINESS. This runs on every `/customers` and `/workspace`,
325
+ # the product's main grid; a `TypeError` from an unserialisable value in a stored user
326
+ # record would 500 BOTH doors, which is a far worse failure than the duplicated work
327
+ # this key exists to remove. The record round-trips JSON by construction today, so the
328
+ # fallback should never fire -- and a key that cannot raise is the only kind worth
329
+ # putting in front of a hot path.
330
+ json.dumps(session.user, sort_keys=True, separators=(",", ":"), default=str))
331
+
332
+ def own_copy(result):
333
+ # The pool is already shared by scope_cache and rows_from_pool never mutates it.
334
+ # Copy the rest together to preserve internal aliases without lending mutable state.
335
+ out = deepcopy({k: v for k, v in result.items() if k != "rows_src"})
336
+ out["rows_src"] = result["rows_src"]
337
+ out["workspace"]["storageKey"] = storage_key
338
+ return out
339
+
340
+ if not _grid_assembly_enabled:
341
+ return own_copy(_compute_grid_assembly(session, scope, storage_key, consume_corrections))
342
+
343
+ with _grid_assembly_lock:
344
+ entry = _grid_assembly_inflight.get(key)
345
+ producer = entry is None
346
+ if producer:
347
+ entry = {"event": threading.Event(), "result": None, "error": None}
348
+ _grid_assembly_inflight[key] = entry
349
+
350
+ if not producer:
351
+ if entry["event"].wait(_GRID_ASSEMBLY_WAIT_SECONDS):
352
+ if entry["error"] is not None:
353
+ raise entry["error"]
354
+ result = own_copy(entry["result"])
355
+ with _grid_assembly_lock:
356
+ grid_assembly_shared += 1
357
+ return result
358
+ # A timeout changes neither the caller's answer nor the producer's ownership.
359
+ return own_copy(_compute_grid_assembly(session, scope, storage_key, consume_corrections))
360
+
361
+ try:
362
+ entry["result"] = _compute_grid_assembly(session, scope, storage_key, consume_corrections)
363
+ except BaseException as exc:
364
+ entry["error"] = exc
365
+ raise
366
+ finally:
367
+ with _grid_assembly_lock:
368
+ if _grid_assembly_inflight.get(key) is entry:
369
+ del _grid_assembly_inflight[key]
370
+ entry["event"].set()
371
+ return own_copy(entry["result"])
372
+
373
+
374
+ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
375
+ consume_corrections: bool = True):
376
  """ONE assembly of this session's grid state, shared by `/customers`, `/workspace` and the
377
  events route (2026-07-31 β€” the standalone measure gap, owner item 1).
378
 
 
399
 
400
  import core.perm_scope as perm_scope
401
 
402
+ global grid_assembly_computed
403
+ with _grid_assembly_lock:
404
+ grid_assembly_computed += 1
405
+
406
  rt = session.runtime
407
  team_id, agent = _team_agent(session)
408
  rows_src = _pool_for(rt, team_id, agent)
api/routes_odoo_tables.py CHANGED
The diff for this file is too large to render. See raw diff
 
api/routes_sheet.py CHANGED
@@ -2582,13 +2582,15 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
2582
  return {"value": value, "limits": limits, "database": database, "binding": binding}
2583
 
2584
 
2585
- def execute_daily_sales_repair(session: Session, request, *, backup_store):
2586
  """Run the explicit T21 repair through the normal scoped binding and formula engines.
2587
 
2588
  This is intentionally not an HTTP route. A normal workbook request must never acquire an
2589
  exceptional tenant-data mutation surface. The approved operator calls this helper with the
2590
- exact marker/revision/source oracle and a backup store; the core workflow then performs its own
2591
- target, marker, snapshot, backup and readback checks.
 
 
2592
  """
2593
  from core import daily_sales_repair, sheets
2594
  import formula_runtime
@@ -2598,7 +2600,8 @@ def execute_daily_sales_repair(session: Session, request, *, backup_store):
2598
  raise daily_sales_repair.RepairRefusal(
2599
  "repair_tenant_mismatch",
2600
  "This operation may run only in the Royal Imports workspace.")
2601
- book = sheets.get_workbook(_store(session), daily_sales_repair.TARGET_WORKBOOK_ID)
 
2602
  _require_editor(session, book)
2603
 
2604
  view_memo = {}
@@ -2616,6 +2619,7 @@ def execute_daily_sales_repair(session: Session, request, *, backup_store):
2616
 
2617
  return daily_sales_repair.execute(
2618
  _store(session), backup_store, request,
 
2619
  resolve_binding=resolve, formula_check=formula_check,
2620
  actor=session.uname, actor_name=session.user.get("name") or session.uname)
2621
  except sheets.SheetRefusal as exc:
 
2582
  return {"value": value, "limits": limits, "database": database, "binding": binding}
2583
 
2584
 
2585
+ def execute_daily_sales_repair(session: Session, request, *, backup_store, workbook_id=None):
2586
  """Run the explicit T21 repair through the normal scoped binding and formula engines.
2587
 
2588
  This is intentionally not an HTTP route. A normal workbook request must never acquire an
2589
  exceptional tenant-data mutation surface. The approved operator calls this helper with the
2590
+ exact marker/revision/source oracle and a backup store, naming the workbook with workbook_id.
2591
+ Omission retains the owner's workbook default. The helper explicitly points the core workflow
2592
+ at that target; the core refuses any workbook it was not pointed at and performs its own marker,
2593
+ snapshot, backup and readback checks.
2594
  """
2595
  from core import daily_sales_repair, sheets
2596
  import formula_runtime
 
2600
  raise daily_sales_repair.RepairRefusal(
2601
  "repair_tenant_mismatch",
2602
  "This operation may run only in the Royal Imports workspace.")
2603
+ target = str(workbook_id or "").strip() or daily_sales_repair.TARGET_WORKBOOK_ID
2604
+ book = sheets.get_workbook(_store(session), target)
2605
  _require_editor(session, book)
2606
 
2607
  view_memo = {}
 
2619
 
2620
  return daily_sales_repair.execute(
2621
  _store(session), backup_store, request,
2622
+ target_workbook_id=target,
2623
  resolve_binding=resolve, formula_check=formula_check,
2624
  actor=session.uname, actor_name=session.user.get("name") or session.uname)
2625
  except sheets.SheetRefusal as exc:
api/test_s63_integration.py CHANGED
@@ -42,60 +42,6 @@ class SourceCounts:
42
 
43
 
44
  class IntegrationTests(unittest.TestCase):
45
- def test_agent_options_respect_private_sharing_and_setup(self):
46
- from types import SimpleNamespace
47
- import automation_engine as engine
48
- import routes_automation
49
- rt = MemStore()
50
- engine.ensure_agent_contract(rt, "owned", actor="alice", name="Owned")
51
- engine.ensure_agent_contract(rt, "private", actor="bob", name="Private")
52
- engine.ensure_agent_contract(rt, "shared", actor="bob", name="Shared")
53
- recs = rt.data[engine.AGENT_CONTRACT_KEY]
54
- recs["shared"]["sharing"]["sharedWith"] = ["alice"]
55
- for key in ("purpose", "source", "workflow"):
56
- engine.answer_setup_interview(rt, "owned", key, answer="fixture")
57
- session = SimpleNamespace(runtime=rt, uname="alice", admin=False)
58
- choices = routes_automation._customer_intelligence_options(session)["agents"]
59
- self.assertEqual({r["id"]: r["ready"] for r in choices}, {"owned": True, "shared": False})
60
- self.assertNotIn("Private", json.dumps(choices))
61
- rt.data[engine.AGENT_CONTRACT_KEY]["shared"]["sharing"]["sharedWith"] = []
62
- self.assertEqual([r["id"] for r in routes_automation._customer_intelligence_options(session)["agents"]], ["owned"])
63
-
64
- def test_view_payload_round_trips_through_real_engine(self):
65
- script = r'''
66
- const fs=require('fs'),ts=require('typescript'),vm=require('vm');
67
- const source=fs.readFileSync('src/customer-grid/CustomerGrid.tsx','utf8');
68
- const file=ts.createSourceFile('view.tsx',source,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
69
- const fn=file.statements.find(n=>ts.isFunctionDeclaration(n)&&n.name.text==='customerIntelligenceViewPayload');
70
- const body=fn.getText(file).replace('export function','function');
71
- const js=ts.transpileModule(body,{compilerOptions:{target:ts.ScriptTarget.ES2020}}).outputText;
72
- const context={CUSTOMER_INTELLIGENCE_PRESET:'customer_intelligence',
73
- CUSTOMER_INTELLIGENCE_TRIGGER:'enters_view',CUSTOMER_INTELLIGENCE_ACTION:'agent_insight'};
74
- vm.runInNewContext(js,context);
75
- console.log(JSON.stringify(context.customerIntelligenceViewPayload({viewId:'view_fixture',
76
- viewName:'Fixture',table:'ut_fixture',enabled:true,agentId:'agent_fixture',slackAgentId:'channel_fixture'})));
77
- '''
78
- result = subprocess.run(["node", "-e", script], cwd=ROOT / "aios-web/web",
79
- capture_output=True, text=True, encoding="utf-8", timeout=30)
80
- self.assertEqual(result.returncode, 0, result.stderr)
81
- import automation_engine as engine
82
- payload = json.loads(result.stdout)
83
- saved, problem = engine.clean_definition(payload, username="qa", rt=MemStore())
84
- self.assertIsNone(problem)
85
- self.assertTrue(saved["trigger"]["enabled"])
86
- self.assertEqual(engine._flow_table(saved), "ut_fixture")
87
- self.assertEqual(saved["flow"]["actions"][1]["config"]["destinationId"], "channel_fixture")
88
- self.assertEqual([a["kind"] for a in saved["flow"]["actions"]], ["agent_insight", "slack"])
89
- restored, problem = engine.clean_definition(json.loads(json.dumps(saved)), username="qa", rt=MemStore())
90
- self.assertIsNone(problem)
91
- self.assertEqual(restored["trigger"], saved["trigger"])
92
- self.assertEqual(restored["flow"]["actions"], saved["flow"]["actions"])
93
- disabled = copy.deepcopy(payload)
94
- disabled["trigger"]["enabled"] = False
95
- disabled_saved, problem = engine.clean_definition(disabled, username="qa", rt=MemStore())
96
- self.assertIsNone(problem)
97
- self.assertFalse(disabled_saved["trigger"]["enabled"])
98
-
99
  def test_archived_defaults_and_removable_filter(self):
100
  fields = json.loads((ROOT / "platform/aios_grid_fields.json").read_text())["fields"]
101
  config = aios_grid._default_view_config(fields)
 
42
 
43
 
44
  class IntegrationTests(unittest.TestCase):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  def test_archived_defaults_and_removable_filter(self):
46
  fields = json.loads((ROOT / "platform/aios_grid_fields.json").read_text())["fields"]
47
  config = aios_grid._default_view_config(fields)
api/test_sheet_commit_events.py CHANGED
@@ -1,4 +1,4 @@
1
- """Exercise customer-intelligence events at the real workbook commit boundary."""
2
  import copy
3
  from pathlib import Path
4
  import sys
@@ -122,37 +122,6 @@ class CommitEvents(unittest.TestCase):
122
  sheets.put_workbook(self.st, self.book["id"], book)
123
  self.assertEqual(self.events, [])
124
 
125
- def test_real_bulk_commit_reaches_automation_once_and_replay_is_deduped(self):
126
- import automation_engine as engine
127
- raw = {
128
- "preset": "customer_intelligence", "name": "Fixture intelligence", "kind": "plain",
129
- "trigger": {"kind": "sheet_insight_changed", "workbookId": self.book["id"],
130
- "sheetId": self.tab, "enabled": True, "watch": {"ranges": ["B1:B20000"]}},
131
- "flow": {"actions": [{"id": "insight", "kind": "agent_insight",
132
- "config": {"agentId": "fixture_agent"}}]},
133
- }
134
- definition, problem = engine.clean_definition(raw, username="qa", rt=self.st)
135
- self.assertIsNone(problem)
136
- definition["id"] = "fixture_automation"
137
- self.st.data["automations"] = {definition["id"]: definition}
138
- calls, emitted = [], []
139
-
140
- def observer(st, events):
141
- emitted.extend(events)
142
- engine.workbook_insight_committed(st, events)
143
-
144
- with patch.object(sheet_events, "COMMIT_OBSERVER", observer), \
145
- patch.object(engine, "trigger_fire", side_effect=lambda *args, **kw: calls.append(args[2]) or True), \
146
- patch.object(engine, "all_definitions", wraps=engine.all_definitions) as reads:
147
- self.patch_cells({f"B{i}": {"kind": "literal", "value": i} for i in range(1, 20001)})
148
- self.assertEqual(reads.call_count, 1)
149
- self.assertEqual(calls, [definition["id"]])
150
- engine.workbook_insight_committed(self.st, emitted)
151
- self.assertEqual(calls, [definition["id"]])
152
- self.patch_cells({"Z1": {"kind": "literal", "value": 8}})
153
- self.assertEqual(calls, [definition["id"]])
154
- self.assertEqual(emitted[0]["recordCount"], 20000)
155
-
156
  def test_binding_refresh_publishes_output_change_but_not_refresh_stamp(self):
157
  cell = {"kind": "bound", "value": 10, "binding": {
158
  "database": "customers", "aggregate": "balance", "id": "current_ytd"}}
 
1
+ """Exercise value-only workbook commit notifications without crossing cell contents."""
2
  import copy
3
  from pathlib import Path
4
  import sys
 
122
  sheets.put_workbook(self.st, self.book["id"], book)
123
  self.assertEqual(self.events, [])
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  def test_binding_refresh_publishes_output_change_but_not_refresh_stamp(self):
126
  cell = {"kind": "bound", "value": 10, "binding": {
127
  "database": "customers", "aggregate": "balance", "id": "current_ytd"}}
platform/core/daily_sales_repair.py CHANGED
@@ -1,9 +1,12 @@
1
- """A refusal-first, exact-snapshot repair for the named Daily Sales workbook.
 
 
 
2
 
3
  This module does not discover source values and does not contain tenant numbers. An authorized
4
- caller supplies a one-to-one source oracle and two scoped database bindings. The module validates
5
- the complete projected document, writes and verifies a backup, then delegates one atomic,
6
- preconditioned cell mutation to :mod:`core.sheets`.
7
  """
8
 
9
  from __future__ import annotations
@@ -14,12 +17,22 @@ import re
14
  from datetime import date
15
 
16
  from core import sheets
 
17
 
18
 
19
  TARGET_WORKBOOK_ID = "b8edba3d3f47"
20
  TARGET_TENANT = "royal-imports"
21
- OPERATION = "repair-daily-sales-b8edba3d3f47"
 
 
 
 
 
 
 
22
  YTD_NAMES = {"Current YTD": "ytd", "Previous YTD": "ytd_last_year"}
 
 
23
 
24
  _VISUAL_TAB_KEYS = (
25
  "colWidths", "rowHeight", "rowHeights", "freeze", "rules", "hiddenRows", "hiddenCols",
@@ -58,15 +71,15 @@ def _addr(raw):
58
  return value
59
 
60
 
61
- def _validate_marker(marker, expected_revision):
62
  if not isinstance(marker, dict) or marker.get("direct_tenant_data_live") is not True:
63
  raise RepairRefusal(
64
  "repair_marker_required",
65
  "This repair requires the direct tenant data live marker from the owner instruction.")
66
  expected = {
67
- "operation": OPERATION,
68
  "tenant": TARGET_TENANT,
69
- "workbook_id": TARGET_WORKBOOK_ID,
70
  "expected_revision": expected_revision,
71
  }
72
  if any(marker.get(key) != value for key, value in expected.items()):
@@ -88,7 +101,7 @@ def _contains_forbidden_key(value):
88
  return False
89
 
90
 
91
- def _validate_ytd_binding(name, binding):
92
  if not isinstance(binding, dict) or _contains_forbidden_key(binding):
93
  raise RepairRefusal(
94
  "repair_binding_static",
@@ -104,11 +117,13 @@ def _validate_ytd_binding(name, binding):
104
  raise RepairRefusal(
105
  "repair_binding_scope_required",
106
  name + " must use an existing saved View so linked dimensions retain their join.")
107
- kind = (((binding.get("period") or {}).get("window") or {}).get("kind"))
108
- if kind != YTD_NAMES[name]:
 
 
109
  raise RepairRefusal(
110
  "repair_binding_period_invalid",
111
- name + " must use the " + YTD_NAMES[name] + " canonical date window.")
112
 
113
 
114
  def _preserve_visual(before, desired):
@@ -291,12 +306,15 @@ def _build_plan(current, request, resolve_binding):
291
  if not isinstance(row, dict):
292
  raise RepairRefusal("repair_binding_invalid", "Every YTD binding must be an object.")
293
  name = str(row.get("name") or "").strip()
294
- if name not in YTD_NAMES or name in binding_names:
 
 
295
  raise RepairRefusal("repair_bindings_required",
296
- "The repair requires one Current YTD and one Previous YTD binding.")
 
297
  binding_names.append(name)
298
  binding = copy.deepcopy(row.get("binding"))
299
- _validate_ytd_binding(name, binding)
300
  tab_name, address = str(row.get("sheet") or "").strip(), _addr(row.get("address"))
301
  slot = (tab_name.casefold(), address)
302
  if slot in slots:
@@ -312,7 +330,7 @@ def _build_plan(current, request, resolve_binding):
312
  if not isinstance(resolved, dict) or "value" not in resolved:
313
  raise RepairRefusal("repair_binding_unreadable", name + " did not resolve canonical data.")
314
  canonical_binding = copy.deepcopy(resolved.get("binding") or binding)
315
- _validate_ytd_binding(name, canonical_binding)
316
  desired = _preserve_visual(before, {
317
  "kind": "bound", "state": "fresh", "binding": canonical_binding,
318
  "value": copy.deepcopy(resolved["value"]),
@@ -322,7 +340,7 @@ def _build_plan(current, request, resolve_binding):
322
  desired = sheets.clean_cell(desired, addr=address)
323
  edits.append({"kind": "binding", "name": name, "sheet": tab_name,
324
  "address": address, "before": before, "after": desired})
325
- if set(binding_names) != set(YTD_NAMES):
326
  raise RepairRefusal("repair_bindings_required",
327
  "The repair requires one Current YTD and one Previous YTD binding.")
328
 
@@ -330,10 +348,10 @@ def _build_plan(current, request, resolve_binding):
330
  return edits
331
 
332
 
333
- def _write_backup(backup_store, current, digest, diff_digest):
334
  revision = int(current.get("rev") or 0)
335
- key = "sheet_repair_backup_" + TARGET_WORKBOOK_ID + "_r" + str(revision) + "_" + digest[:16]
336
- record = {"operation": OPERATION, "workbook_id": TARGET_WORKBOOK_ID,
337
  "revision": revision, "digest": digest, "diff_digest": diff_digest,
338
  "workbook": copy.deepcopy(current)}
339
 
@@ -351,21 +369,41 @@ def _write_backup(backup_store, current, digest, diff_digest):
351
  return key
352
 
353
 
354
- def execute(st, backup_store, request, *, resolve_binding, formula_check=None,
355
- actor="", actor_name=""):
356
- """Validate, back up, atomically repair and independently read back the target workbook."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  if backup_store is None or not callable(getattr(backup_store, "update", None)) \
358
  or not callable(getattr(backup_store, "get", None)):
359
  raise RepairRefusal("repair_backup_required",
360
  "A readable, writable backup store is required before repair.")
361
- if not isinstance(request, dict) or request.get("workbook_id") != TARGET_WORKBOOK_ID:
362
  raise RepairRefusal("repair_workbook_mismatch",
363
- "This operation may repair only workbook " + TARGET_WORKBOOK_ID + ".")
364
  revision = request.get("expected_revision")
365
  if isinstance(revision, bool) or not isinstance(revision, int) or revision < 0:
366
  raise RepairRefusal("repair_revision_required",
367
  "An exact expected workbook revision is required for repair.")
368
- _validate_marker(request.get("marker"), revision)
369
  try:
370
  calculation_date = date.fromisoformat(str(request.get("calculation_date") or ""))
371
  except ValueError as exc:
@@ -375,8 +413,8 @@ def execute(st, backup_store, request, *, resolve_binding, formula_check=None,
375
  raise RepairRefusal("repair_calculation_date_required",
376
  "The deterministic repair plan requires one ISO calculation date.")
377
 
378
- current = sheets.workbook_snapshot(st, TARGET_WORKBOOK_ID)
379
- if str(current.get("id") or "") != TARGET_WORKBOOK_ID:
380
  raise RepairRefusal("repair_workbook_mismatch",
381
  "The stored workbook identity does not match this repair target.")
382
  if int(current.get("rev") or 0) != revision:
@@ -400,11 +438,11 @@ def execute(st, backup_store, request, *, resolve_binding, formula_check=None,
400
  {key: copy.deepcopy(row[key]) for key in ("sheet", "address", "before", "after")}
401
  for row in edits]
402
  diff_digest = sheets.workbook_digest({"edits": exact_edits})
403
- backup_key = _write_backup(backup_store, current, digest, diff_digest)
404
  write = sheets.apply_exact_cell_edits(
405
- st, TARGET_WORKBOOK_ID, exact_edits,
406
  revision, digest, actor=actor, actor_name=actor_name)
407
- readback = sheets.workbook_snapshot(st, TARGET_WORKBOOK_ID)
408
 
409
  if int(readback.get("rev") or 0) != revision + 1:
410
  raise RepairRefusal("repair_readback_revision",
@@ -430,7 +468,7 @@ def execute(st, backup_store, request, *, resolve_binding, formula_check=None,
430
  ((_tab(readback, row["sheet"]).get("cells") or {}).get(row["address"]) or {}).get("binding"))
431
  for row in edits if row["kind"] == "binding"}
432
  return {
433
- "workbook_id": TARGET_WORKBOOK_ID,
434
  "revision_before": revision,
435
  "revision_after": readback["rev"],
436
  "backup_key": backup_key,
 
1
+ """A refusal-first, exact-snapshot repair for a Daily Sales workbook the caller names.
2
+
3
+ The core target is required so no default can point a repair at the owner's data. Every binding
4
+ window uses core.windows.normalize, the arbiter used by core.sheet_binding.clean_period (C2, S64-T20).
5
 
6
  This module does not discover source values and does not contain tenant numbers. An authorized
7
+ caller supplies a one-to-one source oracle and scoped database bindings, including both YTDs.
8
+ The module validates the complete projected document, writes and verifies a backup, then delegates
9
+ one atomic, preconditioned cell mutation to :mod:`core.sheets`.
10
  """
11
 
12
  from __future__ import annotations
 
17
  from datetime import date
18
 
19
  from core import sheets
20
+ from core import windows as W
21
 
22
 
23
  TARGET_WORKBOOK_ID = "b8edba3d3f47"
24
  TARGET_TENANT = "royal-imports"
25
+
26
+
27
+ def operation_for(workbook_id):
28
+ """Bind a repair operation to the workbook the caller names."""
29
+ return "repair-daily-sales-" + workbook_id
30
+
31
+
32
+ OPERATION = operation_for(TARGET_WORKBOOK_ID)
33
  YTD_NAMES = {"Current YTD": "ytd", "Previous YTD": "ytd_last_year"}
34
+ if not all(kind in W.WINDOW_KINDS for kind in YTD_NAMES.values()):
35
+ raise RuntimeError("C2 requires every YTD window kind to exist in core.windows.WINDOW_KINDS.")
36
 
37
  _VISUAL_TAB_KEYS = (
38
  "colWidths", "rowHeight", "rowHeights", "freeze", "rules", "hiddenRows", "hiddenCols",
 
71
  return value
72
 
73
 
74
+ def _validate_marker(marker, expected_revision, workbook_id):
75
  if not isinstance(marker, dict) or marker.get("direct_tenant_data_live") is not True:
76
  raise RepairRefusal(
77
  "repair_marker_required",
78
  "This repair requires the direct tenant data live marker from the owner instruction.")
79
  expected = {
80
+ "operation": operation_for(workbook_id),
81
  "tenant": TARGET_TENANT,
82
+ "workbook_id": workbook_id,
83
  "expected_revision": expected_revision,
84
  }
85
  if any(marker.get(key) != value for key, value in expected.items()):
 
101
  return False
102
 
103
 
104
+ def _validate_binding(name, binding, *, window_kind=None):
105
  if not isinstance(binding, dict) or _contains_forbidden_key(binding):
106
  raise RepairRefusal(
107
  "repair_binding_static",
 
117
  raise RepairRefusal(
118
  "repair_binding_scope_required",
119
  name + " must use an existing saved View so linked dimensions retain their join.")
120
+ period = binding.get("period")
121
+ window = W.normalize(copy.deepcopy(period.get("window") if isinstance(period, dict) else None))
122
+ if window is None or (window_kind is not None and window["kind"] != window_kind):
123
+ expected_window = "the " + window_kind if window_kind is not None else "a valid"
124
  raise RepairRefusal(
125
  "repair_binding_period_invalid",
126
+ name + " must use " + expected_window + " canonical date window.")
127
 
128
 
129
  def _preserve_visual(before, desired):
 
306
  if not isinstance(row, dict):
307
  raise RepairRefusal("repair_binding_invalid", "Every YTD binding must be an object.")
308
  name = str(row.get("name") or "").strip()
309
+ # S64-T21 widened this loop to ANY named report cell, so a blank or repeated name is now
310
+ # reachable for an Orders row too. The sentence has to cover both, not just the YTD pair.
311
+ if not name or name in binding_names:
312
  raise RepairRefusal("repair_bindings_required",
313
+ "Every repair binding needs its own report cell name, and the "
314
+ "repair requires one Current YTD and one Previous YTD among them.")
315
  binding_names.append(name)
316
  binding = copy.deepcopy(row.get("binding"))
317
+ _validate_binding(name, binding, window_kind=YTD_NAMES.get(name))
318
  tab_name, address = str(row.get("sheet") or "").strip(), _addr(row.get("address"))
319
  slot = (tab_name.casefold(), address)
320
  if slot in slots:
 
330
  if not isinstance(resolved, dict) or "value" not in resolved:
331
  raise RepairRefusal("repair_binding_unreadable", name + " did not resolve canonical data.")
332
  canonical_binding = copy.deepcopy(resolved.get("binding") or binding)
333
+ _validate_binding(name, canonical_binding, window_kind=YTD_NAMES.get(name))
334
  desired = _preserve_visual(before, {
335
  "kind": "bound", "state": "fresh", "binding": canonical_binding,
336
  "value": copy.deepcopy(resolved["value"]),
 
340
  desired = sheets.clean_cell(desired, addr=address)
341
  edits.append({"kind": "binding", "name": name, "sheet": tab_name,
342
  "address": address, "before": before, "after": desired})
343
+ if set(YTD_NAMES) - set(binding_names):
344
  raise RepairRefusal("repair_bindings_required",
345
  "The repair requires one Current YTD and one Previous YTD binding.")
346
 
 
348
  return edits
349
 
350
 
351
+ def _write_backup(backup_store, current, digest, diff_digest, workbook_id):
352
  revision = int(current.get("rev") or 0)
353
+ key = "sheet_repair_backup_" + workbook_id + "_r" + str(revision) + "_" + digest[:16]
354
+ record = {"operation": operation_for(workbook_id), "workbook_id": workbook_id,
355
  "revision": revision, "digest": digest, "diff_digest": diff_digest,
356
  "workbook": copy.deepcopy(current)}
357
 
 
369
  return key
370
 
371
 
372
+ def execute(st, backup_store, request, *, target_workbook_id=TARGET_WORKBOOK_ID,
373
+ resolve_binding, formula_check=None, actor="", actor_name=""):
374
+ """Validate, back up, repair and read back only the workbook this call is POINTED AT.
375
+
376
+ ⭐ `target_workbook_id` is what makes the repair general, and it is the one argument to read
377
+ twice. It is checked against THREE independent things before a byte moves: the request's own
378
+ `workbook_id`, the marker's (through `operation_for`, so a marker minted for one workbook
379
+ cannot authorise another), and the STORED document's identity. A caller pointed at a fixture
380
+ and handed a request for another workbook is refused, which is the whole point of S64-T21.
381
+
382
+ ⚠ THE DEFAULT IS THE OWNER'S WORKBOOK, DELIBERATELY, AND IT IS NOT A HOLE. It is the one
383
+ workbook this module was written for and the only one an unpointed call could ever have
384
+ reached; every other target must be NAMED. An EXPLICIT empty or non-string target still
385
+ refuses `repair_target_required`, so "pointed at nothing" and "pointed at the default" stay
386
+ different answers. Making the argument mandatory instead would have been a breaking change to
387
+ `verify_sheet.py`'s five S63-T21 call sites, a gate no lane on this board owns, and it would
388
+ have bought no safety the route does not already give: `routes_sheet.py` carries the same
389
+ default for the operator.
390
+ """
391
+ if not isinstance(target_workbook_id, str) or not target_workbook_id.strip():
392
+ raise RepairRefusal("repair_target_required",
393
+ "The repair requires an explicitly named target workbook.")
394
+ target_workbook_id = target_workbook_id.strip()
395
  if backup_store is None or not callable(getattr(backup_store, "update", None)) \
396
  or not callable(getattr(backup_store, "get", None)):
397
  raise RepairRefusal("repair_backup_required",
398
  "A readable, writable backup store is required before repair.")
399
+ if not isinstance(request, dict) or request.get("workbook_id") != target_workbook_id:
400
  raise RepairRefusal("repair_workbook_mismatch",
401
+ "This operation may repair only workbook " + target_workbook_id + ".")
402
  revision = request.get("expected_revision")
403
  if isinstance(revision, bool) or not isinstance(revision, int) or revision < 0:
404
  raise RepairRefusal("repair_revision_required",
405
  "An exact expected workbook revision is required for repair.")
406
+ _validate_marker(request.get("marker"), revision, target_workbook_id)
407
  try:
408
  calculation_date = date.fromisoformat(str(request.get("calculation_date") or ""))
409
  except ValueError as exc:
 
413
  raise RepairRefusal("repair_calculation_date_required",
414
  "The deterministic repair plan requires one ISO calculation date.")
415
 
416
+ current = sheets.workbook_snapshot(st, target_workbook_id)
417
+ if str(current.get("id") or "") != target_workbook_id:
418
  raise RepairRefusal("repair_workbook_mismatch",
419
  "The stored workbook identity does not match this repair target.")
420
  if int(current.get("rev") or 0) != revision:
 
438
  {key: copy.deepcopy(row[key]) for key in ("sheet", "address", "before", "after")}
439
  for row in edits]
440
  diff_digest = sheets.workbook_digest({"edits": exact_edits})
441
+ backup_key = _write_backup(backup_store, current, digest, diff_digest, target_workbook_id)
442
  write = sheets.apply_exact_cell_edits(
443
+ st, target_workbook_id, exact_edits,
444
  revision, digest, actor=actor, actor_name=actor_name)
445
+ readback = sheets.workbook_snapshot(st, target_workbook_id)
446
 
447
  if int(readback.get("rev") or 0) != revision + 1:
448
  raise RepairRefusal("repair_readback_revision",
 
468
  ((_tab(readback, row["sheet"]).get("cells") or {}).get(row["address"]) or {}).get("binding"))
469
  for row in edits if row["kind"] == "binding"}
470
  return {
471
+ "workbook_id": target_workbook_id,
472
  "revision_before": revision,
473
  "revision_after": readback["rev"],
474
  "backup_key": backup_key,
platform/core/sheet_binding.py CHANGED
@@ -22,6 +22,7 @@ DRAG_DOWN_NONE = "none"
22
 
23
  _MESSAGES = {
24
  "period_invalid": "{subject} is not a period this cell can use. Choose a valid start for the selected period unit.",
 
25
  "ending_invalid": "Ending {subject} cannot be used. Choose a valid ending date.",
26
  "ending_not_supported": "{subject} does not support an Ending. Choose year to date, last year to date, this month or this quarter.",
27
  "ending_cell_unreadable": "Ending from cell {subject} cannot be read. Use a cell containing a date in YYYY-MM-DD format.",
@@ -135,7 +136,10 @@ def clean_period(raw):
135
  out["ref"] = ref
136
  if (raw.get("window") is not None and "unit" not in out and "start" not in out
137
  and not out.get("frozen")):
138
- out["window"] = raw["window"]
 
 
 
139
  if not ({"start", "window", "ref", "frozen"} & set(out)):
140
  return None
141
  return out
 
22
 
23
  _MESSAGES = {
24
  "period_invalid": "{subject} is not a period this cell can use. Choose a valid start for the selected period unit.",
25
+ "period_window_invalid": "This cell's lookback window is invalid. Choose a valid window in the period control.",
26
  "ending_invalid": "Ending {subject} cannot be used. Choose a valid ending date.",
27
  "ending_not_supported": "{subject} does not support an Ending. Choose year to date, last year to date, this month or this quarter.",
28
  "ending_cell_unreadable": "Ending from cell {subject} cannot be read. Use a cell containing a date in YYYY-MM-DD format.",
 
136
  out["ref"] = ref
137
  if (raw.get("window") is not None and "unit" not in out and "start" not in out
138
  and not out.get("frozen")):
139
+ window = W.normalize(raw["window"])
140
+ if window is None:
141
+ raise BindingMetadataRefusal("period_window_invalid")
142
+ out["window"] = window
143
  if not ({"start", "window", "ref", "frozen"} & set(out)):
144
  return None
145
  return out
platform/core/sheets.py CHANGED
@@ -260,8 +260,17 @@ _MAX_HIDDEN = 5000
260
  _MAX_CHARTS = 50
261
  _MAX_UNSUPPORTED = 200
262
 
263
- #: A colour is a `--lp-*` TOKEN NAME, not a hue. Hex is allowed so a future palette door is not
264
- #: locked out, but nothing free form reaches a canvas `fillStyle` from a stored document.
 
 
 
 
 
 
 
 
 
265
  _COLOUR = re.compile(r"^[A-Za-z0-9#_-]{1,40}$")
266
 
267
  _MAX_DECIMALS = 10
@@ -533,6 +542,29 @@ def _clean_format(raw):
533
  return out
534
 
535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536
  def _clean_style(raw):
537
  """Normalize a cell's A1 style, or None when nothing survives.
538
 
@@ -555,8 +587,8 @@ def _clean_style(raw):
555
  out[mark] = True
556
 
557
  for key in ("color", "fill"):
558
- token = _text(raw.get(key), 40)
559
- if token and _COLOUR.match(token):
560
  out[key] = token
561
 
562
  align = _text(raw.get("align"), 12)
 
260
  _MAX_CHARTS = 50
261
  _MAX_UNSUPPORTED = 200
262
 
263
+ #: ⭐⭐ SDLC 64 R2 / CONTRACT C1 β€” THE ACCEPTED FORM OF A CELL COLOUR, AS ONE NAMED PATTERN.
264
+ #: Mirrored BYTE FOR BYTE in `aios-web/web/src/sheet/types.ts::CELL_COLOUR_PATTERN`, and
265
+ #: `verify_sheet.py`'s C1 leg compares the two source strings, so the client cannot start
266
+ #: writing a form this cleaner would drop.
267
+ CELL_COLOUR_PATTERN = r"^(--lp-[a-z0-9-]{1,40}|#[0-9a-f]{6})$"
268
+ _CELL_COLOUR = re.compile(CELL_COLOUR_PATTERN)
269
+
270
+ #: R2 / C1: CELL `color` / `fill` use CELL_COLOUR_PATTERN above. This older guard stays on
271
+ #: `_clean_rule_style` and `_clean_scale`: their RULE_FILLS / RULE_INKS galleries remain token
272
+ #: only. Its existing storage allowance is unchanged; a cell fill's custom door does not widen
273
+ #: the conditional-format palettes or make either guard dead.
274
  _COLOUR = re.compile(r"^[A-Za-z0-9#_-]{1,40}$")
275
 
276
  _MAX_DECIMALS = 10
 
542
  return out
543
 
544
 
545
+ def _normalise_colour(token):
546
+ """One cell colour in C1's accepted form, or "" when nothing survives.
547
+
548
+ ⭐⭐ C1's FORM IS LOWERCASE `#rrggbb`, AND THAT IS WHAT IS STORED, SO A RELOAD COMPARES
549
+ BYTE FOR BYTE EQUAL TO THE SAVE. A colour already in that form is returned unchanged:
550
+ normalisation is the identity on everything the client writes, which is the whole point.
551
+
552
+ ⚠ THE TWO COERCIONS ARE A RESCUE, NOT A CONVENIENCE. `#AABBCC` and `#abc` are forms an
553
+ IMPORTED workbook can carry, and this cleaner's house rule is to DROP what it does not
554
+ recognise, in silence. Dropping a colour somebody can see is the exact failure R2 named,
555
+ so a case difference and the three digit shorthand are widened onto the stored form
556
+ instead of being thrown away. Anything else is still dropped.
557
+ """
558
+ if not token:
559
+ return ""
560
+ if token.startswith("#"):
561
+ body = token[1:].lower()
562
+ if len(body) == 3 and all(c in "0123456789abcdef" for c in body):
563
+ body = body[0] * 2 + body[1] * 2 + body[2] * 2
564
+ token = "#" + body
565
+ return token if _CELL_COLOUR.match(token) else ""
566
+
567
+
568
  def _clean_style(raw):
569
  """Normalize a cell's A1 style, or None when nothing survives.
570
 
 
587
  out[mark] = True
588
 
589
  for key in ("color", "fill"):
590
+ token = _normalise_colour(_text(raw.get(key), 40))
591
+ if token:
592
  out[key] = token
593
 
594
  align = _text(raw.get("align"), 12)
platform/modules/finance_apps.py CHANGED
@@ -186,6 +186,9 @@ def finance_group():
186
  return deepcopy(FINANCE_GROUP)
187
 
188
 
 
 
 
189
  def finance_applications(may_open=None):
190
  """Return immutable descriptors, optionally filtered through the request permission wall."""
191
  rows = FINANCE_APPLICATIONS
 
186
  return deepcopy(FINANCE_GROUP)
187
 
188
 
189
+ # SDLC 64 / R6: also feeds GET /nav/applications through
190
+ # application_registry.py::finance_application_records. platform/core/registry.py has no Finance
191
+ # row, so may_open here is the ONLY grant between a session and a Finance application.
192
  def finance_applications(may_open=None):
193
  """Return immutable descriptors, optionally filtered through the request permission wall."""
194
  rows = FINANCE_APPLICATIONS
platform/modules/sheet.py CHANGED
@@ -66,6 +66,7 @@ REFUSALS = {
66
  "field_unknown": "{subject} is not a column on this database.",
67
  "period_invalid": "{subject} is not a period this cell can use. "
68
  "Choose a valid start for the selected period unit.",
 
69
  "ending_invalid": "Ending {subject} cannot be used. Choose a valid ending date.",
70
  "ending_not_supported": "{subject} does not support an Ending. Choose year to date, last year "
71
  "to date, this month or this quarter.",
 
66
  "field_unknown": "{subject} is not a column on this database.",
67
  "period_invalid": "{subject} is not a period this cell can use. "
68
  "Choose a valid start for the selected period unit.",
69
+ "period_window_invalid": "This cell's lookback window is invalid. Choose a valid window in the period control.",
70
  "ending_invalid": "Ending {subject} cannot be used. Choose a valid ending date.",
71
  "ending_not_supported": "{subject} does not support an Ending. Choose year to date, last year "
72
  "to date, this month or this quarter.",
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- 0521836276d5c2cbf8b1b51dfe42dcee34b5c0f5bdacc486779eeac6e63a2299
 
1
+ a1325140555b13c530dea2d818b87453a5ccb5f1021ef3f9f7a6caa0cbf25e90
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -322,411 +322,6 @@ const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48
322
  */
323
  const ONE_LINE = { whiteSpace: "nowrap" } as const;
324
 
325
- const CUSTOMER_INTELLIGENCE_PRESET = "customer_intelligence";
326
- const CUSTOMER_INTELLIGENCE_TRIGGER = "enters_view";
327
- const CUSTOMER_INTELLIGENCE_ACTION = "agent_insight";
328
-
329
- type CustomerIntelligenceChoice = { id: string; label: string; ready: boolean };
330
-
331
- function ciObject(value: unknown): Record<string, unknown> {
332
- return value && typeof value === "object" && !Array.isArray(value)
333
- ? value as Record<string, unknown>
334
- : {};
335
- }
336
-
337
- function ciObjects(value: unknown): Record<string, unknown>[] {
338
- return Array.isArray(value) ? value.map(ciObject).filter((item) => Object.keys(item).length > 0) : [];
339
- }
340
-
341
- function ciText(...values: unknown[]): string {
342
- const found = values.find((value) => typeof value === "string" && value.trim());
343
- return typeof found === "string" ? found.trim() : "";
344
- }
345
-
346
- function ciFlag(value: unknown, fallback = false): boolean {
347
- return typeof value === "boolean" ? value : fallback;
348
- }
349
-
350
- /**
351
- * S63-T09 / C2 - one frozen View-native payload. The general Automation builder is not involved:
352
- * a View contributes only its stable id, one Agent, and the selected governed destinations.
353
- * Activation uses the engine's trigger.enabled field. The source table stays in targetTable,
354
- * outside the fixed View trigger vocabulary.
355
- */
356
- export function customerIntelligenceViewPayload(input: {
357
- viewId: string;
358
- viewName: string;
359
- table: string;
360
- enabled: boolean;
361
- agentId: string;
362
- slackAgentId?: string;
363
- }): Record<string, unknown> {
364
- const destinations: Record<string, unknown> = {};
365
- const actions: Record<string, unknown>[] = [
366
- {
367
- id: "customer_intelligence_insight",
368
- kind: CUSTOMER_INTELLIGENCE_ACTION,
369
- enabled: true,
370
- config: { agentId: input.agentId },
371
- },
372
- ];
373
- if (input.slackAgentId) {
374
- destinations.slack = { destinationId: input.slackAgentId };
375
- actions.push({
376
- id: "customer_intelligence_slack",
377
- kind: "slack",
378
- enabled: true,
379
- config: { destinationId: input.slackAgentId, digestRows: 12 },
380
- });
381
- }
382
- return {
383
- name: `${input.viewName} customer intelligence`,
384
- kind: "plain",
385
- preset: CUSTOMER_INTELLIGENCE_PRESET,
386
- enabled: input.enabled,
387
- trigger: { kind: CUSTOMER_INTELLIGENCE_TRIGGER, viewId: input.viewId, enabled: input.enabled },
388
- config: {
389
- enabled: input.enabled,
390
- targetTable: input.table,
391
- viewId: input.viewId,
392
- agentId: input.agentId,
393
- destinations,
394
- },
395
- flow: { actions, ending: { mode: "terminal" } },
396
- };
397
- }
398
-
399
- /**
400
- * The active View toolbar is the product's View-settings surface. This deliberately lives in the
401
- * grid file, not the general Automation builder: the trigger and action cannot be changed here.
402
- * The server remains the readiness/permission wall; client checks make a refusal answerable
403
- * before Save. Test has its own no-send door and can never fall through to `/run`.
404
- */
405
- export function ViewCustomerIntelligenceSettings({
406
- table,
407
- view,
408
- }: {
409
- table: string;
410
- view: Pick<SavedView, "id" | "name">;
411
- }) {
412
- const [open, setOpen] = useState(false);
413
- const [loading, setLoading] = useState(true);
414
- const [saving, setSaving] = useState(false);
415
- const [testing, setTesting] = useState(false);
416
- const [automationId, setAutomationId] = useState("");
417
- const [duplicate, setDuplicate] = useState(false);
418
- const [enabled, setEnabled] = useState(false);
419
- const [agentId, setAgentId] = useState("");
420
- const [slackOn, setSlackOn] = useState(false);
421
- const [slackAgentId, setSlackAgentId] = useState("");
422
- const [agents, setAgents] = useState<CustomerIntelligenceChoice[]>([]);
423
- const [slackAgents, setSlackAgents] = useState<CustomerIntelligenceChoice[]>([]);
424
- const [slackConfigured, setSlackConfigured] = useState(false);
425
- const [message, setMessage] = useState("");
426
- const [preview, setPreview] = useState("");
427
- const [noSendReceipt, setNoSendReceipt] = useState("");
428
-
429
- useEffect(() => {
430
- const controller = new AbortController();
431
- setLoading(true);
432
- setMessage("");
433
- setPreview("");
434
- setNoSendReceipt("");
435
- void Promise.all([
436
- fetch(`${API_V1}/automations`, { credentials: CREDENTIALS, signal: controller.signal }),
437
- fetch(`${API_V1}/agents`, { credentials: CREDENTIALS, signal: controller.signal }),
438
- ]).then(async ([automationResponse, slackResponse]) => {
439
- if (!automationResponse.ok) throw new Error("automation-options");
440
- const automationBody = ciObject(await automationResponse.json());
441
- const slackBody = slackResponse.ok ? ciObject(await slackResponse.json()) : {};
442
- const rows = ciObjects(automationBody.automations);
443
- const matches = rows.filter((row) => {
444
- const config = ciObject(row.config);
445
- const trigger = ciObject(row.trigger);
446
- return ciText(row.preset, config.preset) === CUSTOMER_INTELLIGENCE_PRESET
447
- && ciText(trigger.viewId, config.viewId) === view.id;
448
- });
449
- const stored = matches[0] ?? {};
450
- setDuplicate(matches.length > 1);
451
- setAutomationId(ciText(stored.id));
452
-
453
- const config = ciObject(stored.config);
454
- const destinations = ciObject(config.destinations);
455
- const slack = ciObject(destinations.slack);
456
- const flow = ciObject(stored.flow);
457
- const actions = ciObjects(flow.actions);
458
- const insightAction = actions.find((action) => action.kind === CUSTOMER_INTELLIGENCE_ACTION);
459
- const slackAction = actions.find((action) => action.kind === "slack");
460
- const insightConfig = ciObject(insightAction?.config);
461
- const slackConfig = ciObject(slackAction?.config);
462
- setEnabled(ciFlag(ciObject(stored.trigger).enabled, false));
463
- setAgentId(ciText(config.agentId, insightConfig.agentId));
464
- const savedSlack = ciText(slack.agentId, slack.destinationId,
465
- slackConfig.agentId, slackConfig.destinationId);
466
- setSlackOn(Boolean(savedSlack));
467
- setSlackAgentId(savedSlack);
468
-
469
- const presetOptions = ciObject(automationBody.customerIntelligence);
470
- const optionAgents = ciObjects(presetOptions.agents);
471
- setAgents(optionAgents.map((row) => ({
472
- id: ciText(row.id),
473
- label: ciText(row.label, row.name) || "Unnamed Agent",
474
- ready: ciFlag(row.ready, false),
475
- })).filter((row) => row.id));
476
-
477
- setSlackConfigured(ciFlag(slackBody.configured,
478
- ciFlag(ciObject(ciObject(presetOptions.destinations).slack).ready, false)));
479
- setSlackAgents(ciObjects(slackBody.agents).map((row) => ({
480
- id: ciText(row.id),
481
- label: ciText(row.label, row.channelName) || "Governed Slack destination",
482
- ready: ciFlag(row.ready, ciFlag(row.active, false)),
483
- })).filter((row) => row.id));
484
- }).catch((error: unknown) => {
485
- if ((error as { name?: string })?.name !== "AbortError")
486
- setMessage("Customer intelligence settings could not be loaded. Try again.");
487
- }).finally(() => {
488
- if (!controller.signal.aborted) setLoading(false);
489
- });
490
- return () => controller.abort();
491
- }, [view.id]);
492
-
493
- const selectedAgent = agents.find((item) => item.id === agentId);
494
- const selectedSlack = slackAgents.find((item) => item.id === slackAgentId);
495
- const agentReady = Boolean(selectedAgent?.ready);
496
- const slackReady = !slackOn || (slackConfigured && Boolean(selectedSlack?.ready));
497
- const hasDestination = slackOn;
498
- const configured = agentReady && hasDestination && slackReady;
499
-
500
- const missing = !agentId
501
- ? "Select an Agent."
502
- : !selectedAgent
503
- ? "The selected Agent is no longer available. Choose another Agent."
504
- : !selectedAgent.ready
505
- ? "Finish setting up the selected Agent."
506
- : !hasDestination
507
- ? "Choose a governed Slack destination."
508
- : slackOn && !slackConfigured
509
- ? "Connect Slack before enabling this automation."
510
- : slackOn && !slackAgentId
511
- ? "Choose a governed Slack destination."
512
- : slackOn && !selectedSlack?.ready
513
- ? "Finish setting up the selected Slack destination."
514
- : "";
515
-
516
- const save = async () => {
517
- if (duplicate || (enabled && !configured) || saving) return;
518
- setSaving(true);
519
- setMessage("");
520
- setPreview("");
521
- setNoSendReceipt("");
522
- const payload = customerIntelligenceViewPayload({
523
- viewId: view.id,
524
- viewName: view.name,
525
- table,
526
- enabled,
527
- agentId,
528
- slackAgentId: slackOn ? slackAgentId : undefined,
529
- });
530
- try {
531
- const response = await fetch(
532
- automationId
533
- ? `${API_V1}/automations/${encodeURIComponent(automationId)}`
534
- : `${API_V1}/automations`,
535
- {
536
- method: automationId ? "PATCH" : "POST",
537
- credentials: CREDENTIALS,
538
- headers: { "Content-Type": "application/json" },
539
- body: JSON.stringify(payload),
540
- }
541
- );
542
- if (!response.ok) throw new Error("save-refused");
543
- const body = ciObject(await response.json());
544
- const saved = ciObject(body.automation);
545
- const savedId = ciText(saved.id, automationId);
546
- if (!savedId) throw new Error("missing-id");
547
- setAutomationId(savedId);
548
- setMessage("Customer intelligence saved for this View.");
549
- } catch {
550
- setMessage("Customer intelligence was not saved. Check setup and try again.");
551
- } finally {
552
- setSaving(false);
553
- }
554
- };
555
-
556
- const test = async () => {
557
- if (!automationId || !configured || testing) return;
558
- setTesting(true);
559
- setMessage("");
560
- setPreview("");
561
- setNoSendReceipt("");
562
- try {
563
- const response = await fetch(
564
- `${API_V1}/automations/${encodeURIComponent(automationId)}/customer-intelligence/dry-run`,
565
- {
566
- method: "POST",
567
- credentials: CREDENTIALS,
568
- headers: { "Content-Type": "application/json" },
569
- body: JSON.stringify({ viewId: view.id }),
570
- }
571
- );
572
- if (!response.ok) throw new Error("test-refused");
573
- const body = ciObject(await response.json());
574
- const previewBody = ciObject(body.preview);
575
- const receipt = ciObject(body.receipt);
576
- const insight = ciText(body.insight, body.preview, previewBody.insight, previewBody.summary);
577
- const noSend = receipt.dryRun === true && receipt.noDispatch === true
578
- && receipt.dispatchCount === 0 && receipt.providerCalls === 0;
579
- if (!insight || !noSend) throw new Error("unsafe-test-receipt");
580
- setPreview(insight);
581
- setNoSendReceipt("Test only. No Slack message was sent.");
582
- } catch {
583
- setMessage("The no-send test could not be completed. Nothing was sent.");
584
- } finally {
585
- setTesting(false);
586
- }
587
- };
588
-
589
- const panelStyle = {
590
- width: "min(720px, 100%)",
591
- display: "grid",
592
- gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
593
- gap: 10,
594
- padding: "10px 0 4px",
595
- } as const;
596
- const labelStyle = { display: "grid", gap: 5, color: "var(--lp-ink)" } as const;
597
-
598
- return (
599
- <section
600
- className="cg-cal-settings"
601
- aria-label="Customer intelligence"
602
- data-view-id={view.id}
603
- style={open ? { alignItems: "stretch", flexDirection: "column" } : undefined}
604
- >
605
- <button
606
- type="button"
607
- className="cg-btn"
608
- aria-expanded={open}
609
- onClick={() => setOpen((value) => !value)}
610
- style={{ alignSelf: "flex-start", display: "inline-flex", alignItems: "center", gap: 8 }}
611
- >
612
- <span>Customer intelligence</span>
613
- <span style={{ color: enabled ? "var(--lp-navy)" : "var(--lp-muted)", fontWeight: 600 }}>
614
- {enabled ? "On" : "Off"}
615
- </span>
616
- </button>
617
- {open && (
618
- <div style={panelStyle}>
619
- <p style={{ gridColumn: "1 / -1", margin: 0, color: "var(--lp-muted)" }}>
620
- Generate an insight when a record enters this View, then notify the destinations you choose.
621
- </p>
622
- <label style={labelStyle}>
623
- Trigger
624
- <input className="cg-select" value="When a record enters this View" readOnly disabled />
625
- </label>
626
- <label style={labelStyle}>
627
- Action
628
- <select className="cg-select" value={CUSTOMER_INTELLIGENCE_ACTION} disabled>
629
- <option value={CUSTOMER_INTELLIGENCE_ACTION}>Generate insight with agent</option>
630
- </select>
631
- </label>
632
- <label style={labelStyle}>
633
- Agent
634
- <select
635
- className="cg-select"
636
- value={agentId}
637
- disabled={loading}
638
- onChange={(event) => { setAgentId(event.target.value); setEnabled(false); }}
639
- >
640
- <option value="">Select an Agent</option>
641
- {agentId && !agents.some((item) => item.id === agentId) && (
642
- <option value={agentId}>Unavailable Agent</option>
643
- )}
644
- {agents.map((item) => (
645
- <option key={item.id} value={item.id} disabled={!item.ready}>
646
- {item.label}{item.ready ? "" : " (setup required)"}
647
- </option>
648
- ))}
649
- </select>
650
- </label>
651
- <fieldset style={{ border: 0, margin: 0, padding: 0, display: "grid", gap: 7 }}>
652
- <legend style={{ color: "var(--lp-ink)", marginBottom: 5 }}>Destinations</legend>
653
- <label>
654
- <input
655
- type="checkbox"
656
- checked={slackOn}
657
- onChange={(event) => { setSlackOn(event.target.checked); setEnabled(false); }}
658
- /> Slack
659
- </label>
660
- </fieldset>
661
- {slackOn && (
662
- <label style={labelStyle}>
663
- Governed Slack destination
664
- <select
665
- className="cg-select"
666
- value={slackAgentId}
667
- onChange={(event) => { setSlackAgentId(event.target.value); setEnabled(false); }}
668
- >
669
- <option value="">Choose a channel</option>
670
- {slackAgentId && !slackAgents.some((item) => item.id === slackAgentId) && (
671
- <option value={slackAgentId}>Unavailable Slack destination</option>
672
- )}
673
- {slackAgents.map((item) => (
674
- <option key={item.id} value={item.id} disabled={!item.ready}>{item.label}</option>
675
- ))}
676
- </select>
677
- </label>
678
- )}
679
- <label style={{ ...labelStyle, gridColumn: "1 / -1", display: "flex", alignItems: "center" }}>
680
- <input
681
- type="checkbox"
682
- role="switch"
683
- checked={enabled}
684
- disabled={!configured}
685
- onChange={(event) => setEnabled(event.target.checked)}
686
- />
687
- Enable Customer intelligence
688
- </label>
689
- {(missing || duplicate) && (
690
- <p role="status" style={{ gridColumn: "1 / -1", margin: 0, color: "var(--lp-muted)" }}>
691
- {duplicate
692
- ? "More than one Customer intelligence automation is linked to this View. Ask an administrator to resolve the duplicate before changing it."
693
- : missing}
694
- </p>
695
- )}
696
- <div style={{ gridColumn: "1 / -1", display: "flex", gap: 8, alignItems: "center" }}>
697
- <button
698
- type="button"
699
- className="cg-btn"
700
- disabled={loading || saving || duplicate || (enabled && !configured)}
701
- onClick={() => void save()}
702
- >
703
- {saving ? "Saving..." : "Save"}
704
- </button>
705
- <button
706
- type="button"
707
- className="cg-btn"
708
- disabled={!automationId || !configured || testing || duplicate}
709
- onClick={() => void test()}
710
- >
711
- {testing ? "Testing..." : "Test without sending"}
712
- </button>
713
- </div>
714
- {message && <p role="status" style={{ gridColumn: "1 / -1", margin: 0 }}>{message}</p>}
715
- {preview && (
716
- <div style={{ gridColumn: "1 / -1" }} aria-label="Insight preview">
717
- <strong>Insight preview</strong>
718
- <p>{preview}</p>
719
- </div>
720
- )}
721
- {noSendReceipt && (
722
- <p role="status" style={{ gridColumn: "1 / -1", margin: 0 }}>{noSendReceipt}</p>
723
- )}
724
- </div>
725
- )}
726
- </section>
727
- );
728
- }
729
-
730
  /**
731
  * How many VISIBLE columns glide freezes. Module-level and used twice on purpose (item 15): the
732
  * `freezeColumns` prop and the group bar's label fit must read ONE answer, because the label is
@@ -2479,6 +2074,7 @@ function CustomerGridSurface({
2479
  rawRows: fetchedRows,
2480
  payload,
2481
  loading,
 
2482
  overlayEdits,
2483
  setOverlayEdits,
2484
  patchOverlay,
@@ -4054,6 +3650,11 @@ function CustomerGridSurface({
4054
  requestWindow(windowRequest(0));
4055
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);
4056
 
 
 
 
 
 
4057
  /**
4058
  * The scroll β†’ next window. glide reports the visible RECTANGLE; `nextWindowOffset` decides.
4059
  *
@@ -7094,6 +6695,17 @@ function CustomerGridSurface({
7094
  [views, activeViewId, persistView]
7095
  );
7096
 
 
 
 
 
 
 
 
 
 
 
 
7097
  const selectView = useCallback(
7098
  (id: string) => {
7099
  if (isQueryPreview || isApplicationSurface) return;
@@ -7113,7 +6725,25 @@ function CustomerGridSurface({
7113
  */
7114
  const next = views.find((view) => view.id === id)
7115
  ?? (id === recordStars.stars.view?.id ? recordStars.stars.view : undefined);
7116
- if (!next) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7117
  if (next.assigned) selectAssignedView(next.id);
7118
  else clearAssignedView();
7119
  setActiveViewId(id);
@@ -7141,7 +6771,8 @@ function CustomerGridSurface({
7141
  signal(NAV_MINIMIZE_EVENT);
7142
  },
7143
  [views, activeViewId, config, persistView, fields, isQueryPreview, recordStars.stars.view,
7144
- dataPath, selectAssignedView, clearAssignedView, isApplicationSurface, emitHostEvent]
 
7145
  );
7146
 
7147
  useEffect(() => {
@@ -7156,45 +6787,37 @@ function CustomerGridSurface({
7156
  const liveDataPath = typeof window === "undefined" ? dataPath : readDataPath();
7157
  if (dataPath && (liveDataPath?.database !== dataPath.database ||
7158
  (liveDataPath.view ?? ALL_VIEW_ID) !== viewId)) return;
 
 
7159
  if (viewId === null || viewId === activeViewId) return;
7160
  if (!views.some((view) => view.id === viewId)) return;
7161
  selectView(viewId);
7162
- }, [dataPath, activeViewId, views, selectView]);
7163
 
7164
  /**
7165
  * A-S4-3 (item 25) β€” a notification's click-through. The SHELL routes to the table and fires
7166
  * this; the GRID owns view selection, so neither learns the other's state.
7167
  *
7168
- * β›” IGNORE, NEVER THROW, when the view is not ours: an alert can outlive the view it watches
7169
- * (deleted, or a share revoked), and a reader who can no longer see it must simply land on the
7170
- * table. `selectView` already returns early on an unknown id; the topic check stops one grid
7171
- * reacting to another's alert when both are mounted.
7172
  */
7173
- const parkedViewOpenRef = useRef<ViewOpenDetail | null>(null);
7174
- const parkedViewScopeRef = useRef(scope);
7175
- if (parkedViewScopeRef.current !== scope) {
7176
- // A late list for the database we just left must not replay when the user later returns.
7177
- // A new click may park one new request below; this old request has been superseded by scope.
7178
- parkedViewScopeRef.current = scope;
7179
- parkedViewOpenRef.current = null;
7180
- }
7181
  useEffect(() => {
7182
  const onOpen = (e: Event) => {
7183
  const detail = (e as CustomEvent<ViewOpenDetail>).detail;
7184
  if (!detail || detail.topic !== scope) return;
7185
- if (!views.some((v) => v.id === detail.viewId)) { parkedViewOpenRef.current = detail; return; }
7186
- parkedViewOpenRef.current = null;
7187
  selectView(detail.viewId);
7188
  };
7189
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
7190
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
7191
- }, [scope, views, selectView]);
7192
  useEffect(() => {
7193
  const parked = parkedViewOpenRef.current;
7194
- if (!parked || parked.topic !== scope || !views.some((view) => view.id === parked.viewId)) return;
 
7195
  parkedViewOpenRef.current = null;
7196
  selectView(parked.viewId);
7197
- }, [scope, selectView, views]);
7198
 
7199
  const addressedFieldRef = useRef<string | null>(null);
7200
  useEffect(() => {
@@ -10988,23 +10611,6 @@ function CustomerGridSurface({
10988
  not be wired yet: absent beats present-and-inert. A control row over a database whose
10989
  columns never arrived would offer Hide fields, Filter, Sort and Group on nothing. */}
10990
  {secondaryToolbar}
10991
- {/* S63-T09 / C2 - the active toolbar is this View's settings surface. A shared reader,
10992
- assigned projection, locked Cohort, or system View gets no configuration controls;
10993
- `mayEditView` handles ownership/edit grants and the kind checks handle server-owned
10994
- projections. The stable View id is the component key and the preset's trigger key. */}
10995
- {activeView
10996
- && !embedded
10997
- && !queryBinding
10998
- && !isApplicationSurface
10999
- && activeView.kind !== "system"
11000
- && activeView.kind !== "locked"
11001
- && mayEditView(activeView, viewer) && (
11002
- <ViewCustomerIntelligenceSettings
11003
- key={`${scope}:${activeView.id}`}
11004
- table={scope}
11005
- view={activeView}
11006
- />
11007
- )}
11008
  {workspaceDrawer && <aside className="cg-workspace-drawer" aria-label={workspaceDrawer === "notes" ? "Notes" : "History"}><header><strong>{workspaceDrawer === "notes" ? "Notes" : "History"}</strong><button type="button" className="cg-icon-button" aria-label="Close drawer" onClick={() => setWorkspaceDrawer(null)}>Γ—</button></header>{drawerBusy && <span className="lp-spin" role="status" aria-label="Loading" />}{drawerError && <p role="alert">{drawerError}</p>}{workspaceDrawer === "notes" ? <><div className="cg-note-tabs" role="group" aria-label="Notes scope"><button type="button" className="cg-note-tab" aria-pressed={notesMode === "database"} onClick={() => setNotesMode("database")}>Database note</button><button type="button" className="cg-note-tab" aria-pressed={notesMode === "view"} onClick={() => setNotesMode("view")}>View note</button></div><div className="cg-note-feed" aria-live="polite">{savedNote ? <article className="cg-record-comment"><div className="cg-record-comment-avatar" aria-hidden>{noteInitials(savedNote.author)}</div><div className="cg-record-comment-content"><div className="cg-record-comment-meta"><strong>{savedNote.author || "Unknown"}</strong><time dateTime={savedNote.updated}>{noteWhen(savedNote.updated)}</time><button type="button" className="cg-note-edit" aria-label={notesMode === "view" ? "Edit this View note" : "Edit this Database note"} title="Edit note" onClick={() => { setSharedNote(savedNote.body); setNoteEditing(true); window.setTimeout(() => document.getElementById("cg-note-input")?.focus(), 0); }}>Edit</button></div><p>{savedNote.body}</p></div></article> : !drawerBusy && <div className="cg-record-comment-state">No note yet. Write the first one below.</div>}</div><form className="cg-note-compose cg-record-comment-compose" onSubmit={(event) => { event.preventDefault(); void saveSharedNote(); }}><label htmlFor="cg-note-input">{noteEditing ? (notesMode === "view" ? "Editing this View note" : "Editing this Database note") : savedNote ? (notesMode === "view" ? "Update this View note" : "Update this Database note") : (notesMode === "view" ? "Add a View note" : "Add a Database note")}</label><textarea id="cg-note-input" className="cg-note-input" value={sharedNote} maxLength={100000} placeholder={noteEditing ? "Edit the note and save your changes" : savedNote ? "Write a new version of this note" : "Share context with the team here"} onChange={(event) => setSharedNote(event.target.value)} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }} /><div className="cg-record-comment-compose-foot"><span>Ctrl/Cmd + Enter to save</span>{noteEditing && <button type="button" className="cg-note-cancel" onClick={() => { setNoteEditing(false); setSharedNote(""); }}>Cancel</button>}<button type="submit" disabled={drawerBusy || noteSaving || !sharedNote.trim()}>{noteSaving ? "Saving…" : noteEditing ? "Save changes" : savedNote ? "Update note" : "Save note"}</button></div></form></> : <><label>Retention<select className="cg-select" value={historyRetention} onChange={(event) => setHistoryRetention(Number(event.target.value) as 30 | 90)}><option value={30}>30 days</option><option value={90}>90 days Β· platform admin</option></select></label>{historyPid == null ? <p>Select one record to inspect its history.</p> : historyRows.length === 0 && !drawerBusy ? <p>No retained changes.</p> : <ol className="cg-history-list">{historyRows.map((event, index) => <li key={String(event.id ?? index)}><strong>{String(event.field ?? event.fieldKey ?? "Record")}</strong><span>{String(event.updatedAt ?? event.at ?? "")}</span><button type="button" className="cg-link-btn" onClick={async () => { if (!window.confirm("Restore this recorded value? This writes a new auditable change and does not erase history.")) return; const id = String(event.id ?? ""); const restoreUrl = scope.startsWith("ut_") ? `${API_V1}/tables/${encodeURIComponent(scope)}/history/${encodeURIComponent(id)}/restore` : `${API_V1}/grid/history/${encodeURIComponent(id)}/restore?scope=${encodeURIComponent(scope)}`; const response = await fetch(restoreUrl, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rowId: historyPid, field: event.field ?? event.fieldKey, retentionDays: historyRetention }) }); if (!response.ok) setDrawerError("Restore was refused. Your current value was not changed."); else setWorkspaceDrawer(null); }}>Restore…</button></li>)}</ol>}</>}</aside>}
11009
  {!routeApplicationSurface && mapSettingsRow}
11010
  {/* ⭐⭐ WAVE 42 Β· W42-T19 (owner instruction 11) β€” CALENDAR'S SECOND ROW. The real
@@ -11237,7 +10843,19 @@ function CustomerGridSurface({
11237
  <span className="cg-app-launch-grid" />
11238
  </div>
11239
  )}
11240
- {displayMode === "grid" && !applicationLaunching && (
 
 
 
 
 
 
 
 
 
 
 
 
11241
  <>
11242
  <DataEditor
11243
  ref={gridRef}
 
322
  */
323
  const ONE_LINE = { whiteSpace: "nowrap" } as const;
324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
  /**
326
  * How many VISIBLE columns glide freezes. Module-level and used twice on purpose (item 15): the
327
  * `freezeColumns` prop and the group bar's label fit must read ONE answer, because the label is
 
2074
  rawRows: fetchedRows,
2075
  payload,
2076
  loading,
2077
+ windowPending,
2078
  overlayEdits,
2079
  setOverlayEdits,
2080
  patchOverlay,
 
3650
  requestWindow(windowRequest(0));
3651
  }, [serverWindowed, windowPredicate, windowRequest, requestWindow]);
3652
 
3653
+ // Reading the ref during render detects a window request owed before the effect runs,
3654
+ // so the pending skeleton paints in the click's own frame.
3655
+ const viewSwitchPending = serverWindowed
3656
+ && (windowPending || (sentPredicate.current !== null && sentPredicate.current !== windowPredicate));
3657
+
3658
  /**
3659
  * The scroll β†’ next window. glide reports the visible RECTANGLE; `nextWindowOffset` decides.
3660
  *
 
6695
  [views, activeViewId, persistView]
6696
  );
6697
 
6698
+ // Rail clicks and shell hand-offs share one pending request, owned by this database scope.
6699
+ const parkedViewOpenRef = useRef<ViewOpenDetail | null>(null);
6700
+ const parkedViewScopeRef = useRef<{ scope: string; reportedViewId: string | null }>({
6701
+ scope, reportedViewId: null,
6702
+ });
6703
+ if (parkedViewScopeRef.current.scope !== scope) {
6704
+ // A late list for the database we just left must not replay when the user later returns.
6705
+ parkedViewScopeRef.current = { scope, reportedViewId: null };
6706
+ parkedViewOpenRef.current = null;
6707
+ }
6708
+
6709
  const selectView = useCallback(
6710
  (id: string) => {
6711
  if (isQueryPreview || isApplicationSurface) return;
 
6725
  */
6726
  const next = views.find((view) => view.id === id)
6727
  ?? (id === recordStars.stars.view?.id ? recordStars.stars.view : undefined);
6728
+ if (!next) {
6729
+ if (!workspaceReady) {
6730
+ parkedViewOpenRef.current = { topic: scope, viewId: id };
6731
+ } else {
6732
+ // Resolve before signalling, including a miss received after initialization.
6733
+ parkedViewOpenRef.current = null;
6734
+ if (parkedViewScopeRef.current.reportedViewId !== id) {
6735
+ // Shell can resend the same hand-off. Keep its failure quiet after the first report.
6736
+ parkedViewScopeRef.current.reportedViewId = id;
6737
+ const databaseName = databases?.find((database) => database.key === applicationDatabase)?.label
6738
+ ?? applicationDatabase;
6739
+ signal(TOAST_EVENT, `This view is unavailable in ${databaseName}. Choose another view or ask the database owner for access.`);
6740
+ }
6741
+ }
6742
+ return;
6743
+ }
6744
+ parkedViewOpenRef.current = null;
6745
+ if (parkedViewScopeRef.current.reportedViewId === id)
6746
+ parkedViewScopeRef.current.reportedViewId = null;
6747
  if (next.assigned) selectAssignedView(next.id);
6748
  else clearAssignedView();
6749
  setActiveViewId(id);
 
6771
  signal(NAV_MINIMIZE_EVENT);
6772
  },
6773
  [views, activeViewId, config, persistView, fields, isQueryPreview, recordStars.stars.view,
6774
+ dataPath, selectAssignedView, clearAssignedView, isApplicationSurface, emitHostEvent,
6775
+ workspaceReady, scope, databases, applicationDatabase, adoptFold]
6776
  );
6777
 
6778
  useEffect(() => {
 
6787
  const liveDataPath = typeof window === "undefined" ? dataPath : readDataPath();
6788
  if (dataPath && (liveDataPath?.database !== dataPath.database ||
6789
  (liveDataPath.view ?? ALL_VIEW_ID) !== viewId)) return;
6790
+ // A cold click takes precedence over the route's initial/default selection on arrival.
6791
+ if (parkedViewOpenRef.current?.topic === scope) return;
6792
  if (viewId === null || viewId === activeViewId) return;
6793
  if (!views.some((view) => view.id === viewId)) return;
6794
  selectView(viewId);
6795
+ }, [dataPath, activeViewId, views, selectView, scope]);
6796
 
6797
  /**
6798
  * A-S4-3 (item 25) β€” a notification's click-through. The SHELL routes to the table and fires
6799
  * this; the GRID owns view selection, so neither learns the other's state.
6800
  *
6801
+ * An alert can outlive its view or share. Once this workspace is ready, `selectView` names
6802
+ * that failure and leaves the current selection intact. Before then it parks the request.
6803
+ * The topic check stops one grid reacting to another's alert when both are mounted.
 
6804
  */
 
 
 
 
 
 
 
 
6805
  useEffect(() => {
6806
  const onOpen = (e: Event) => {
6807
  const detail = (e as CustomEvent<ViewOpenDetail>).detail;
6808
  if (!detail || detail.topic !== scope) return;
 
 
6809
  selectView(detail.viewId);
6810
  };
6811
  window.addEventListener(VIEW_OPEN_EVENT, onOpen);
6812
  return () => window.removeEventListener(VIEW_OPEN_EVENT, onOpen);
6813
+ }, [scope, selectView]);
6814
  useEffect(() => {
6815
  const parked = parkedViewOpenRef.current;
6816
+ if (!parked || parked.topic !== scope) return;
6817
+ if (!workspaceReady && !views.some((view) => view.id === parked.viewId)) return;
6818
  parkedViewOpenRef.current = null;
6819
  selectView(parked.viewId);
6820
+ }, [scope, selectView, views, workspaceReady]);
6821
 
6822
  const addressedFieldRef = useRef<string | null>(null);
6823
  useEffect(() => {
 
10611
  not be wired yet: absent beats present-and-inert. A control row over a database whose
10612
  columns never arrived would offer Hide fields, Filter, Sort and Group on nothing. */}
10613
  {secondaryToolbar}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10614
  {workspaceDrawer && <aside className="cg-workspace-drawer" aria-label={workspaceDrawer === "notes" ? "Notes" : "History"}><header><strong>{workspaceDrawer === "notes" ? "Notes" : "History"}</strong><button type="button" className="cg-icon-button" aria-label="Close drawer" onClick={() => setWorkspaceDrawer(null)}>Γ—</button></header>{drawerBusy && <span className="lp-spin" role="status" aria-label="Loading" />}{drawerError && <p role="alert">{drawerError}</p>}{workspaceDrawer === "notes" ? <><div className="cg-note-tabs" role="group" aria-label="Notes scope"><button type="button" className="cg-note-tab" aria-pressed={notesMode === "database"} onClick={() => setNotesMode("database")}>Database note</button><button type="button" className="cg-note-tab" aria-pressed={notesMode === "view"} onClick={() => setNotesMode("view")}>View note</button></div><div className="cg-note-feed" aria-live="polite">{savedNote ? <article className="cg-record-comment"><div className="cg-record-comment-avatar" aria-hidden>{noteInitials(savedNote.author)}</div><div className="cg-record-comment-content"><div className="cg-record-comment-meta"><strong>{savedNote.author || "Unknown"}</strong><time dateTime={savedNote.updated}>{noteWhen(savedNote.updated)}</time><button type="button" className="cg-note-edit" aria-label={notesMode === "view" ? "Edit this View note" : "Edit this Database note"} title="Edit note" onClick={() => { setSharedNote(savedNote.body); setNoteEditing(true); window.setTimeout(() => document.getElementById("cg-note-input")?.focus(), 0); }}>Edit</button></div><p>{savedNote.body}</p></div></article> : !drawerBusy && <div className="cg-record-comment-state">No note yet. Write the first one below.</div>}</div><form className="cg-note-compose cg-record-comment-compose" onSubmit={(event) => { event.preventDefault(); void saveSharedNote(); }}><label htmlFor="cg-note-input">{noteEditing ? (notesMode === "view" ? "Editing this View note" : "Editing this Database note") : savedNote ? (notesMode === "view" ? "Update this View note" : "Update this Database note") : (notesMode === "view" ? "Add a View note" : "Add a Database note")}</label><textarea id="cg-note-input" className="cg-note-input" value={sharedNote} maxLength={100000} placeholder={noteEditing ? "Edit the note and save your changes" : savedNote ? "Write a new version of this note" : "Share context with the team here"} onChange={(event) => setSharedNote(event.target.value)} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); event.currentTarget.form?.requestSubmit(); } }} /><div className="cg-record-comment-compose-foot"><span>Ctrl/Cmd + Enter to save</span>{noteEditing && <button type="button" className="cg-note-cancel" onClick={() => { setNoteEditing(false); setSharedNote(""); }}>Cancel</button>}<button type="submit" disabled={drawerBusy || noteSaving || !sharedNote.trim()}>{noteSaving ? "Saving…" : noteEditing ? "Save changes" : savedNote ? "Update note" : "Save note"}</button></div></form></> : <><label>Retention<select className="cg-select" value={historyRetention} onChange={(event) => setHistoryRetention(Number(event.target.value) as 30 | 90)}><option value={30}>30 days</option><option value={90}>90 days Β· platform admin</option></select></label>{historyPid == null ? <p>Select one record to inspect its history.</p> : historyRows.length === 0 && !drawerBusy ? <p>No retained changes.</p> : <ol className="cg-history-list">{historyRows.map((event, index) => <li key={String(event.id ?? index)}><strong>{String(event.field ?? event.fieldKey ?? "Record")}</strong><span>{String(event.updatedAt ?? event.at ?? "")}</span><button type="button" className="cg-link-btn" onClick={async () => { if (!window.confirm("Restore this recorded value? This writes a new auditable change and does not erase history.")) return; const id = String(event.id ?? ""); const restoreUrl = scope.startsWith("ut_") ? `${API_V1}/tables/${encodeURIComponent(scope)}/history/${encodeURIComponent(id)}/restore` : `${API_V1}/grid/history/${encodeURIComponent(id)}/restore?scope=${encodeURIComponent(scope)}`; const response = await fetch(restoreUrl, { method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rowId: historyPid, field: event.field ?? event.fieldKey, retentionDays: historyRetention }) }); if (!response.ok) setDrawerError("Restore was refused. Your current value was not changed."); else setWorkspaceDrawer(null); }}>Restore…</button></li>)}</ol>}</>}</aside>}
10615
  {!routeApplicationSurface && mapSettingsRow}
10616
  {/* ⭐⭐ WAVE 42 Β· W42-T19 (owner instruction 11) β€” CALENDAR'S SECOND ROW. The real
 
10843
  <span className="cg-app-launch-grid" />
10844
  </div>
10845
  )}
10846
+ {/* S64-T01 / C4 - the view switch's own skeleton. It deliberately does NOT wear
10847
+ `cg-app-launch-state`: route-app.css:28-31 hides the Data toolbar's controls on
10848
+ `.cg-main:has(.cg-app-launch-state)`, so borrowing that class would flash the whole toolbar
10849
+ away on every rail click. Only the bar classes are reused; they carry size and the pulse. */}
10850
+ {!applicationLaunching && viewSwitchPending && (
10851
+ <div className="cg-view-pending" role="status" aria-label="Loading view"
10852
+ style={{ display: "grid", alignContent: "start", gap: 12, padding: 24 }}>
10853
+ <span className="cg-app-launch-line is-wide" />
10854
+ <span className="cg-app-launch-line" />
10855
+ <span className="cg-app-launch-grid" />
10856
+ </div>
10857
+ )}
10858
+ {displayMode === "grid" && !applicationLaunching && !viewSwitchPending && (
10859
  <>
10860
  <DataEditor
10861
  ref={gridRef}
web/src/customer-grid/useCustomerData.ts CHANGED
@@ -231,6 +231,7 @@ export interface CustomerData {
231
  rawRows: Row[];
232
  payload: CustomersPayload | null;
233
  loading: boolean;
 
234
  /** pid -> partial overlay of user-authored edits, layered OVER the fetched row. */
235
  overlayEdits: OverlayEdits;
236
  /** Raw setter β€” for live, un-persisted optimistic edits (e.g. keystrokes). */
@@ -310,6 +311,7 @@ export function useCustomerData(
310
  // Lazy initializer: in embed mode the data is already on the page, so seed it
311
  // synchronously β€” `loading` is false on the very first render (no flash).
312
  const [data, setData] = useState<CustomersPayload | null>(() => suppliedPayload ? null : readInitialPayload());
 
313
  // Item 3c: seeded SYNCHRONOUSLY from the cell journal, so a remounted grid
314
  // paints its first frame with this browser's recent edits already layered β€”
315
  // an effect would seed after paint, which is one frame of the very blip this
@@ -349,6 +351,7 @@ export function useCustomerData(
349
  if (suppliedPayloadRef.current !== suppliedPayload) {
350
  suppliedPayloadRef.current = suppliedPayload;
351
  windowSeq.current += 1;
 
352
  inflightOffset.current = null;
353
  readThroughRef.current = false;
354
  assignedBaseRows.current = null;
@@ -374,6 +377,7 @@ export function useCustomerData(
374
 
375
  dataScopeRef.current = scope;
376
  windowSeq.current += 1;
 
377
  inflightOffset.current = null;
378
  readThroughRef.current = false;
379
 
@@ -575,7 +579,9 @@ export function useCustomerData(
575
  : fetchTopicRows(topic),
576
  wsPromise,
577
  ]);
578
- if (cancelled || seq !== windowSeq.current || !payload) return;
 
 
579
  // ⚠ `false`: this call has just fetched `payload` FROM THE SERVER, and the workspace
580
  // beside it may be a memo hit. See `withWorkspace`'s `adoptFields` note β€” letting the
581
  // cached list win here is what kept a newly created column off the screen until reload.
@@ -744,6 +750,18 @@ export function useCustomerData(
744
  // purpose β€” that is a PREDICATE change, and the newest predicate must always be able to
745
  // overtake an older one rather than be suppressed by it.
746
  if (offset > 0 && inflightOffset.current === offset) return;
 
 
 
 
 
 
 
 
 
 
 
 
747
  const seq = ++windowSeq.current;
748
  if (offset > 0) inflightOffset.current = offset;
749
  /* ⭐⭐ W51-T06 / C6 β€” AND THE SCROLL CARRIES THE PIN, WHICH IS THE HALF A CLOSURE LOSES.
@@ -753,8 +771,13 @@ export function useCustomerData(
753
  count agrees with itself, and the rows are two different populations stacked. */
754
  void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
755
  if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
756
- if (seq !== windowSeq.current || !next) return;
 
 
757
  setData((prev) => mergeWindow(prev, next, offset));
 
 
 
758
  });
759
  }, [scope, related, suppliedPayload]);
760
 
@@ -790,6 +813,7 @@ export function useCustomerData(
790
  rawRows: visibleData?.rows ?? [],
791
  payload: visibleData,
792
  loading: visibleData === null,
 
793
  overlayEdits: suppliedPayload ? EMPTY_OVERLAY_EDITS : overlayEdits,
794
  setOverlayEdits: suppliedPayload ? ignoreOverlayEdits : setOverlayEdits,
795
  patchOverlay,
 
231
  rawRows: Row[];
232
  payload: CustomersPayload | null;
233
  loading: boolean;
234
+ windowPending: boolean;
235
  /** pid -> partial overlay of user-authored edits, layered OVER the fetched row. */
236
  overlayEdits: OverlayEdits;
237
  /** Raw setter β€” for live, un-persisted optimistic edits (e.g. keystrokes). */
 
311
  // Lazy initializer: in embed mode the data is already on the page, so seed it
312
  // synchronously β€” `loading` is false on the very first render (no flash).
313
  const [data, setData] = useState<CustomersPayload | null>(() => suppliedPayload ? null : readInitialPayload());
314
+ const [windowPending, setWindowPending] = useState(false);
315
  // Item 3c: seeded SYNCHRONOUSLY from the cell journal, so a remounted grid
316
  // paints its first frame with this browser's recent edits already layered β€”
317
  // an effect would seed after paint, which is one frame of the very blip this
 
351
  if (suppliedPayloadRef.current !== suppliedPayload) {
352
  suppliedPayloadRef.current = suppliedPayload;
353
  windowSeq.current += 1;
354
+ setWindowPending(false);
355
  inflightOffset.current = null;
356
  readThroughRef.current = false;
357
  assignedBaseRows.current = null;
 
377
 
378
  dataScopeRef.current = scope;
379
  windowSeq.current += 1;
380
+ setWindowPending(false);
381
  inflightOffset.current = null;
382
  readThroughRef.current = false;
383
 
 
579
  : fetchTopicRows(topic),
580
  wsPromise,
581
  ]);
582
+ if (cancelled || seq !== windowSeq.current) return;
583
+ setWindowPending(false);
584
+ if (!payload) return;
585
  // ⚠ `false`: this call has just fetched `payload` FROM THE SERVER, and the workspace
586
  // beside it may be a memo hit. See `withWorkspace`'s `adoptFields` note β€” letting the
587
  // cached list win here is what kept a newly created column off the screen until reload.
 
750
  // purpose β€” that is a PREDICATE change, and the newest predicate must always be able to
751
  // overtake an older one rather than be suppressed by it.
752
  if (offset > 0 && inflightOffset.current === offset) return;
753
+ /* β›”β›” S64-T01 / C4 β€” PENDING IS FOR THE PREDICATE CHANGE ONLY, AND THE `offset === 0` GUARD
754
+ IS THE WHOLE REASON THIS DOES NOT BREAK THE SCROLL. The two callers mean opposite things
755
+ about the rows already on screen. Offset 0 REPLACES them: it is a view switch (the rows
756
+ belong to the view the reader just left) or `CustomerGrid.tsx`'s bulk-write refresh, whose
757
+ own comment says *"Do not paint loaded rows as though they were the whole update"*. Offset
758
+ > 0 APPENDS to a window that is still the right view.
759
+ β›” Without the guard every scroll page entered pending, and `viewSwitchPending` unmounts the
760
+ `DataEditor` β€” so paging a read-through grid would blank it and return the reader to the top
761
+ of the table, on every page. `counts.ts::nextWindowOffset` returns `loaded`, always >= 1, so
762
+ that fires on EVERY append rather than in some corner. Pinned by `verify_api.py`'s C4
763
+ section and its negative control. */
764
+ if (offset === 0) setWindowPending(true);
765
  const seq = ++windowSeq.current;
766
  if (offset > 0) inflightOffset.current = offset;
767
  /* ⭐⭐ W51-T06 / C6 β€” AND THE SCROLL CARRIES THE PIN, WHICH IS THE HALF A CLOSURE LOSES.
 
771
  count agrees with itself, and the rows are two different populations stacked. */
772
  void fetchTableWindow(scope, { ...req, related, offset }).then((next) => {
773
  if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
774
+ if (seq !== windowSeq.current) return;
775
+ setWindowPending(false);
776
+ if (!next) return;
777
  setData((prev) => mergeWindow(prev, next, offset));
778
+ }).catch(() => {
779
+ if (offset > 0 && inflightOffset.current === offset) inflightOffset.current = null;
780
+ if (seq === windowSeq.current) setWindowPending(false);
781
  });
782
  }, [scope, related, suppliedPayload]);
783
 
 
813
  rawRows: visibleData?.rows ?? [],
814
  payload: visibleData,
815
  loading: visibleData === null,
816
+ windowPending,
817
  overlayEdits: suppliedPayload ? EMPTY_OVERLAY_EDITS : overlayEdits,
818
  setOverlayEdits: suppliedPayload ? ignoreOverlayEdits : setOverlayEdits,
819
  patchOverlay,
web/src/home/HomePage.tsx CHANGED
@@ -299,7 +299,10 @@ function QuickCard({
299
  detail,
300
  onClick,
301
  disabled = false,
302
- buttonTitle,
 
 
 
303
  }: {
304
  icon: React.ReactNode;
305
  title: string;
@@ -308,14 +311,21 @@ function QuickCard({
308
  onClick: (event: MouseEvent<HTMLButtonElement>) => void;
309
  disabled?: boolean;
310
  buttonTitle?: string;
 
 
 
311
  }) {
 
 
312
  return (
313
- <button type="button" className="home-card" onClick={onClick} disabled={disabled} title={buttonTitle}>
 
 
314
  <span className="home-card-head">
315
  {icon}
316
  <span className="home-card-title">{title}</span>
317
  </span>
318
- <span className="home-card-detail">{detail}</span>
319
  </button>
320
  );
321
  }
@@ -583,6 +593,9 @@ export function HomeSurface({
583
  : suppliedModuleIndex;
584
  const indexKnown = moduleHome && moduleIndex !== null;
585
  const folderWritable = indexKnown && !moduleIndexBusy && !moduleIndexError;
 
 
 
586
  const [folderEdit, setFolderEdit] = useState<{ id: string | null; name: string } | null>(null);
587
  const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(null);
588
  const [movePicker, setMovePicker] = useState(false);
@@ -598,9 +611,19 @@ export function HomeSurface({
598
  const levelApplications = mode === "app" ? appLevel.items : visibleApplications;
599
  const levelSheets = mode === "sheet" ? sheetLevel.items : visibleSheets;
600
  const levelDatabases = mode === "data" ? dataLevel.items : visibleDatabases;
 
 
 
 
 
 
 
 
 
601
  useEffect(() => {
602
  setFolderAt(mode === "data" ? new URLSearchParams(window.location.hash.split("?")[1]).get("folder") : null);
603
  setFolderEdit(null);
 
604
  setMovePicker(false);
605
  setDraggedIds([]);
606
  selection.clear();
@@ -674,16 +697,28 @@ export function HomeSurface({
674
  setDraggedIds([]);
675
  },
676
  });
677
- const newFolderControl = folderWritable ? (
 
 
 
 
678
  <QuickCard
679
  icon={<span className="home-card-icon" aria-hidden="true"><FolderMark size={16} /></span>}
680
  title="New folder"
681
  detail="Group items in this module into folders."
 
682
  disabled={mode === "data" && folders.length >= MAX_NAV_FOLDERS}
683
  buttonTitle={mode === "data" && folders.length >= MAX_NAV_FOLDERS ? "Folder limit reached" : undefined}
 
 
 
 
 
 
684
  onClick={(event) => {
685
  setFolderAnchor(event.currentTarget);
686
- setFolderEdit({ id: null, name: "" });
 
687
  }}
688
  />
689
  ) : <span className="home-card-ghost" aria-hidden="true" />;
 
299
  detail,
300
  onClick,
301
  disabled = false,
302
+ buttonTitle: cardTitle,
303
+ holdReason,
304
+ holdDetail,
305
+ busy = false,
306
  }: {
307
  icon: React.ReactNode;
308
  title: string;
 
311
  onClick: (event: MouseEvent<HTMLButtonElement>) => void;
312
  disabled?: boolean;
313
  buttonTitle?: string;
314
+ holdReason?: string;
315
+ holdDetail?: string;
316
+ busy?: boolean;
317
  }) {
318
+ // A hold reason speaks for the card while it cannot act, so it outranks the card's own tooltip.
319
+ const buttonTitle = holdReason ?? cardTitle;
320
  return (
321
+ <button type="button" className="home-card" onClick={onClick}
322
+ disabled={disabled || Boolean(holdReason)} title={buttonTitle}
323
+ aria-busy={busy ? true : undefined}>
324
  <span className="home-card-head">
325
  {icon}
326
  <span className="home-card-title">{title}</span>
327
  </span>
328
+ <span className="home-card-detail">{holdDetail ?? detail}</span>
329
  </button>
330
  );
331
  }
 
593
  : suppliedModuleIndex;
594
  const indexKnown = moduleHome && moduleIndex !== null;
595
  const folderWritable = indexKnown && !moduleIndexBusy && !moduleIndexError;
596
+ const [folderWanted, setFolderWanted] = useState(false);
597
+ const sheetFolderEarlyPaint = mode === "sheet";
598
+ const folderAwaiting = folderWanted && !folderWritable && !moduleIndexError;
599
  const [folderEdit, setFolderEdit] = useState<{ id: string | null; name: string } | null>(null);
600
  const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(null);
601
  const [movePicker, setMovePicker] = useState(false);
 
611
  const levelApplications = mode === "app" ? appLevel.items : visibleApplications;
612
  const levelSheets = mode === "sheet" ? sheetLevel.items : visibleSheets;
613
  const levelDatabases = mode === "data" ? dataLevel.items : visibleDatabases;
614
+ useEffect(() => {
615
+ if (!folderWanted) return;
616
+ if (moduleIndexError) {
617
+ setFolderWanted(false);
618
+ } else if (folderWritable) {
619
+ setFolderWanted(false);
620
+ setFolderEdit({ id: null, name: "" });
621
+ }
622
+ }, [folderWanted, folderWritable, moduleIndexError]);
623
  useEffect(() => {
624
  setFolderAt(mode === "data" ? new URLSearchParams(window.location.hash.split("?")[1]).get("folder") : null);
625
  setFolderEdit(null);
626
+ setFolderWanted(false);
627
  setMovePicker(false);
628
  setDraggedIds([]);
629
  selection.clear();
 
697
  setDraggedIds([]);
698
  },
699
  });
700
+ // Owner instruction 6: Sheet paints New folder in the first frame with its siblings.
701
+ // sheetFolderEarlyPaint moves safety to the action: onSaveModuleIndex and moveTiles both
702
+ // assume a non-null moduleIndex. App and Agents retain their current behavior because
703
+ // api_home's W61-T20 render leg asserts it, and this lane does not own that gate.
704
+ const newFolderControl = folderWritable || sheetFolderEarlyPaint ? (
705
  <QuickCard
706
  icon={<span className="home-card-icon" aria-hidden="true"><FolderMark size={16} /></span>}
707
  title="New folder"
708
  detail="Group items in this module into folders."
709
+ holdDetail={folderAwaiting ? "Waiting for folders to load." : undefined}
710
  disabled={mode === "data" && folders.length >= MAX_NAV_FOLDERS}
711
  buttonTitle={mode === "data" && folders.length >= MAX_NAV_FOLDERS ? "Folder limit reached" : undefined}
712
+ holdReason={sheetFolderEarlyPaint && !folderWritable
713
+ ? moduleIndexError
714
+ ? "Folders could not load. Use Reload folders to try again."
715
+ : folderAwaiting ? "The dialog opens as soon as the folder list loads." : undefined
716
+ : undefined}
717
+ busy={folderAwaiting}
718
  onClick={(event) => {
719
  setFolderAnchor(event.currentTarget);
720
+ if (folderWritable) { setFolderEdit({ id: null, name: "" }); return; }
721
+ setFolderWanted(true);
722
  }}
723
  />
724
  ) : <span className="home-card-ghost" aria-hidden="true" />;
web/src/settings/ExternalAccessPane.tsx CHANGED
@@ -4,13 +4,65 @@
4
  // MCP URL and a safe starter prompt; API-key secrets appear only in the one-time reveal returned
5
  // by create or rotate. All editable metadata is seeded again from the server response.
6
 
7
- import { useCallback, useEffect, useMemo, useState } from "react";
8
- import type { FormEvent } from "react";
9
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../apiContract";
10
 
11
  type Access = "read" | "readwrite";
12
  type ResourceScope = string[] | "all";
13
- type ClientId = "claude" | "chatgpt" | "claude-code" | "codex";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  interface ExternalKeyMetadata {
16
  id: string;
@@ -26,10 +78,16 @@ interface ExternalKeyMetadata {
26
  interface ScopeDatabase { database: string; label: string }
27
 
28
  interface ExternalConnection {
29
- client: ClientId;
30
- status: "connected" | "expired" | "refused" | "disconnected";
31
- connected_at: string | null;
 
 
 
 
32
  last_used: string | null;
 
 
33
  }
34
 
35
  interface KeyListResponse { keys: ExternalKeyMetadata[]; can_mint: boolean }
@@ -44,18 +102,17 @@ interface KeyDraft {
44
  expiresAt: string;
45
  }
46
 
47
- interface ClientGuide {
48
- id: ClientId;
49
- label: string;
50
- steps: string;
51
- caveat: string;
52
- copyLabel: string;
53
- }
54
 
55
  type ApiResult<T> =
56
  | { ok: true; data: T }
57
  | { ok: false; message: string; status: number };
58
 
 
 
 
 
59
  const SAFE_STARTER_PROMPT =
60
  "Using Loopable, list the databases and Views I can access. Summarize the available schemas, " +
61
  "then ask before preparing any write. Do not request or repeat credentials.";
@@ -145,15 +202,25 @@ function parseKey(value: unknown): ExternalKeyMetadata | null {
145
  function parseConnection(value: unknown): ExternalConnection | null {
146
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
147
  const row = value as Record<string, unknown>;
148
- const client = row.client;
149
- const status = row.status;
150
- if (client !== "claude" && client !== "chatgpt" && client !== "claude-code" && client !== "codex") return null;
151
- if (status !== "connected" && status !== "expired" && status !== "refused" && status !== "disconnected") return null;
 
 
 
 
152
  return {
153
- client,
154
- status,
155
- connected_at: typeof row.connected_at === "string" ? row.connected_at : null,
 
 
 
 
156
  last_used: typeof row.last_used === "string" ? row.last_used : null,
 
 
157
  };
158
  }
159
 
@@ -192,11 +259,41 @@ function connectionLabel(connection: ExternalConnection | undefined): string {
192
  if (!connection || connection.status === "disconnected") return "Not connected";
193
  if (connection.status === "connected") return "Connected";
194
  if (connection.status === "expired") return "Reconnect required";
195
- return "Connection refused";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  }
197
 
198
  export default function ExternalAccessPane() {
199
- const [door, setDoor] = useState<"apps" | "keys">("apps");
 
 
 
 
 
200
  const [keys, setKeys] = useState<ExternalKeyMetadata[] | null>(null);
201
  const [connections, setConnections] = useState<ExternalConnection[]>([]);
202
  const [canMint, setCanMint] = useState<boolean | null>(null);
@@ -220,32 +317,27 @@ export default function ExternalAccessPane() {
220
  return `${origin}${API_V1}/external/mcp`;
221
  }, []);
222
 
223
- const guides = useMemo<ClientGuide[]>(() => [
224
- {
225
- id: "claude", label: "Claude",
226
- steps: `Customize β†’ Connectors β†’ Add custom connector\nRemote MCP URL: ${mcpUrl}\nChoose Add, then Connect and finish the Loopable sign-in.`,
227
- caveat: "Available on Free, Pro, Max, Team, and Enterprise. Free is limited to one custom connector. Team and Enterprise require an Owner or Primary Owner to add it first.",
228
- copyLabel: "Copy Claude setup",
229
- },
230
- {
231
- id: "chatgpt", label: "ChatGPT",
232
- steps: `Workspace settings β†’ Apps β†’ Create\nAdd this MCP endpoint: ${mcpUrl}\nChoose OAuth, scan tools, and finish the Loopable sign-in.`,
233
- caveat: "Full MCP is available on Business and Enterprise/Edu; Pro is read/fetch only. Only admins and owners can publish apps.",
234
- copyLabel: "Copy ChatGPT setup",
235
- },
236
- {
237
- id: "claude-code", label: "Claude Code",
238
- steps: `claude mcp add --transport http loopable ${mcpUrl}\nThen open /mcp and authenticate in the browser.`,
239
- caveat: "Use a current Claude Code release. Organization policy can restrict MCP servers.",
240
- copyLabel: "Copy Claude Code command",
241
- },
242
- {
243
- id: "codex", label: "Codex",
244
- steps: `codex mcp add loopable --url ${mcpUrl}\ncodex mcp login loopable`,
245
- caveat: "CLI, IDE, and desktop share config.toml. Project-scoped configuration loads only in trusted projects.",
246
- copyLabel: "Copy Codex commands",
247
- },
248
- ], [mcpUrl]);
249
 
250
  const load = useCallback(async () => {
251
  const result = await call<KeyListResponse>("/external/keys");
@@ -265,7 +357,7 @@ export default function ExternalAccessPane() {
265
  }, []);
266
 
267
  const loadConnections = useCallback(async () => {
268
- const result = await call<ConnectionListResponse>("/external/oauth/connections");
269
  if (!result.ok || !Array.isArray(result.data?.connections)) {
270
  // Key management remains usable if OAuth discovery is unavailable.
271
  setConnections([]); return;
@@ -329,6 +421,7 @@ export default function ExternalAccessPane() {
329
  if (invalid) { setError(invalid); return; }
330
  const databases = selectedScope(databaseMode, selectedDatabases);
331
  setBusy("create"); setError(""); setNotice("");
 
332
  const result = await call<MintResponse>("/external/keys", {
333
  method: "POST",
334
  headers: { "Content-Type": "application/json" },
@@ -349,8 +442,10 @@ export default function ExternalAccessPane() {
349
  }
350
 
351
  async function copy(value: string, name: string) {
 
352
  try { await navigator.clipboard.writeText(value); setCopied(name); setError(""); }
353
  catch { setCopied(""); setError("That text could not be copied. Select it and copy it manually."); }
 
354
  }
355
 
356
  async function saveEdit(event: FormEvent) {
@@ -360,6 +455,7 @@ export default function ExternalAccessPane() {
360
  if (invalid) { setError(invalid); return; }
361
  const databases = selectedScope(editDraft.databaseMode, editDraft.databases);
362
  setBusy(`edit:${editing}`); setError(""); setNotice("");
 
363
  const result = await call<{ key: ExternalKeyMetadata }>(`/external/keys/${encodeURIComponent(editing)}`, {
364
  method: "PATCH",
365
  headers: { "Content-Type": "application/json" },
@@ -382,6 +478,7 @@ export default function ExternalAccessPane() {
382
  async function rotate(key: ExternalKeyMetadata) {
383
  if (!window.confirm(`Rotate "${key.label}"? Its current secret will stop working immediately.`)) return;
384
  setBusy(`rotate:${key.id}`); setError(""); setNotice("");
 
385
  const result = await call<MintResponse>(`/external/keys/${encodeURIComponent(key.id)}/rotate`, { method: "POST" });
386
  setBusy("");
387
  if (!result.ok) { setError(result.message); return; }
@@ -397,6 +494,7 @@ export default function ExternalAccessPane() {
397
  async function revoke(key: ExternalKeyMetadata) {
398
  if (!window.confirm(`Revoke "${key.label}"? Its next request will be refused.`)) return;
399
  setBusy(`revoke:${key.id}`); setError(""); setNotice("");
 
400
  const result = await call<{ key: ExternalKeyMetadata }>(
401
  `/external/keys/${encodeURIComponent(key.id)}/revoke`, { method: "POST" },
402
  );
@@ -409,8 +507,11 @@ export default function ExternalAccessPane() {
409
  }
410
 
411
  async function disconnect(connection: ExternalConnection) {
412
- if (!window.confirm(`Disconnect ${connection.client} from Loopable?`)) return;
 
 
413
  setBusy(`disconnect:${connection.client}`); setError("");
 
414
  const result = await call<{ connection: unknown }>(
415
  `/external/oauth/connections/${encodeURIComponent(connection.client)}/disconnect`, { method: "POST" },
416
  );
@@ -420,6 +521,91 @@ export default function ExternalAccessPane() {
420
  setNotice("AI app disconnected. Its next request will be refused.");
421
  }
422
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  async function skillDocument(action: "copy" | "download"): Promise<string | null> {
424
  setBusy(`skill-${action}`); setError(""); setNotice("");
425
  const result = await callText("/external/skill.md");
@@ -466,195 +652,283 @@ export default function ExternalAccessPane() {
466
  );
467
  }
468
 
469
- if (keys === null) {
470
- return <div className="set-loading"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading the AI API" /></div>;
471
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
472
 
473
  return (
474
  <div className="set-pane">
475
  <h1 className="set-h">AI API</h1>
476
  <p className="set-help set-pane-intro">
477
- Connect an AI app with your Loopable sign-in, or create a scoped API key for code and SDKs.
478
- Both stay inside your current permissions.
479
  </p>
480
  {error ? <p className="set-error" role="alert">{error}</p> : null}
481
  {notice ? <p className="set-notice" role="status">{notice}</p> : null}
482
 
483
- <div className="set-actions" aria-label="AI API connection choices">
484
- <button type="button" className={door === "apps" ? "set-primary" : "set-secondary"}
485
- aria-pressed={door === "apps"} onClick={() => setDoor("apps")}>Connect an AI app</button>
486
- <button type="button" className={door === "keys" ? "set-primary" : "set-secondary"}
487
- aria-pressed={door === "keys"} onClick={() => setDoor("keys")}>Create API key for code/SDK</button>
488
- </div>
489
-
490
- {door === "apps" ? (
491
- <>
492
- <section className="set-card">
493
- <h2 className="set-h4">Remote MCP</h2>
494
- <div className="set-field">
495
- <label className="set-label" htmlFor="external-mcp-url">MCP URL</label>
496
- <input id="external-mcp-url" className="set-input" value={mcpUrl} readOnly />
497
- </div>
498
- <div className="set-actions">
499
- <button type="button" className="set-secondary" onClick={() => void copy(mcpUrl, "mcp-url")}>
500
- {copied === "mcp-url" ? "Copied" : "Copy MCP URL"}
501
- </button>
502
- </div>
503
- </section>
504
-
505
- {guides.map((guide) => {
506
- const connection = connections.find((row) => row.client === guide.id);
507
- return (
508
- <section className="set-card" key={guide.id} data-client={guide.id}>
509
- <h2 className="set-h4">{guide.label}</h2>
510
- <div className="pg-drill-row"><span className="pg-drill-key">Status</span>
511
- <span className="pg-drill-val">{connectionLabel(connection)}</span></div>
512
- {connection?.status === "connected" ? (
513
- <div className="pg-drill-row"><span className="pg-drill-key">Last used</span>
514
- <span className="pg-drill-val">{when(connection.last_used)}</span></div>
515
  ) : null}
516
- <textarea className="set-input" value={guide.steps} readOnly rows={3}
517
- aria-label={`${guide.label} setup`} />
518
- <p className="set-help">{guide.caveat}</p>
519
- <div className="set-actions">
520
- <button type="button" className="set-secondary"
521
- onClick={() => void copy(guide.steps, `guide:${guide.id}`)}>
522
- {copied === `guide:${guide.id}` ? "Copied" : guide.copyLabel}
523
- </button>
524
- {connection?.status === "connected" ? (
525
- <button type="button" className="set-secondary kc-danger"
526
- disabled={busy === `disconnect:${guide.id}`} onClick={() => void disconnect(connection)}>
527
- {busy === `disconnect:${guide.id}` ? "Disconnecting…" : "Disconnect"}
 
 
 
 
 
 
 
 
 
 
 
528
  </button>
529
- ) : null}
530
  </div>
531
- </section>
532
- );
533
- })}
534
-
535
- <section className="set-card">
536
- <h2 className="set-h4">Safe starter prompt</h2>
537
- <textarea className="set-input" value={SAFE_STARTER_PROMPT} readOnly rows={3}
538
- aria-label="Safe starter prompt" />
539
- <p className="set-help">This prompt contains no API key or other secret.</p>
540
- <div className="set-actions"><button type="button" className="set-primary"
541
- onClick={() => void copy(SAFE_STARTER_PROMPT, "starter-prompt")}>
542
- {copied === "starter-prompt" ? "Copied" : "Copy starter prompt"}
543
- </button></div>
544
- </section>
545
- </>
546
- ) : (
547
- <>
548
- {revealed ? (
549
- <section className="set-card">
550
- <h2 className="set-h4">Save this API key</h2>
551
- <p className="set-help">Copy it now. This replacement is shown once; the old secret no longer works.</p>
552
- <div className="set-field"><label className="set-label" htmlFor="set-external-secret">API key</label>
553
- <input id="set-external-secret" className="set-input" type="text" value={revealed.secret}
554
- readOnly autoComplete="off" spellCheck={false} /></div>
555
- <div className="set-actions">
556
- <button type="button" className="set-primary" onClick={() => void copy(revealed.secret, "secret")}>
557
- {copied === "secret" ? "Copied" : "Copy API key"}</button>
558
- <button type="button" className="set-secondary" onClick={() => { setRevealed(null); setCopied(""); }}>Done</button>
559
- </div>
560
- </section>
561
- ) : canMint ? (
562
- <form className="set-card" onSubmit={(event) => void create(event)}>
563
- <h2 className="set-h4">New API key</h2>
564
- <div className="set-field"><label className="set-label" htmlFor="set-external-label">Label</label>
565
- <input id="set-external-label" className="set-input" type="text" maxLength={80} value={label}
566
- autoComplete="off" placeholder="Reporting SDK" onChange={(event) => setLabel(event.currentTarget.value)} /></div>
567
- <div className="set-field"><label className="set-label" htmlFor="set-external-access">Access</label>
568
- <select id="set-external-access" className="pg-select" value={access}
569
- onChange={(event) => setAccess(event.currentTarget.value as Access)}>
570
- <option value="read">Read only</option><option value="readwrite">Read and write</option>
571
- </select></div>
572
- <div className="set-field"><label className="set-label" htmlFor="set-external-databases">Resources</label>
573
- <select id="set-external-databases" className="pg-select" value={databaseMode}
574
- onChange={(event) => setDatabaseMode(event.currentTarget.value as "all" | "subset")}>
575
- <option value="all">All databases</option><option value="subset">Selected databases</option>
576
- </select></div>
577
- {databaseMode === "subset" ? databaseChecks(selectedDatabases, setSelectedDatabases) : null}
578
- <div className="set-field"><label className="set-label" htmlFor="set-external-expiry">Expiry</label>
579
- <input id="set-external-expiry" className="set-input" type="datetime-local" value={expiresAt}
580
- onChange={(event) => setExpiresAt(event.currentTarget.value)} />
581
- <p className="set-help">Leave blank for no expiry.</p></div>
582
- <div className="set-actions"><button type="submit" className="set-primary" disabled={busy === "create"}>
583
- {busy === "create" ? "Creating…" : "Create API key"}</button></div>
584
- </form>
585
- ) : canMint === false ? (
586
- <p className="set-help set-pane-intro">Creating API keys requires the Analyst module. Ask an administrator to grant it.</p>
587
- ) : null}
588
-
589
- <section className="set-card">
590
- <h2 className="set-h4">SDK skill</h2>
591
- <p className="set-help">Download or copy skill.md. It describes the API but contains no API key or other secret.</p>
592
- <div className="set-actions">
593
- <button type="button" className="set-primary" disabled={canMint !== true || busy === "skill-download"}
594
- onClick={() => void downloadSkill()}>{busy === "skill-download" ? "Preparing…" : "Download skill.md"}</button>
595
- <button type="button" className="set-secondary" disabled={canMint !== true || busy === "skill-copy"}
596
- onClick={() => void copySkill()}>{busy === "skill-copy" ? "Copying…" : copied === "skill" ? "Copied" : "Copy skill.md"}</button>
597
- </div>
598
- </section>
599
-
600
- <div className="set-perm-sect"><h2 className="set-h4">API keys</h2></div>
601
- {keys.length === 0 ? <p className="set-help">You have no API keys yet.</p> : (
602
- <div aria-label="Active API keys">
603
- {keys.map((key) => (
604
- <section className="set-card" key={key.id}>
605
- {editing === key.id && editDraft ? (
606
- <form onSubmit={(event) => void saveEdit(event)}>
607
- <h2 className="set-h4">Edit API key</h2>
608
- <div className="set-field"><label className="set-label" htmlFor={`key-label-${key.id}`}>Label</label>
609
- <input id={`key-label-${key.id}`} className="set-input" maxLength={80} value={editDraft.label}
610
- onChange={(event) => setEditDraft({ ...editDraft, label: event.currentTarget.value })} /></div>
611
- <div className="set-field"><label className="set-label" htmlFor={`key-access-${key.id}`}>Access</label>
612
- <select id={`key-access-${key.id}`} className="pg-select" value={editDraft.access}
613
- onChange={(event) => setEditDraft({ ...editDraft, access: event.currentTarget.value as Access })}>
614
  <option value="read">Read only</option><option value="readwrite">Read and write</option>
615
  </select></div>
616
- <div className="set-field"><label className="set-label" htmlFor={`key-databases-${key.id}`}>Resources</label>
617
- <select id={`key-databases-${key.id}`} className="pg-select" value={editDraft.databaseMode}
618
- onChange={(event) => setEditDraft({ ...editDraft, databaseMode: event.currentTarget.value as "all" | "subset" })}>
619
  <option value="all">All databases</option><option value="subset">Selected databases</option>
620
  </select></div>
621
- {editDraft.databaseMode === "subset"
622
- ? databaseChecks(editDraft.databases, (databases) => setEditDraft({ ...editDraft, databases })) : null}
623
- <div className="set-field"><label className="set-label" htmlFor={`key-expiry-${key.id}`}>Expiry</label>
624
- <input id={`key-expiry-${key.id}`} className="set-input" type="datetime-local" value={editDraft.expiresAt}
625
- onChange={(event) => setEditDraft({ ...editDraft, expiresAt: event.currentTarget.value })} />
626
  <p className="set-help">Leave blank for no expiry.</p></div>
627
- <div className="set-actions">
628
- <button type="submit" className="set-primary" disabled={busy === `edit:${key.id}`}>
629
- {busy === `edit:${key.id}` ? "Saving…" : "Save changes"}</button>
630
- <button type="button" className="set-secondary" onClick={() => { setEditing(null); setEditDraft(null); }}>Cancel</button>
631
- </div>
632
  </form>
633
- ) : (
634
- <>
635
- <h2 className="set-h4">{key.label}</h2>
636
- <div className="pg-drill-row"><span className="pg-drill-key">Access</span>
637
- <span className="pg-drill-val">{key.access === "read" ? "Read only" : "Read and write"}</span></div>
638
- <div className="pg-drill-row"><span className="pg-drill-key">Resources</span>
639
- <span className="pg-drill-val">{databaseLabels(key.databases)}</span></div>
640
- <div className="pg-drill-row"><span className="pg-drill-key">Expiry</span>
641
- <span className="pg-drill-val">{key.expires_at ? when(key.expires_at) : "No expiry"}</span></div>
642
- <div className="pg-drill-row"><span className="pg-drill-key">Last used</span>
643
- <span className="pg-drill-val">{when(key.last_used)}</span></div>
644
- <div className="set-actions">
645
- <button type="button" className="set-secondary" onClick={() => { setEditing(key.id); setEditDraft(draftFor(key)); }}>Edit</button>
646
- <button type="button" className="set-secondary" disabled={busy === `rotate:${key.id}`}
647
- onClick={() => void rotate(key)}>{busy === `rotate:${key.id}` ? "Rotating…" : "Rotate"}</button>
648
- <button type="button" className="set-secondary kc-danger" disabled={busy === `revoke:${key.id}`}
649
- onClick={() => void revoke(key)}>{busy === `revoke:${key.id}` ? "Revoking…" : "Revoke"}</button>
650
- </div>
651
- </>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652
  )}
653
- </section>
654
- ))}
655
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
  )}
657
- </>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  )}
659
  </div>
660
  );
 
4
  // MCP URL and a safe starter prompt; API-key secrets appear only in the one-time reveal returned
5
  // by create or rotate. All editable metadata is seeded again from the server response.
6
 
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
+ import type { FormEvent, ReactNode } from "react";
9
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../apiContract";
10
 
11
  type Access = "read" | "readwrite";
12
  type ResourceScope = string[] | "all";
13
+ type ConnectionKind = "mcp" | "key";
14
+
15
+ // Add a client only here: choices, setup, supported connections and grant matching all derive from this catalog.
16
+ const CLIENTS = [
17
+ {
18
+ id: "claude", label: "Claude", connections: ["mcp"],
19
+ steps: (mcpUrl: string) => `Customize β†’ Connectors β†’ Add custom connector\nRemote MCP URL: ${mcpUrl}\nChoose Add, then Connect and finish the Loopable sign-in.`,
20
+ caveat: "Available on Free, Pro, Max, Team, and Enterprise. Free is limited to one custom connector. Team and Enterprise require an Owner or Primary Owner to add it first.",
21
+ copyLabel: "Copy Claude setup", match: ["claude"],
22
+ },
23
+ {
24
+ id: "chatgpt", label: "ChatGPT", connections: ["mcp"],
25
+ steps: (mcpUrl: string) => `Workspace settings β†’ Apps β†’ Create\nAdd this MCP endpoint: ${mcpUrl}\nChoose OAuth, scan tools, and finish the Loopable sign-in.`,
26
+ caveat: "Full MCP is available on Business and Enterprise/Edu; Pro is read/fetch only. Only admins and owners can publish apps.",
27
+ copyLabel: "Copy ChatGPT setup", match: ["chatgpt", "chat gpt"],
28
+ },
29
+ {
30
+ id: "claude-code", label: "Claude Code", connections: ["mcp", "key"],
31
+ steps: (mcpUrl: string) => `claude mcp add --transport http loopable ${mcpUrl}\nThen open /mcp and authenticate in the browser.`,
32
+ keySteps: (mcpUrl: string) => `Run in your terminal, replacing <YOUR_API_KEY> with your saved key:\nclaude mcp add \\\n --transport http loopable ${mcpUrl} \\\n --header "Authorization: Bearer <YOUR_API_KEY>"\nIf loopable is already configured, remove its old entry with claude mcp remove loopable first.\nOpen /mcp to check the server. Keep the key out of chat messages.`,
33
+ caveat: "Use a current Claude Code release. Organization policy can restrict MCP servers.",
34
+ copyLabel: "Copy Claude Code command", match: ["claude code", "claude-code", "claude_code"],
35
+ },
36
+ {
37
+ id: "codex", label: "Codex", connections: ["mcp", "key"],
38
+ steps: (mcpUrl: string) => `codex mcp add loopable --url ${mcpUrl}\ncodex mcp login loopable`,
39
+ keySteps: (mcpUrl: string) => `In ~/.codex/config.toml, add or update this server:\n[mcp_servers.loopable]\nurl = "${mcpUrl}"\nhttp_headers = { Authorization = "Bearer <YOUR_API_KEY>" }\nReplace <YOUR_API_KEY> with your saved key locally, then restart Codex. Keep the key out of chat messages.`,
40
+ caveat: "CLI, IDE, and desktop share config.toml. Project-scoped configuration loads only in trusted projects.",
41
+ copyLabel: "Copy Codex commands", match: ["codex"],
42
+ },
43
+ {
44
+ id: "cursor", label: "Cursor", connections: ["mcp", "key"],
45
+ steps: (mcpUrl: string) => `Settings β†’ Tools and Integrations β†’ New MCP Server\nAdd this server in ~/.cursor/mcp.json, keeping any existing servers:\n${JSON.stringify({ mcpServers: { loopable: { url: mcpUrl } } }, null, 2)}\nReopen the server and finish the Loopable sign-in.`,
46
+ keySteps: (mcpUrl: string) => `In ~/.cursor/mcp.json, add or update this server, keeping any other servers:\n${JSON.stringify({ mcpServers: { loopable: { url: mcpUrl, headers: { Authorization: "Bearer <YOUR_API_KEY>" } } } }, null, 2)}\nReplace <YOUR_API_KEY> with your saved key locally, then reopen the server. Keep the key out of chat messages.`,
47
+ caveat: "Cursor reads project servers from .cursor/mcp.json and personal servers from the home folder. An organization policy can block a server.",
48
+ copyLabel: "Copy Cursor setup", match: ["cursor"],
49
+ },
50
+ ] as const satisfies readonly {
51
+ id: string;
52
+ label: string;
53
+ connections: readonly ConnectionKind[];
54
+ steps: (mcpUrl: string) => string;
55
+ keySteps?: (mcpUrl: string) => string;
56
+ caveat: string;
57
+ copyLabel: string;
58
+ match: readonly string[];
59
+ }[];
60
+
61
+ type ClientId = (typeof CLIENTS)[number]["id"];
62
+
63
+ function isClientId(value: unknown): value is ClientId {
64
+ return typeof value === "string" && CLIENTS.some((entry) => entry.id === value);
65
+ }
66
 
67
  interface ExternalKeyMetadata {
68
  id: string;
 
78
  interface ScopeDatabase { database: string; label: string }
79
 
80
  interface ExternalConnection {
81
+ id: string;
82
+ // This field holds the grant id; its existing name keeps disconnect URLs addressing the server's connection id.
83
+ client: string;
84
+ clientId: ClientId | null;
85
+ label: string | null;
86
+ status: "connected" | "expired" | "disconnected";
87
+ created: string | null;
88
  last_used: string | null;
89
+ expires_at: string | null;
90
+ disconnected_at: string | null;
91
  }
92
 
93
  interface KeyListResponse { keys: ExternalKeyMetadata[]; can_mint: boolean }
 
102
  expiresAt: string;
103
  }
104
 
105
+ type VerifyResult = { state: "ok" | "failed"; message: string };
106
+ type StepState = "done" | "current" | "waiting";
 
 
 
 
 
107
 
108
  type ApiResult<T> =
109
  | { ok: true; data: T }
110
  | { ok: false; message: string; status: number };
111
 
112
+ // The one spelling of the OAuth connections route. The pane reads it on mount and again when
113
+ // the MCP step verifies, and two copies of a route are two things to keep in step.
114
+ const CONNECTIONS_PATH = "/external/oauth/connections";
115
+
116
  const SAFE_STARTER_PROMPT =
117
  "Using Loopable, list the databases and Views I can access. Summarize the available schemas, " +
118
  "then ask before preparing any write. Do not request or repeat credentials.";
 
202
  function parseConnection(value: unknown): ExternalConnection | null {
203
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
204
  const row = value as Record<string, unknown>;
205
+ if (typeof row.id !== "string" || !row.id.trim()) return null;
206
+ const label = typeof row.label === "string" ? row.label : null;
207
+ // Prefer the longest matching name, so Claude Code resolves before the broader Claude match.
208
+ const resolved = CLIENTS.flatMap((entry) => entry.match.map((match) => ({ id: entry.id, match })))
209
+ .sort((a, b) => b.match.length - a.match.length)
210
+ .find((entry) => label?.toLowerCase().includes(entry.match))?.id;
211
+ const expires_at = typeof row.expires_at === "string" ? row.expires_at : null;
212
+ const disconnected_at = typeof row.disconnected_at === "string" ? row.disconnected_at : null;
213
  return {
214
+ id: row.id,
215
+ client: row.id,
216
+ clientId: isClientId(resolved) ? resolved : null,
217
+ label,
218
+ status: disconnected_at ? "disconnected"
219
+ : expires_at && Date.parse(expires_at) <= Date.now() ? "expired" : "connected",
220
+ created: typeof row.created === "string" ? row.created : null,
221
  last_used: typeof row.last_used === "string" ? row.last_used : null,
222
+ expires_at,
223
+ disconnected_at,
224
  };
225
  }
226
 
 
259
  if (!connection || connection.status === "disconnected") return "Not connected";
260
  if (connection.status === "connected") return "Connected";
261
  if (connection.status === "expired") return "Reconnect required";
262
+ return "Not connected";
263
+ }
264
+
265
+ function Step({ number, title, state, value, children }: {
266
+ number: number; title: string; state: StepState; value?: string; children: ReactNode;
267
+ }) {
268
+ return (
269
+ <li data-step={number} data-state={state} aria-current={state === "current" ? "step" : undefined}
270
+ style={{ display: "grid", gridTemplateColumns: "32px minmax(0, 1fr)", gap: 12 }}>
271
+ <span aria-hidden="true" style={{
272
+ display: "grid", placeItems: "center", height: 32, borderRadius: "var(--lp-r-md)",
273
+ background: state === "current" ? "var(--lp-blue-tint)" : "var(--lp-wash)",
274
+ color: "var(--lp-ink)", fontWeight: 600,
275
+ }}>{number}</span>
276
+ <div>
277
+ <div style={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 8, minHeight: 32 }}>
278
+ <h2 className="set-h4" style={{ margin: 0 }}>{title}</h2>
279
+ <span className="set-help" style={{ margin: 0 }}>
280
+ {state === "done" ? "Done" : state === "current" ? "Current" : "Waiting"}
281
+ </span>
282
+ </div>
283
+ {value ? <p className="set-help" style={{ margin: "4px 0 8px" }}>{value}</p> : null}
284
+ <div style={{ marginTop: 8 }}>{children}</div>
285
+ </div>
286
+ </li>
287
+ );
288
  }
289
 
290
  export default function ExternalAccessPane() {
291
+ const [clientId, setClientId] = useState<ClientId | null>(null);
292
+ const [connection, setConnection] = useState<ConnectionKind | null>(null);
293
+ const [readyToVerify, setReadyToVerify] = useState(false);
294
+ const [verifyResult, setVerifyResult] = useState<VerifyResult | null>(null);
295
+ const [verifySecret, setVerifySecret] = useState("");
296
+ const verificationVersion = useRef(0);
297
  const [keys, setKeys] = useState<ExternalKeyMetadata[] | null>(null);
298
  const [connections, setConnections] = useState<ExternalConnection[]>([]);
299
  const [canMint, setCanMint] = useState<boolean | null>(null);
 
317
  return `${origin}${API_V1}/external/mcp`;
318
  }, []);
319
 
320
+ const client = CLIENTS.find((entry) => entry.id === clientId);
321
+ const connectionKinds: readonly ConnectionKind[] = client?.connections ?? [];
322
+ const setup = client && connection
323
+ ? connection === "mcp" ? client.steps(mcpUrl) : "keySteps" in client ? client.keySteps(mcpUrl) : ""
324
+ : "";
325
+
326
+ function resetVerification() {
327
+ verificationVersion.current += 1;
328
+ setVerifyResult(null); setVerifySecret("");
329
+ }
330
+
331
+ function chooseClient(id: ClientId) {
332
+ const entry = CLIENTS.find((candidate) => candidate.id === id);
333
+ setClientId(id);
334
+ setConnection(entry?.connections.length === 1 ? entry.connections[0] : null);
335
+ setReadyToVerify(false); resetVerification(); setCopied(""); setError(""); setNotice("");
336
+ }
337
+
338
+ function chooseConnection(kind: ConnectionKind) {
339
+ setConnection(kind); setReadyToVerify(false); resetVerification(); setCopied(""); setError(""); setNotice("");
340
+ }
 
 
 
 
 
341
 
342
  const load = useCallback(async () => {
343
  const result = await call<KeyListResponse>("/external/keys");
 
357
  }, []);
358
 
359
  const loadConnections = useCallback(async () => {
360
+ const result = await call<ConnectionListResponse>(CONNECTIONS_PATH);
361
  if (!result.ok || !Array.isArray(result.data?.connections)) {
362
  // Key management remains usable if OAuth discovery is unavailable.
363
  setConnections([]); return;
 
421
  if (invalid) { setError(invalid); return; }
422
  const databases = selectedScope(databaseMode, selectedDatabases);
423
  setBusy("create"); setError(""); setNotice("");
424
+ resetVerification();
425
  const result = await call<MintResponse>("/external/keys", {
426
  method: "POST",
427
  headers: { "Content-Type": "application/json" },
 
442
  }
443
 
444
  async function copy(value: string, name: string) {
445
+ setBusy(`copy:${name}`);
446
  try { await navigator.clipboard.writeText(value); setCopied(name); setError(""); }
447
  catch { setCopied(""); setError("That text could not be copied. Select it and copy it manually."); }
448
+ finally { setBusy((current) => current === `copy:${name}` ? "" : current); }
449
  }
450
 
451
  async function saveEdit(event: FormEvent) {
 
455
  if (invalid) { setError(invalid); return; }
456
  const databases = selectedScope(editDraft.databaseMode, editDraft.databases);
457
  setBusy(`edit:${editing}`); setError(""); setNotice("");
458
+ resetVerification();
459
  const result = await call<{ key: ExternalKeyMetadata }>(`/external/keys/${encodeURIComponent(editing)}`, {
460
  method: "PATCH",
461
  headers: { "Content-Type": "application/json" },
 
478
  async function rotate(key: ExternalKeyMetadata) {
479
  if (!window.confirm(`Rotate "${key.label}"? Its current secret will stop working immediately.`)) return;
480
  setBusy(`rotate:${key.id}`); setError(""); setNotice("");
481
+ resetVerification();
482
  const result = await call<MintResponse>(`/external/keys/${encodeURIComponent(key.id)}/rotate`, { method: "POST" });
483
  setBusy("");
484
  if (!result.ok) { setError(result.message); return; }
 
494
  async function revoke(key: ExternalKeyMetadata) {
495
  if (!window.confirm(`Revoke "${key.label}"? Its next request will be refused.`)) return;
496
  setBusy(`revoke:${key.id}`); setError(""); setNotice("");
497
+ resetVerification();
498
  const result = await call<{ key: ExternalKeyMetadata }>(
499
  `/external/keys/${encodeURIComponent(key.id)}/revoke`, { method: "POST" },
500
  );
 
507
  }
508
 
509
  async function disconnect(connection: ExternalConnection) {
510
+ const name = connection.label?.trim()
511
+ || CLIENTS.find((entry) => entry.id === connection.clientId)?.label || "this AI app";
512
+ if (!window.confirm(`Disconnect ${name} from Loopable?`)) return;
513
  setBusy(`disconnect:${connection.client}`); setError("");
514
+ resetVerification();
515
  const result = await call<{ connection: unknown }>(
516
  `/external/oauth/connections/${encodeURIComponent(connection.client)}/disconnect`, { method: "POST" },
517
  );
 
521
  setNotice("AI app disconnected. Its next request will be refused.");
522
  }
523
 
524
+ async function verifyKey() {
525
+ const secret = revealed?.secret ?? verifySecret.trim();
526
+ if (!secret || !readyToVerify || connection !== "key") return;
527
+ setBusy("verify:key"); setVerifyResult(null);
528
+ const version = ++verificationVersion.current;
529
+ const report = (state: VerifyResult["state"], message: string) => {
530
+ if (version !== verificationVersion.current) return;
531
+ // A refusal may include server text; never let a reflected credential reach the result region.
532
+ setVerifyResult({ state, message: message.split(secret).join("[redacted]") });
533
+ };
534
+ try {
535
+ // Omit the cookie so success proves the bearer alone. Do not dispatch UNAUTHORIZED_EVENT
536
+ // or call checkTenant: a refused key is expected here and must not end the browser session.
537
+ const response = await fetch(`${API_V1}/external/whoami`, {
538
+ credentials: "omit",
539
+ headers: { Authorization: `Bearer ${secret}` },
540
+ });
541
+ setVerifySecret("");
542
+ let body: unknown = null;
543
+ try { body = await response.json(); } catch { /* Report unreadable successes and generic refusals. */ }
544
+ if (!response.ok) {
545
+ const cause = response.status === 401 ? "The key was refused. It may be wrong, expired or revoked. "
546
+ : response.status === 403 ? "The key is valid, but the account has no Analyst module. " : "";
547
+ const fallback = response.status >= 500
548
+ ? "The AI API is unavailable right now." : "That request could not be completed.";
549
+ report("failed", `${response.status}: ${cause}${messageFrom(body, fallback)}`);
550
+ return;
551
+ }
552
+ const identity = body && typeof body === "object" && !Array.isArray(body)
553
+ ? body as Record<string, unknown> : null;
554
+ const name = typeof identity?.name === "string" && identity.name.trim() ? identity.name
555
+ : typeof identity?.username === "string" ? identity.username : "";
556
+ const databases = identity?.databases;
557
+ if (!name || (identity?.access !== "read" && identity?.access !== "readwrite")
558
+ || (databases !== "all" && (!Array.isArray(databases)
559
+ || !databases.every((database) => typeof database === "string")))) {
560
+ report("failed", "The AI API returned an unreadable response.");
561
+ return;
562
+ }
563
+ const accessLabel = identity.access === "read" ? "Read only" : "Read and write";
564
+ const scopeLabel = databases === "all" ? "All databases"
565
+ : `${databases.length} ${databases.length === 1 ? "database" : "databases"}`;
566
+ report("ok", `API key accepted for ${name}. ${accessLabel}. ${scopeLabel}.`);
567
+ } catch {
568
+ report("failed", "The server could not be reached.");
569
+ } finally {
570
+ setVerifySecret("");
571
+ setBusy((current) => current === "verify:key" ? "" : current);
572
+ }
573
+ }
574
+
575
+ async function verifyMcp() {
576
+ if (!client || !readyToVerify || connection !== "mcp") return;
577
+ setBusy("verify:mcp"); setVerifyResult(null);
578
+ const version = ++verificationVersion.current;
579
+ // OAuth grants belong to the signed-in session, independently of the API-key bearer check.
580
+ const result = await call<ConnectionListResponse>(CONNECTIONS_PATH);
581
+ setBusy((current) => current === "verify:mcp" ? "" : current);
582
+ if (version !== verificationVersion.current) return;
583
+ if (!result.ok) {
584
+ setVerifyResult({ state: "failed", message: result.status ? `${result.status}: ${result.message}` : result.message });
585
+ return;
586
+ }
587
+ if (!Array.isArray(result.data?.connections)) {
588
+ setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." });
589
+ return;
590
+ }
591
+ const parsed = result.data.connections.map(parseConnection);
592
+ const grants = parsed.filter((row): row is ExternalConnection => row !== null);
593
+ if (grants.length !== parsed.length) {
594
+ setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." });
595
+ return;
596
+ }
597
+ setConnections(grants);
598
+ const live = grants.filter((grant) => grant.status === "connected");
599
+ const matched = live.find((grant) => grant.clientId === client.id);
600
+ if (matched) {
601
+ setVerifyResult({ state: "ok", message: `Loopable sign-in completed for ${matched.label}. Last used: ${when(matched.last_used)}.` });
602
+ } else if (live.length) {
603
+ setVerifyResult({ state: "failed", message: `Connected: ${live.map((grant) => grant.label || "Unnamed AI app").join(", ")}. None can be identified as ${client.label}. Loopable identifies a connection by the name the client registered itself under. Finish the ${client.label} sign-in, then check again.` });
604
+ } else {
605
+ setVerifyResult({ state: "failed", message: "No completed sign-in yet. Finish the sign-in the client opened in the browser, then check again." });
606
+ }
607
+ }
608
+
609
  async function skillDocument(action: "copy" | "download"): Promise<string | null> {
610
  setBusy(`skill-${action}`); setError(""); setNotice("");
611
  const result = await callText("/external/skill.md");
 
652
  );
653
  }
654
 
655
+ const revealCard = revealed ? (
656
+ <section className="set-card">
657
+ <h2 className="set-h4">Save this API key</h2>
658
+ <p className="set-help">Copy it now. Loopable cannot show this secret again.</p>
659
+ <div className="set-field"><label className="set-label" htmlFor="set-external-secret">API key</label>
660
+ <input id="set-external-secret" className="set-input" type="text" value={revealed.secret}
661
+ readOnly autoComplete="off" spellCheck={false} /></div>
662
+ <div className="set-actions">
663
+ <button type="button" className="set-primary" disabled={busy !== ""}
664
+ onClick={() => void copy(revealed.secret, "secret")}>
665
+ {busy === "copy:secret" ? "Copying…" : copied === "secret" ? "Copied" : "Copy API key"}</button>
666
+ <button type="button" className="set-secondary" disabled={busy !== ""}
667
+ onClick={() => { setRevealed(null); setCopied(""); }}>Done</button>
668
+ </div>
669
+ </section>
670
+ ) : null;
671
 
672
  return (
673
  <div className="set-pane">
674
  <h1 className="set-h">AI API</h1>
675
  <p className="set-help set-pane-intro">
676
+ Choose your AI client, follow its setup, then verify the connection.
 
677
  </p>
678
  {error ? <p className="set-error" role="alert">{error}</p> : null}
679
  {notice ? <p className="set-notice" role="status">{notice}</p> : null}
680
 
681
+ <ol aria-label="Connect to Loopable" style={{ listStyle: "none", padding: 0, margin: "24px 0", display: "grid", gap: 24 }}>
682
+ <Step number={1} title="Choose a client" state={client ? "done" : "current"} value={client?.label}>
683
+ <div className="set-actions" style={{ marginTop: 0 }}>
684
+ {CLIENTS.map((entry) => (
685
+ <button key={entry.id} type="button" className="set-secondary" data-client={entry.id}
686
+ aria-pressed={clientId === entry.id} disabled={busy !== ""}
687
+ style={{ background: clientId === entry.id ? "var(--lp-blue-tint)" : "var(--lp-surface)" }}
688
+ onClick={() => chooseClient(entry.id)}>{entry.label}</button>
689
+ ))}
690
+ </div>
691
+ </Step>
692
+
693
+ <Step number={2} title="Connection" state={!client ? "waiting" : connection ? "done" : "current"}
694
+ value={connection ? connection === "mcp" ? "Loopable sign-in" : "API key" : undefined}>
695
+ {!client ? <p className="set-help">Choose a client first.</p> : connectionKinds.length === 1 ? (
696
+ <p className="set-help">{client.label} connects with {connection === "mcp" ? "your Loopable sign-in" : "an API key"}. There is nothing to choose here.</p>
697
+ ) : (
698
+ <>
699
+ <p className="set-help">Use your Loopable sign-in, or an API key you manage. Both stay inside your current permissions.</p>
700
+ <div className="set-actions" aria-label="AI API connection choices">
701
+ {connectionKinds.includes("mcp") ? (
702
+ <button type="button" className="set-secondary" data-connection="mcp"
703
+ style={{ background: connection === "mcp" ? "var(--lp-blue-tint)" : "var(--lp-surface)" }}
704
+ disabled={busy !== ""} aria-pressed={connection === "mcp"}
705
+ onClick={() => chooseConnection("mcp")}>Connect an AI app</button>
 
 
 
 
 
 
 
706
  ) : null}
707
+ {connectionKinds.includes("key") ? (
708
+ <button type="button" className="set-secondary" data-connection="key"
709
+ style={{ background: connection === "key" ? "var(--lp-blue-tint)" : "var(--lp-surface)" }}
710
+ disabled={busy !== ""} aria-pressed={connection === "key"}
711
+ onClick={() => chooseConnection("key")}>Create API key for code/SDK</button>
712
+ ) : null}
713
+ </div>
714
+ </>
715
+ )}
716
+ </Step>
717
+
718
+ <Step number={3} title="Connect" state={!connection ? "waiting" : readyToVerify ? "done" : "current"}
719
+ value={readyToVerify ? `${client?.label} setup ready to check` : undefined}>
720
+ {!client || !connection ? <p className="set-help">Choose the connection to see its setup.</p> : (
721
+ <>
722
+ {connection === "mcp" ? (
723
+ <div className="set-field">
724
+ <label className="set-label" htmlFor="external-mcp-url">MCP URL</label>
725
+ <input id="external-mcp-url" className="set-input" value={mcpUrl} readOnly />
726
+ <div className="set-actions">
727
+ <button type="button" className="set-secondary" disabled={busy !== ""}
728
+ onClick={() => void copy(mcpUrl, "mcp-url")}>
729
+ {busy === "copy:mcp-url" ? "Copying…" : copied === "mcp-url" ? "Copied" : "Copy MCP URL"}
730
  </button>
731
+ </div>
732
  </div>
733
+ ) : (
734
+ <>
735
+ <p className="set-help" style={{ marginBottom: 12 }}>Use a saved API key or create one here, then add it to {client.label}.</p>
736
+ {revealed ? revealCard : canMint ? (
737
+ <form className="set-card" onSubmit={(event) => void create(event)}>
738
+ <h2 className="set-h4">New API key</h2>
739
+ <div className="set-field"><label className="set-label" htmlFor="set-external-label">Label</label>
740
+ <input id="set-external-label" className="set-input" type="text" maxLength={80} value={label}
741
+ autoComplete="off" placeholder="Reporting SDK" onChange={(event) => setLabel(event.currentTarget.value)} /></div>
742
+ <div className="set-field"><label className="set-label" htmlFor="set-external-access">Access</label>
743
+ <select id="set-external-access" className="pg-select" value={access}
744
+ onChange={(event) => setAccess(event.currentTarget.value as Access)}>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745
  <option value="read">Read only</option><option value="readwrite">Read and write</option>
746
  </select></div>
747
+ <div className="set-field"><label className="set-label" htmlFor="set-external-databases">Resources</label>
748
+ <select id="set-external-databases" className="pg-select" value={databaseMode}
749
+ onChange={(event) => setDatabaseMode(event.currentTarget.value as "all" | "subset")}>
750
  <option value="all">All databases</option><option value="subset">Selected databases</option>
751
  </select></div>
752
+ {databaseMode === "subset" ? databaseChecks(selectedDatabases, setSelectedDatabases) : null}
753
+ <div className="set-field"><label className="set-label" htmlFor="set-external-expiry">Expiry</label>
754
+ <input id="set-external-expiry" className="set-input" type="datetime-local" value={expiresAt}
755
+ onChange={(event) => setExpiresAt(event.currentTarget.value)} />
 
756
  <p className="set-help">Leave blank for no expiry.</p></div>
757
+ <div className="set-actions"><button type="submit" className="set-primary" disabled={busy === "create"}>
758
+ {busy === "create" ? "Creating…" : "Create API key"}</button></div>
 
 
 
759
  </form>
760
+ ) : canMint === false ? (
761
+ <p className="set-help set-pane-intro">Creating API keys requires the Analyst module. Ask an administrator to grant it.</p>
762
+ ) : <p className="set-help">Loading API key settings…</p>}
763
+ </>
764
+ )}
765
+
766
+ <div className="set-field">
767
+ <label className="set-label" htmlFor="external-client-setup">{client.label} setup</label>
768
+ <textarea id="external-client-setup" className="set-input" value={setup} readOnly
769
+ rows={Math.min(12, setup.split("\n").length + 1)} />
770
+ <p className="set-help">{client.caveat}</p>
771
+ <div className="set-actions">
772
+ <button type="button" className="set-secondary" disabled={busy !== ""}
773
+ onClick={() => void copy(setup, `guide:${client.id}`)}>
774
+ {busy === `copy:guide:${client.id}` ? "Copying…" : copied === `guide:${client.id}` ? "Copied" : client.copyLabel}
775
+ </button>
776
+ </div>
777
+ </div>
778
+
779
+ <section className="set-card">
780
+ <h2 className="set-h4">SDK skill</h2>
781
+ <p className="set-help">Download or copy skill.md. It describes the API but contains no API key or other secret.</p>
782
+ <div className="set-actions">
783
+ <button type="button" className="set-primary" disabled={canMint !== true || busy === "skill-download"}
784
+ onClick={() => void downloadSkill()}>{busy === "skill-download" ? "Preparing…" : "Download skill.md"}</button>
785
+ <button type="button" className="set-secondary" disabled={canMint !== true || busy === "skill-copy"}
786
+ onClick={() => void copySkill()}>{busy === "skill-copy" ? "Copying…" : copied === "skill" ? "Copied" : "Copy skill.md"}</button>
787
+ </div>
788
+ </section>
789
+
790
+ {!readyToVerify ? (
791
+ <div className="set-actions">
792
+ <button type="button" className="set-primary" disabled={busy !== ""}
793
+ onClick={() => setReadyToVerify(true)}>Continue to verify</button>
794
+ </div>
795
+ ) : null}
796
+ </>
797
+ )}
798
+ </Step>
799
+
800
+ <Step number={4} title="Verify" state={!readyToVerify ? "waiting" : verifyResult?.state === "ok" ? "done" : "current"}
801
+ value={verifyResult?.state === "ok" ? connection === "mcp" ? "Sign-in verified" : "API key verified" : undefined}>
802
+ {!readyToVerify || !client ? <p className="set-help">Finish setup, then continue to verify.</p> : (
803
+ <>
804
+ {connection === "key" ? (
805
+ <>
806
+ {revealed ? <p className="set-help">Verify the API key just created or rotated.</p> : (
807
+ <div className="set-field">
808
+ <label className="set-label" htmlFor="external-verify-key">Saved API key</label>
809
+ <input id="external-verify-key" className="set-input" type="password" value={verifySecret}
810
+ autoComplete="off" spellCheck={false} disabled={busy !== ""}
811
+ aria-describedby="external-verify-key-help"
812
+ onChange={(event) => { setVerifySecret(event.currentTarget.value); setVerifyResult(null); }} />
813
+ <p id="external-verify-key-help" className="set-help">Loopable cannot show an existing key again. Rotating issues a new one. This field clears after the check.</p>
814
+ </div>
815
  )}
816
+ <p className="set-help">This checks the key with Loopable. Use the starter prompt in {client.label} to check its setup.</p>
817
+ <div className="set-actions">
818
+ <button type="button" className="set-primary" data-verify="key"
819
+ disabled={busy !== "" || !(revealed?.secret || verifySecret.trim())}
820
+ onClick={() => void verifyKey()}>{busy === "verify:key" ? "Verifying…" : "Verify API key"}</button>
821
+ </div>
822
+ </>
823
+ ) : (
824
+ <>
825
+ <p className="set-help">Check for a completed {client.label} sign-in with Loopable.</p>
826
+ <div className="set-actions">
827
+ <button type="button" className="set-primary" data-verify="mcp" disabled={busy !== ""}
828
+ onClick={() => void verifyMcp()}>{busy === "verify:mcp" ? "Checking…" : "Verify sign-in"}</button>
829
+ </div>
830
+ </>
831
+ )}
832
+ {verifyResult ? (
833
+ <p className="set-help" role="status" data-verify-result data-verify-state={verifyResult.state}
834
+ style={{ padding: 12, marginTop: 12, borderRadius: "var(--lp-r-md)",
835
+ color: verifyResult.state === "ok" ? "var(--lp-green-deep)" : "var(--lp-red-deep)",
836
+ background: verifyResult.state === "ok" ? "var(--lp-green-tint)" : "var(--lp-red-tint)" }}>
837
+ {verifyResult.message}
838
+ </p>
839
+ ) : null}
840
+ {connection === "mcp" ? connections.map((connection) => (
841
+ <div key={connection.id} style={{ marginTop: 16 }}>
842
+ <div className="pg-drill-row"><span className="pg-drill-key">{connection.label || "Unnamed AI app"}</span>
843
+ <span className="pg-drill-val">{connectionLabel(connection)}</span></div>
844
+ <div className="pg-drill-row"><span className="pg-drill-key">Last used</span>
845
+ <span className="pg-drill-val">{when(connection.last_used)}</span></div>
846
+ {connection.status === "connected" ? (
847
+ <div className="set-actions">
848
+ <button type="button" className="set-secondary kc-danger" disabled={busy !== ""}
849
+ onClick={() => void disconnect(connection)}>
850
+ {busy === `disconnect:${connection.client}` ? "Disconnecting…" : "Disconnect"}
851
+ </button>
852
+ </div>
853
+ ) : null}
854
+ </div>
855
+ )) : null}
856
+ </>
857
  )}
858
+ </Step>
859
+ </ol>
860
+
861
+ <section className="set-card">
862
+ <h2 className="set-h4">Safe starter prompt</h2>
863
+ <label className="set-label" htmlFor="external-starter-prompt">First message</label>
864
+ <textarea id="external-starter-prompt" className="set-input" value={SAFE_STARTER_PROMPT} readOnly rows={3}
865
+ aria-label="Safe starter prompt" />
866
+ <p className="set-help">This prompt contains no API key or other secret.</p>
867
+ <div className="set-actions"><button type="button" className="set-secondary" disabled={busy !== ""}
868
+ onClick={() => void copy(SAFE_STARTER_PROMPT, "starter-prompt")}>
869
+ {busy === "copy:starter-prompt" ? "Copying…" : copied === "starter-prompt" ? "Copied" : "Copy starter prompt"}
870
+ </button></div>
871
+ </section>
872
+
873
+ {connection !== "key" ? revealCard : null}
874
+
875
+ <div className="set-perm-sect"><h2 className="set-h4">API keys</h2></div>
876
+ {keys === null ? <p className="set-help" role="status">Loading API keys…</p>
877
+ : keys.length === 0 ? <p className="set-help">You have no API keys yet.</p> : (
878
+ <div aria-label="Active API keys">
879
+ {keys.map((key) => (
880
+ <section className="set-card" key={key.id}>
881
+ {editing === key.id && editDraft ? (
882
+ <form onSubmit={(event) => void saveEdit(event)}>
883
+ <h2 className="set-h4">Edit API key</h2>
884
+ <div className="set-field"><label className="set-label" htmlFor={`key-label-${key.id}`}>Label</label>
885
+ <input id={`key-label-${key.id}`} className="set-input" maxLength={80} value={editDraft.label}
886
+ onChange={(event) => setEditDraft({ ...editDraft, label: event.currentTarget.value })} /></div>
887
+ <div className="set-field"><label className="set-label" htmlFor={`key-access-${key.id}`}>Access</label>
888
+ <select id={`key-access-${key.id}`} className="pg-select" value={editDraft.access}
889
+ onChange={(event) => setEditDraft({ ...editDraft, access: event.currentTarget.value as Access })}>
890
+ <option value="read">Read only</option><option value="readwrite">Read and write</option>
891
+ </select></div>
892
+ <div className="set-field"><label className="set-label" htmlFor={`key-databases-${key.id}`}>Resources</label>
893
+ <select id={`key-databases-${key.id}`} className="pg-select" value={editDraft.databaseMode}
894
+ onChange={(event) => setEditDraft({ ...editDraft, databaseMode: event.currentTarget.value as "all" | "subset" })}>
895
+ <option value="all">All databases</option><option value="subset">Selected databases</option>
896
+ </select></div>
897
+ {editDraft.databaseMode === "subset"
898
+ ? databaseChecks(editDraft.databases, (databases) => setEditDraft({ ...editDraft, databases })) : null}
899
+ <div className="set-field"><label className="set-label" htmlFor={`key-expiry-${key.id}`}>Expiry</label>
900
+ <input id={`key-expiry-${key.id}`} className="set-input" type="datetime-local" value={editDraft.expiresAt}
901
+ onChange={(event) => setEditDraft({ ...editDraft, expiresAt: event.currentTarget.value })} />
902
+ <p className="set-help">Leave blank for no expiry.</p></div>
903
+ <div className="set-actions">
904
+ <button type="submit" className="set-primary" disabled={busy === `edit:${key.id}`}>
905
+ {busy === `edit:${key.id}` ? "Saving…" : "Save changes"}</button>
906
+ <button type="button" className="set-secondary" onClick={() => { setEditing(null); setEditDraft(null); }}>Cancel</button>
907
+ </div>
908
+ </form>
909
+ ) : (
910
+ <>
911
+ <h2 className="set-h4">{key.label}</h2>
912
+ <div className="pg-drill-row"><span className="pg-drill-key">Access</span>
913
+ <span className="pg-drill-val">{key.access === "read" ? "Read only" : "Read and write"}</span></div>
914
+ <div className="pg-drill-row"><span className="pg-drill-key">Resources</span>
915
+ <span className="pg-drill-val">{databaseLabels(key.databases)}</span></div>
916
+ <div className="pg-drill-row"><span className="pg-drill-key">Expiry</span>
917
+ <span className="pg-drill-val">{key.expires_at ? when(key.expires_at) : "No expiry"}</span></div>
918
+ <div className="pg-drill-row"><span className="pg-drill-key">Last used</span>
919
+ <span className="pg-drill-val">{when(key.last_used)}</span></div>
920
+ <div className="set-actions">
921
+ <button type="button" className="set-secondary" onClick={() => { setEditing(key.id); setEditDraft(draftFor(key)); }}>Edit</button>
922
+ <button type="button" className="set-secondary" disabled={busy === `rotate:${key.id}`}
923
+ onClick={() => void rotate(key)}>{busy === `rotate:${key.id}` ? "Rotating…" : "Rotate"}</button>
924
+ <button type="button" className="set-secondary kc-danger" disabled={busy === `revoke:${key.id}`}
925
+ onClick={() => void revoke(key)}>{busy === `revoke:${key.id}` ? "Revoking…" : "Revoke"}</button>
926
+ </div>
927
+ </>
928
+ )}
929
+ </section>
930
+ ))}
931
+ </div>
932
  )}
933
  </div>
934
  );
web/src/sheet/BindingEditor.tsx CHANGED
@@ -47,7 +47,7 @@ import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/O
47
  import type { Field, FilterTree, GridWorkspace, Measure, Row, SavedView } from "../customer-grid/types";
48
  import { choiceVocabulary, topicForScope, MULTI_VALUE_OPS } from "../customer-grid/types";
49
  import type { WindowSpec } from "../customer-grid/windows";
50
- import { normalizeWindow, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS,
51
  endingBounds, endingStepDefault, MAX_N, ANCHOR_VALUE_FREE } from "../customer-grid/windows";
52
  import type { EndingKind, EndingStep } from "../customer-grid/windows";
53
  // ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
@@ -61,9 +61,13 @@ import { useEscapeClose } from "../ui/useEscapeClose";
61
  import { previewCell, readWorkbook } from "./sheetApi";
62
  import DrillModal from "./DrillModal";
63
  import { formatRef, parseRef } from "./a1";
64
- import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, BINDING_ENDING_STEP, BINDING_PERIOD_STEP,
 
65
  VIEW_BINDING_TYPES, VIEW_BINDING_LIMIT_DEFAULT, VIEW_BINDING_LIMIT_MAX } from "./types";
66
- import type { BindingAggregate, BindingDragStep, BindingOnDrag, ViewBinding } from "./types";
 
 
 
67
  import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
68
  bindingRefSlots, filterValueLeaves, resolveFilterCell, updateFilterValueLeaf } from "./bindingRefs";
69
  import "../styles/wave57/binding-actions.css";
@@ -155,38 +159,32 @@ const scopeOf = (database: string): SurfaceScope | null => {
155
  // server compiler reads the pair, and two readings of `2026-08` under `quarter` (August, or Q3)
156
  // are a silent disagreement that no screen shows.
157
 
158
- export type PeriodUnit = "day" | "week" | "month" | "quarter" | "year";
159
-
160
- export interface PeriodBinding {
161
- unit: PeriodUnit;
162
- start: string;
163
- locked: boolean;
164
- ref?: string;
165
  frozen?: true;
166
  from?: string;
167
  to?: string;
168
  window?: WindowSpec;
169
- ending?: { kind: EndingKind; date?: string; n?: number; unit?: EndingStep };
170
- endingStep?: EndingStep;
171
- endingOffset?: number;
172
  }
173
 
174
- export const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [
175
- { unit: "day", label: "Day" },
176
- { unit: "week", label: "Week" },
177
- { unit: "month", label: "Month" },
178
- { unit: "quarter", label: "Quarter" },
179
- { unit: "year", label: "Year" },
180
- ];
 
 
 
 
 
 
181
 
182
  const MONTH_NAMES = [
183
  "January", "February", "March", "April", "May", "June",
184
  "July", "August", "September", "October", "November", "December",
185
  ];
186
 
187
- /** How many months one step of a unit covers. The only place that arithmetic is stated. */
188
- const MONTHS_PER_UNIT: Partial<Record<PeriodUnit, number>> = { month: 1, quarter: 3, year: 12 };
189
-
190
  /** The noun a sentence uses for one step. Sentence case, and no dash anywhere near it. */
191
  const UNIT_NOUN: Record<PeriodUnit, string> = {
192
  day: "day", week: "week", month: "month", quarter: "quarter", year: "year",
@@ -222,19 +220,6 @@ export function normalizePeriodStart(unit: PeriodUnit, ym: string): string {
222
  return joinYm(y, m);
223
  }
224
 
225
- /** Move a start by whole periods. Negative steps go back; this is also the drag rule's maths. */
226
- export function shiftPeriodStart(unit: PeriodUnit, ym: string, steps: number): string {
227
- if (unit === "day" || unit === "week") {
228
- const date = new Date(`${normalizePeriodStart(unit, ym)}T00:00:00Z`);
229
- if (!Number.isFinite(date.getTime())) return ym;
230
- date.setUTCDate(date.getUTCDate() + steps * (unit === "week" ? 7 : 1));
231
- return date.toISOString().slice(0, 10);
232
- }
233
- const { y, m } = splitYm(normalizePeriodStart(unit, ym));
234
- const total = y * 12 + (m - 1) + steps * MONTHS_PER_UNIT[unit]!;
235
- return joinYm(Math.floor(total / 12), (total % 12) + 1);
236
- }
237
-
238
  /** The inclusive day range a calendar period covers. Mirrors
239
  * `platform/modules/sheet.py::period_window`, whose `to` is the LAST DAY of the period. */
240
  export function periodRange(unit: PeriodUnit, ym: string): { from: string; to: string } {
@@ -245,7 +230,7 @@ export function periodRange(unit: PeriodUnit, ym: string): { from: string; to: s
245
  last.setUTCDate(last.getUTCDate() + (unit === "week" ? 6 : 0));
246
  return { from: start, to: last.toISOString().slice(0, 10) };
247
  }
248
- const last = new Date(`${shiftPeriodStart(unit, start, 1)}-01T00:00:00Z`);
249
  last.setUTCDate(last.getUTCDate() - 1);
250
  return { from: `${start}-01`, to: last.toISOString().slice(0, 10) };
251
  }
@@ -282,7 +267,10 @@ const todayYm = () => {
282
  export function migratePeriod(raw: unknown): PeriodBinding | null {
283
  if (!raw || typeof raw !== "object") return null;
284
  const p = raw as Record<string, unknown>;
285
- const ref = typeof p.ref === "string" && p.ref.trim() ? p.ref.trim() : "";
 
 
 
286
  // β›” C5 - A DECLARED WINDOW MUST VALIDATE AS THE SHARED WINDOW VOCABULARY. Letting an invalid
287
  // window fall through would misread it as the legacy ref-only dialect or invent a calendar month.
288
  if ("window" in p) {
@@ -296,24 +284,22 @@ export function migratePeriod(raw: unknown): PeriodBinding | null {
296
  ...(p.ending && typeof p.ending === "object" ? {
297
  ending: p.ending as PeriodBinding["ending"],
298
  endingStep: (p.endingStep ?? endingStepDefault(window.kind)) as EndingStep,
299
- endingOffset: Number(p.endingOffset ?? 0), locked: p.locked === true,
300
  ...(ref ? { ref } : {}),
301
  } : {}),
302
  };
303
  }
304
- const declared = PERIOD_UNITS.some((u) => u.unit === p.unit);
305
  if (!declared) {
306
  // The legacy shape. Nothing shifts by surprise: it reads back LOCKED.
307
  if (!ref) return null;
308
  return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref };
309
  }
310
- const unit = p.unit as PeriodUnit;
311
- const stored = typeof p.start === "string" ? p.start.trim() : "";
312
  // D-660: no window named, and no cell to take one from, so there is no period to read.
313
  const startPattern = unit === "day" || unit === "week" ? /^\d{4}-\d{2}-\d{2}$/ : /^\d{4}-\d{2}$/;
314
  if (!startPattern.test(stored) && !ref && p.frozen !== true) return null;
315
  const start = normalizePeriodStart(unit, stored || todayYm());
316
- const locked = p.locked === true;
317
  if (p.frozen === true) {
318
  return {
319
  unit, start, locked, frozen: true,
@@ -329,7 +315,14 @@ export function migratePeriod(raw: unknown): PeriodBinding | null {
329
  // TWO DIRECTIONAL SETTINGS, and C2 spells them `onDrag: {across: "period"|"none",
330
  // down: {field: key}|"none"}`. Defaults: across = period, down = none.
331
 
 
 
 
 
 
332
  export type DragAcross = "period" | "none";
 
 
333
 
334
  export interface OnDragBinding {
335
  across: DragAcross;
@@ -1847,7 +1840,7 @@ export default function BindingEditor({
1847
  <>
1848
  <label className="sheet-field">
1849
  <span>Lookback</span>
1850
- <WindowPicker window={windowSpec} onWindow={(next) => {
1851
  setWindowSpec(next); setEndingStep(endingStepDefault(next.kind));
1852
  setEndingOffset(0);
1853
  }} />
@@ -1921,7 +1914,7 @@ export default function BindingEditor({
1921
  setStart(normalizePeriodStart(next, start));
1922
  }}
1923
  >
1924
- {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
1925
  </select>
1926
  </label>
1927
 
@@ -2015,7 +2008,7 @@ export default function BindingEditor({
2015
  month-or-quarter already reach every period the This and Last buttons
2016
  could, so a second control for the same value was a second way to say one
2017
  thing. `normalizePeriodStart` still normalises all three selects, and
2018
- `shiftPeriodStart` stays exported for the drag arithmetic. */}
2019
 
2020
  {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
2021
  sentence under it says what each one costs when the cell is copied. */}
 
47
  import type { Field, FilterTree, GridWorkspace, Measure, Row, SavedView } from "../customer-grid/types";
48
  import { choiceVocabulary, topicForScope, MULTI_VALUE_OPS } from "../customer-grid/types";
49
  import type { WindowSpec } from "../customer-grid/windows";
50
+ import { normalizeWindow, WINDOW_KINDS, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS,
51
  endingBounds, endingStepDefault, MAX_N, ANCHOR_VALUE_FREE } from "../customer-grid/windows";
52
  import type { EndingKind, EndingStep } from "../customer-grid/windows";
53
  // ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
 
61
  import { previewCell, readWorkbook } from "./sheetApi";
62
  import DrillModal from "./DrillModal";
63
  import { formatRef, parseRef } from "./a1";
64
+ import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, bindingPeriod,
65
+ PERIOD_UNITS, BINDING_ENDING_STEP, BINDING_PERIOD_STEP,
66
  VIEW_BINDING_TYPES, VIEW_BINDING_LIMIT_DEFAULT, VIEW_BINDING_LIMIT_MAX } from "./types";
67
+ import type { BindingAggregate, BindingDragStep, BindingOnDrag, BindingPeriod, PeriodUnit,
68
+ ViewBinding, DragAcross as SharedDragAcross } from "./types";
69
+ // D-687: the drag arithmetic has ONE owner, and it is the file the drag path itself calls.
70
+ import { shiftPeriodStart } from "./sheetState";
71
  import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
72
  bindingRefSlots, filterValueLeaves, resolveFilterCell, updateFilterValueLeaf } from "./bindingRefs";
73
  import "../styles/wave57/binding-actions.css";
 
159
  // server compiler reads the pair, and two readings of `2026-08` under `quarter` (August, or Q3)
160
  // are a silent disagreement that no screen shows.
161
 
162
+ export interface PeriodBinding extends BindingPeriod {
 
 
 
 
 
 
163
  frozen?: true;
164
  from?: string;
165
  to?: string;
166
  window?: WindowSpec;
 
 
 
167
  }
168
 
169
+ // ⭐ D-687 - THE UNITS ARE `types.ts::PERIOD_UNITS` AND ARE NOT RE-TYPED HERE; ONLY THE WORDING IS
170
+ // LOCAL. The table is keyed `Record<PeriodUnit, ...>` so a unit ADDED to the shared tuple is a
171
+ // COMPILE ERROR here rather than a blank option, and the select is built by mapping the shared
172
+ // tuple, so a unit REMOVED there leaves this control without a second edit. Each entry is written
173
+ // out as an object literal because `verify_wiring.py:5641` reads three of them as literal text.
174
+ const PERIOD_UNIT_LABELS: Record<PeriodUnit, { unit: PeriodUnit; label: string }> = {
175
+ day: { unit: "day", label: "Day" },
176
+ week: { unit: "week", label: "Week" },
177
+ month: { unit: "month", label: "Month" },
178
+ quarter: { unit: "quarter", label: "Quarter" },
179
+ year: { unit: "year", label: "Year" },
180
+ };
181
+ const PERIOD_UNIT_OPTIONS = PERIOD_UNITS.map((unit) => PERIOD_UNIT_LABELS[unit]);
182
 
183
  const MONTH_NAMES = [
184
  "January", "February", "March", "April", "May", "June",
185
  "July", "August", "September", "October", "November", "December",
186
  ];
187
 
 
 
 
188
  /** The noun a sentence uses for one step. Sentence case, and no dash anywhere near it. */
189
  const UNIT_NOUN: Record<PeriodUnit, string> = {
190
  day: "day", week: "week", month: "month", quarter: "quarter", year: "year",
 
220
  return joinYm(y, m);
221
  }
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  /** The inclusive day range a calendar period covers. Mirrors
224
  * `platform/modules/sheet.py::period_window`, whose `to` is the LAST DAY of the period. */
225
  export function periodRange(unit: PeriodUnit, ym: string): { from: string; to: string } {
 
230
  last.setUTCDate(last.getUTCDate() + (unit === "week" ? 6 : 0));
231
  return { from: start, to: last.toISOString().slice(0, 10) };
232
  }
233
+ const last = new Date(`${shiftPeriodStart(start, unit, 1)}-01T00:00:00Z`);
234
  last.setUTCDate(last.getUTCDate() - 1);
235
  return { from: `${start}-01`, to: last.toISOString().slice(0, 10) };
236
  }
 
267
  export function migratePeriod(raw: unknown): PeriodBinding | null {
268
  if (!raw || typeof raw !== "object") return null;
269
  const p = raw as Record<string, unknown>;
270
+ // D-687: types.ts belongs to another lane this wave, so wrap its reader rather than widen it.
271
+ const shared = bindingPeriod({ period: p });
272
+ if (!shared) return null;
273
+ const ref = shared.ref ?? "";
274
  // β›” C5 - A DECLARED WINDOW MUST VALIDATE AS THE SHARED WINDOW VOCABULARY. Letting an invalid
275
  // window fall through would misread it as the legacy ref-only dialect or invent a calendar month.
276
  if ("window" in p) {
 
284
  ...(p.ending && typeof p.ending === "object" ? {
285
  ending: p.ending as PeriodBinding["ending"],
286
  endingStep: (p.endingStep ?? endingStepDefault(window.kind)) as EndingStep,
287
+ endingOffset: Number(p.endingOffset ?? 0), locked: shared.locked,
288
  ...(ref ? { ref } : {}),
289
  } : {}),
290
  };
291
  }
292
+ const declared = PERIOD_UNITS.some((unit) => unit === p.unit);
293
  if (!declared) {
294
  // The legacy shape. Nothing shifts by surprise: it reads back LOCKED.
295
  if (!ref) return null;
296
  return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref };
297
  }
298
+ const { unit, start: stored, locked } = shared;
 
299
  // D-660: no window named, and no cell to take one from, so there is no period to read.
300
  const startPattern = unit === "day" || unit === "week" ? /^\d{4}-\d{2}-\d{2}$/ : /^\d{4}-\d{2}$/;
301
  if (!startPattern.test(stored) && !ref && p.frozen !== true) return null;
302
  const start = normalizePeriodStart(unit, stored || todayYm());
 
303
  if (p.frozen === true) {
304
  return {
305
  unit, start, locked, frozen: true,
 
315
  // TWO DIRECTIONAL SETTINGS, and C2 spells them `onDrag: {across: "period"|"none",
316
  // down: {field: key}|"none"}`. Defaults: across = period, down = none.
317
 
318
+ // β›”β›” THIS UNION IS STATED HERE ON PURPOSE AND D-687 DOES NOT REVOKE IT. `verify_wiring.py:5782`
319
+ // reads this exact line as TEXT, because C2's wire vocabulary is what that leg was really for, and
320
+ // this is the file that documents the wire. D-687 is about a SECOND OPINION that can drift in
321
+ // silence, not about an absent declaration: the constant below makes any disagreement with
322
+ // `types.ts::DragAcross` stop compiling, which is the outcome D-687 exists to get.
323
  export type DragAcross = "period" | "none";
324
+ export const DRAG_ACROSS_LOCK_STEP: [DragAcross, SharedDragAcross] extends
325
+ [SharedDragAcross, DragAcross] ? true : never = true;
326
 
327
  export interface OnDragBinding {
328
  across: DragAcross;
 
1840
  <>
1841
  <label className="sheet-field">
1842
  <span>Lookback</span>
1843
+ <WindowPicker window={windowSpec} kinds={WINDOW_KINDS} onWindow={(next) => {
1844
  setWindowSpec(next); setEndingStep(endingStepDefault(next.kind));
1845
  setEndingOffset(0);
1846
  }} />
 
1914
  setStart(normalizePeriodStart(next, start));
1915
  }}
1916
  >
1917
+ {PERIOD_UNIT_OPTIONS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
1918
  </select>
1919
  </label>
1920
 
 
2008
  month-or-quarter already reach every period the This and Last buttons
2009
  could, so a second control for the same value was a second way to say one
2010
  thing. `normalizePeriodStart` still normalises all three selects, and
2011
+ `shiftPeriodStart` comes from the shared drag arithmetic. */}
2012
 
2013
  {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
2014
  sentence under it says what each one costs when the cell is copied. */}
web/src/sheet/SheetGrid.tsx CHANGED
@@ -1104,26 +1104,54 @@ export default function SheetGrid({
1104
  // Keep the HEADER_HEIGHT and ROW_MARKER_WIDTH JSX uses byte-for-byte: verify_api.py 6582/8237
1105
  // and verify_grid_ux.py 7728 pin those expressions, including the band's three-line block.
1106
  const headingsVisible = tab.view?.headings !== false;
 
1107
  /** Stored as a percent; canvas dimensions use this factor without a CSS transform. */
1108
  const zoom = Math.max(10, Math.min(400, Math.round(tab.view?.zoom ?? 100))) / 100;
1109
  const HEADER_HEIGHT = headingsVisible ? Math.round(SHEET_HEADER_HEIGHT * zoom) : 0;
1110
  const ROW_MARKER_WIDTH = headingsVisible ? Math.round(SHEET_ROW_MARKER_WIDTH * zoom) : 0;
1111
  // Copy the shared theme when hiding gridlines: the Data module uses lightTheme too.
1112
  const gridTheme = useMemo(() => {
1113
- const base = tab.view?.gridlines === false
1114
  ? { ...lightTheme, borderColor: "transparent", horizontalBorderColor: "transparent" }
1115
  : lightTheme;
1116
  // Ten points is the document's default, not an approximation copied from glide's theme.
1117
  // Both fonts scale together: glide restores the cell font before drawing headers.
1118
  const pixels = Math.round(fontPx(DEFAULT_FONT_PT) * zoom);
1119
  return { ...base, baseFontStyle: `${pixels}px`, headerFontStyle: `600 ${pixels}px` };
1120
- }, [tab.view?.gridlines, zoom]);
 
 
 
 
 
 
 
 
 
 
 
1121
  const [selection, setSelection] = useState<GridSelection | undefined>(undefined);
1122
  /** The live value used to floor glide's empty Escape payload without adding selection state. */
1123
  const selectionRef = useRef<GridSelection | undefined>(undefined);
1124
  /** Pointer and keyboard provenance for selection callbacks emitted by glide itself. */
1125
  const pointerSelectingRef = useRef(false);
1126
  const keyboardSelectingRef = useRef(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1127
  /** Workbook and tab identity, never workbook object identity, owns the one opening selection. */
1128
  const openedSelectionRef = useRef("");
1129
  /**
@@ -1915,14 +1943,20 @@ export default function SheetGrid({
1915
  // Nothing about a frozen cell is a special case anywhere else in this file.
1916
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1917
  /**
1918
- * Is the selection's anchor inside the frozen band?
 
 
 
 
 
 
 
1919
  *
1920
- * ⚠ THE `bandRows` CLAUSE IS NOT DECORATION. Unfreezing while a frozen cell is selected
1921
- * leaves a NEGATIVE row in a state with no band to hold it, and without this the main grid
1922
- * would be handed `undefined` for its selection until somebody clicked again: a sheet that
1923
- * quietly stops showing what is selected, for one act, with nothing on screen to explain it.
1924
  */
1925
- const inBand = bandRows > 0 && (selection?.current?.cell[1] ?? 0) < 0;
 
1926
  const headerProjectionBounds = useMemo(() => ({
1927
  columns: visCols.length,
1928
  minRow: -bandRows,
@@ -1931,7 +1965,7 @@ export default function SheetGrid({
1931
  const mainSelection = inBand ? undefined : selection;
1932
  const frozenSelection = useMemo<GridSelection | undefined>(() => {
1933
  if (!selection) return undefined;
1934
- const current = inBand ? selection?.current : undefined;
1935
  return {
1936
  // C6: the band is a projection of the document selection, not a second selection. Columns
1937
  // already share view coordinates; row axes shift from negative document-view coordinates
@@ -1946,7 +1980,7 @@ export default function SheetGrid({
1946
  rangeStack: [],
1947
  } : undefined,
1948
  };
1949
- }, [bandRows, inBand, selection]);
1950
  useEffect(() => {
1951
  // Glide damages only the newly focused header when `current.cell` moves. Our header paint is
1952
  // derived from the whole document range/axis, so both the old and new projected sets must be
@@ -3345,6 +3379,9 @@ export default function SheetGrid({
3345
  ) => {
3346
  const prior = selectionRef.current?.current?.cell;
3347
  const anchor = extend ? (axis === "column" ? prior?.[0] : prior?.[1]) ?? index : index;
 
 
 
3348
  const active: Item = axis === "column"
3349
  ? [anchor, prior?.[1] ?? -bandRows]
3350
  : [prior?.[0] ?? 0, anchor];
@@ -3654,6 +3691,30 @@ export default function SheetGrid({
3654
  });
3655
  }, [addrAt, cells, fromBand, tab.id]);
3656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3657
  /**
3658
  * ⭐⭐ Ctrl+1 β€” CONTRACT C1's "THE SAME IMPLEMENTATION, NOT TWO COPIES OF IT", TAKEN LITERALLY.
3659
  *
@@ -5027,6 +5088,11 @@ export default function SheetGrid({
5027
  [hideBands, onColumnWidth, realCol, zoom],
5028
  );
5029
  const onHeaderClicked = useCallback((colIndex: number, args: { shiftKey: boolean }) => {
 
 
 
 
 
5030
  selectDocumentAxis("column", colIndex, args.shiftKey, false);
5031
  }, [selectDocumentAxis]);
5032
  const onHeaderContextMenu = useCallback(
@@ -5626,10 +5692,15 @@ export default function SheetGrid({
5626
 
5627
  ctx.save();
5628
 
5629
- // 1. THE BACKGROUND, FIRST AND INSET BY A PIXEL so the grid's own hairlines survive.
 
5630
  if (style.fill) {
5631
  ctx.fillStyle = tokenColour(style.fill, "#ffffff");
5632
- ctx.fillRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1);
 
 
 
 
5633
  }
5634
 
5635
  // 1b. THE DATA BAR, AFTER THE BACKGROUND AND BEFORE THE TEXT CLIP, which is the whole of the
@@ -5672,8 +5743,13 @@ export default function SheetGrid({
5672
  // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's
5673
  // territory for a line that was never wrong, only no longer load bearing.
5674
  return true;
 
 
 
 
5675
  }, [addrAt, blocksSpill, cellValueGetter, cells, columns, copyMarquee, formulaPointCells, formulaRefCells,
5676
- frozenCols, pasteHighlight, queueSpillPaint, realCol, realRow, rules, spillWidths, tab.name, zoom]);
 
5677
 
5678
  /**
5679
  * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not
@@ -5956,7 +6032,32 @@ export default function SheetGrid({
5956
  overlayCommit.current = { dir, at: Date.now(), from: [from[0], from[1]] };
5957
  if (typing) finishOverlayBoundaryCommit(dir, from);
5958
  }}
5959
- onPointerDownCapture={() => { pointerSelectingRef.current = true; }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5960
  onPointerUpCapture={() => {
5961
  queueMicrotask(() => { pointerSelectingRef.current = false; });
5962
  }}
@@ -5979,6 +6080,12 @@ export default function SheetGrid({
5979
  gives every child `flex: 1 1 auto`, so the stylesheet pins it to `flex: 0 0 auto` at a
5980
  selector specific enough to win, and the height is the band's own rows plus the one
5981
  header row it carries for both grids.
 
 
 
 
 
 
5982
  ══════════════════════════════════════════════════════════════════════════ */}
5983
  {bandRows > 0 && (
5984
  <div
@@ -6061,7 +6168,7 @@ export default function SheetGrid({
6061
  if (followCellLink(clicked)) return;
6062
  setAnchor(args.bounds);
6063
  }}
6064
- onItemHovered={(args: GridMouseEventArgs) => onNoteHover(args, true)}
6065
  onCellContextMenu={(item: Item, args) => {
6066
  args.preventDefault();
6067
  setAnchor(null);
@@ -6227,7 +6334,7 @@ export default function SheetGrid({
6227
  // ⭐ W54-T14 / LANE B β€” the note bubble's own gesture. Hover is read off the SAME
6228
  // callback for both grids, told which one is asking, so a note on a frozen row opens
6229
  // its bubble at the row a person is actually pointing at.
6230
- onItemHovered={(args: GridMouseEventArgs) => onNoteHover(args, false)}
6231
  // ⭐ AND THE COLUMN HEADER'S OWN CLICK, which the library offers directly. glide has
6232
  // already written a `columns` selection by the time this runs, for the same reason and
6233
  // with the same problem; this replaces it with the rectangle the acts read.
@@ -6275,7 +6382,7 @@ export default function SheetGrid({
6275
  <div key={`${header.row}:${header.top}`} className="sheet-active-row-header"
6276
  data-row={header.label} aria-hidden="true"
6277
  style={{ left: header.left, top: header.top, width: header.width, height: header.height,
6278
- fontSize: Math.round(fontPx(DEFAULT_FONT_PT) * zoom) }}>
6279
  {header.label}
6280
  </div>
6281
  ))}
 
1104
  // Keep the HEADER_HEIGHT and ROW_MARKER_WIDTH JSX uses byte-for-byte: verify_api.py 6582/8237
1105
  // and verify_grid_ux.py 7728 pin those expressions, including the band's three-line block.
1106
  const headingsVisible = tab.view?.headings !== false;
1107
+ const gridlinesVisible = tab.view?.gridlines !== false;
1108
  /** Stored as a percent; canvas dimensions use this factor without a CSS transform. */
1109
  const zoom = Math.max(10, Math.min(400, Math.round(tab.view?.zoom ?? 100))) / 100;
1110
  const HEADER_HEIGHT = headingsVisible ? Math.round(SHEET_HEADER_HEIGHT * zoom) : 0;
1111
  const ROW_MARKER_WIDTH = headingsVisible ? Math.round(SHEET_ROW_MARKER_WIDTH * zoom) : 0;
1112
  // Copy the shared theme when hiding gridlines: the Data module uses lightTheme too.
1113
  const gridTheme = useMemo(() => {
1114
+ const base = !gridlinesVisible
1115
  ? { ...lightTheme, borderColor: "transparent", horizontalBorderColor: "transparent" }
1116
  : lightTheme;
1117
  // Ten points is the document's default, not an approximation copied from glide's theme.
1118
  // Both fonts scale together: glide restores the cell font before drawing headers.
1119
  const pixels = Math.round(fontPx(DEFAULT_FONT_PT) * zoom);
1120
  return { ...base, baseFontStyle: `${pixels}px`, headerFontStyle: `600 ${pixels}px` };
1121
+ }, [gridlinesVisible, zoom]);
1122
+ /**
1123
+ * β›”β›” S64-T16 / owner instruction 9 - THE ROW NUMBER MUST NOT RESIZE WHEN ITS ROW IS PICKED.
1124
+ * `.sheet-active-row-header` REDRAWS the row marker over glide's own canvas marker, so the two
1125
+ * have to agree on face, weight AND size or selecting a row visibly grows its number. Glide
1126
+ * draws a marker with `theme.markerFontStyle`, whose library default is `9px`
1127
+ * (`glide-data-grid/common/styles.js`), and `gridTheme` above deliberately does not override it:
1128
+ * unlike cell and header text the marker is therefore NOT scaled by `zoom`. Read the value back
1129
+ * out of the theme rather than restating `9` at the overlay, so a later wave that does set
1130
+ * `markerFontStyle` moves both halves in one edit instead of re-opening this defect.
1131
+ */
1132
+ const markerFontPx = Number.parseFloat(gridTheme.markerFontStyle ?? "9px") || 9;
1133
  const [selection, setSelection] = useState<GridSelection | undefined>(undefined);
1134
  /** The live value used to floor glide's empty Escape payload without adding selection state. */
1135
  const selectionRef = useRef<GridSelection | undefined>(undefined);
1136
  /** Pointer and keyboard provenance for selection callbacks emitted by glide itself. */
1137
  const pointerSelectingRef = useRef(false);
1138
  const keyboardSelectingRef = useRef(false);
1139
+ /**
1140
+ * S64-T23 / ruling R10: a header drag is a range of the one axis selection.
1141
+ * These refs track the gesture; there is no second selection model.
1142
+ * The frozen band is covered because `axisBand` already starts at `-bandRows`.
1143
+ */
1144
+ /**
1145
+ * S64-T23: the column header the pointer is over, with the rectangle it was reported at.
1146
+ * THE RECTANGLE IS NOT DECORATION. Glide skips `onItemHovered` entirely when the pointer has
1147
+ * not changed what it is over (`mouseEventArgsAreEqual`), so this ref is NOT cleared by every
1148
+ * press. The press re-checks that it actually landed inside this rectangle, which is what stops
1149
+ * a stale header from opening a drag on a cell.
1150
+ */
1151
+ const headerHoverColRef = useRef<{ col: number; rect: Rectangle } | null>(null);
1152
+ /** S64-T23: the live header drag. `anchor` is the column pressed, `last` the column the
1153
+ * pointer is over, `moved` whether the drag ever left the anchor column. */
1154
+ const headerDragRef = useRef<{ anchor: number; last: number; moved: boolean } | null>(null);
1155
  /** Workbook and tab identity, never workbook object identity, owns the one opening selection. */
1156
  const openedSelectionRef = useRef("");
1157
  /**
 
1943
  // Nothing about a frozen cell is a special case anywhere else in this file.
1944
  // ═══════════════════════════════════════════════════════════════════════════════════════════
1945
  /**
1946
+ * TWO QUESTIONS, NOT ONE (S64-T22). `bandHoldsActive` asks whether the active cell is in
1947
+ * the frozen band, which is what decides where the RING is drawn and who takes focus.
1948
+ * `inBand` asks the narrower question the pinned `mainSelection` line below consumes: may the
1949
+ * BODY be shown nothing at all? For a whole-COLUMN selection the answer is no, because that
1950
+ * selection belongs to BOTH panes: measured 2026-09-21, Ctrl+Space on a frozen cell selected
1951
+ * the whole column in the model, tinted the header and the band, and left the body white.
1952
+ * A whole-ROW selection anchored in the band is NOT an exception and must keep today's
1953
+ * behaviour, because that row IS the band and the body has none of it to show.
1954
  *
1955
+ * THE `bandRows` CLAUSE IS NOT DECORATION, and it is kept for its original reason: unfreezing
1956
+ * while a frozen cell is selected leaves a NEGATIVE row in a state with no band to hold it.
 
 
1957
  */
1958
+ const bandHoldsActive = bandRows > 0 && (selection?.current?.cell[1] ?? 0) < 0;
1959
+ const inBand = bandHoldsActive && (selection?.columns.length ?? 0) === 0;
1960
  const headerProjectionBounds = useMemo(() => ({
1961
  columns: visCols.length,
1962
  minRow: -bandRows,
 
1965
  const mainSelection = inBand ? undefined : selection;
1966
  const frozenSelection = useMemo<GridSelection | undefined>(() => {
1967
  if (!selection) return undefined;
1968
+ const current = bandHoldsActive ? selection?.current : undefined;
1969
  return {
1970
  // C6: the band is a projection of the document selection, not a second selection. Columns
1971
  // already share view coordinates; row axes shift from negative document-view coordinates
 
1980
  rangeStack: [],
1981
  } : undefined,
1982
  };
1983
+ }, [bandHoldsActive, bandRows, selection]);
1984
  useEffect(() => {
1985
  // Glide damages only the newly focused header when `current.cell` moves. Our header paint is
1986
  // derived from the whole document range/axis, so both the old and new projected sets must be
 
3379
  ) => {
3380
  const prior = selectionRef.current?.current?.cell;
3381
  const anchor = extend ? (axis === "column" ? prior?.[0] : prior?.[1]) ?? index : index;
3382
+ // The active cell deliberately stays where the gesture put it: S63-T25's browser leg
3383
+ // asserts focus stays in the band after Ctrl+Space from a frozen cell. The body is made
3384
+ // to paint by `inBand` above instead.
3385
  const active: Item = axis === "column"
3386
  ? [anchor, prior?.[1] ?? -bandRows]
3387
  : [prior?.[0] ?? 0, anchor];
 
3691
  });
3692
  }, [addrAt, cells, fromBand, tab.id]);
3693
 
3694
+ const onGridItemHovered = useCallback((args: GridMouseEventArgs, band: boolean) => {
3695
+ onNoteHover(args, band);
3696
+ // β›”β›” ONLY THE CANVAS THAT OWNS THE COLUMN HEADER MAY SPEAK FOR IT, and this line is the
3697
+ // whole of S64-T23's first failed run. BOTH DataEditors report the SAME pointer: with rows
3698
+ // frozen the band draws the header (`headerHeight={bandRows > 0 ? 0 : HEADER_HEIGHT}`) and
3699
+ // the body draws none, so the body answers the identical position as `out-of-bounds`
3700
+ // immediately after the band answered `header`. Measured 2026-09-21 from the page console:
3701
+ // `hover header 2` from the band, then `hover out-of-bounds 2` from the body, and the second
3702
+ // one cleared the column the first had just recorded, so no header press ever saw one.
3703
+ if (band !== (bandRows > 0)) return;
3704
+ const col = args.location[0];
3705
+ if (args.kind !== "header" || col < 0) {
3706
+ headerHoverColRef.current = null;
3707
+ return;
3708
+ }
3709
+ headerHoverColRef.current = { col, rect: args.bounds };
3710
+ const drag = headerDragRef.current;
3711
+ // No button held means this is an ordinary hover, not a drag in progress.
3712
+ if (args.buttons === 0 || !drag || col === drag.last) return;
3713
+ drag.last = col;
3714
+ drag.moved = true;
3715
+ selectDocumentAxis("column", col, true, false);
3716
+ }, [bandRows, onNoteHover, selectDocumentAxis]);
3717
+
3718
  /**
3719
  * ⭐⭐ Ctrl+1 β€” CONTRACT C1's "THE SAME IMPLEMENTATION, NOT TWO COPIES OF IT", TAKEN LITERALLY.
3720
  *
 
5088
  [hideBands, onColumnWidth, realCol, zoom],
5089
  );
5090
  const onHeaderClicked = useCallback((colIndex: number, args: { shiftKey: boolean }) => {
5091
+ // S64-T23: a click fires on RELEASE. When the pointer travelled across other headers the drag
5092
+ // has already set the range, and re-running the click would collapse it to one column.
5093
+ const drag = headerDragRef.current;
5094
+ headerDragRef.current = null;
5095
+ if (drag?.moved) return;
5096
  selectDocumentAxis("column", colIndex, args.shiftKey, false);
5097
  }, [selectDocumentAxis]);
5098
  const onHeaderContextMenu = useCallback(
 
5692
 
5693
  ctx.save();
5694
 
5695
+ // 1. S64-T18 / owner instruction 9: inset the fill so visible gridlines survive.
5696
+ // With gridlines hidden, that inset cuts between adjacent fills; paint the exact cell rect.
5697
  if (style.fill) {
5698
  ctx.fillStyle = tokenColour(style.fill, "#ffffff");
5699
+ if (gridlinesVisible) {
5700
+ ctx.fillRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1);
5701
+ } else {
5702
+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
5703
+ }
5704
  }
5705
 
5706
  // 1b. THE DATA BAR, AFTER THE BACKGROUND AND BEFORE THE TEXT CLIP, which is the whole of the
 
5743
  // leg reads it as exactly that. Deleting it as dead reds a gate in another ticket's
5744
  // territory for a line that was never wrong, only no longer load bearing.
5745
  return true;
5746
+ // β›” `gridlinesVisible` IS LAST ON PURPOSE, NOT BY SLOPPINESS. `verify_grid_ux.py` 13468's
5747
+ // W62-T02 claim matches `frozenCols, pasteHighlight` as ADJACENT TEXT, so putting this
5748
+ // entry in alphabetical order between them reds a leg that owns the spill paint. React
5749
+ // does not care what order a dependency array is in; that gate does.
5750
  }, [addrAt, blocksSpill, cellValueGetter, cells, columns, copyMarquee, formulaPointCells, formulaRefCells,
5751
+ frozenCols, pasteHighlight, queueSpillPaint, realCol, realRow, rules, spillWidths, tab.name, zoom,
5752
+ gridlinesVisible]);
5753
 
5754
  /**
5755
  * ⭐ THE BAND'S PAINT: the SAME callback, told which row it is looking at. `fromBand` is not
 
6032
  overlayCommit.current = { dir, at: Date.now(), from: [from[0], from[1]] };
6033
  if (typing) finishOverlayBoundaryCommit(dir, from);
6034
  }}
6035
+ onPointerDownCapture={(event) => {
6036
+ pointerSelectingRef.current = true;
6037
+ // S64-T23 / R10: a press on a column header starts a whole-column drag. The anchor is
6038
+ // set HERE rather than on release, because `onHeaderClicked` only fires on mouse up and
6039
+ // an extend needs an anchor before the pointer has moved anywhere.
6040
+ // S64-T23: the press must land inside the header rectangle the hover reported, or the
6041
+ // remembered column is stale and this is not a header press at all.
6042
+ const hovered = headerHoverColRef.current;
6043
+ const inside = hovered !== undefined && hovered !== null
6044
+ && event.clientX >= hovered.rect.x
6045
+ && event.clientX < hovered.rect.x + hovered.rect.width
6046
+ && event.clientY >= hovered.rect.y
6047
+ && event.clientY < hovered.rect.y + hovered.rect.height;
6048
+ const col = inside && hovered ? hovered.col : null;
6049
+ if (col === null || event.button !== 0) {
6050
+ headerDragRef.current = null;
6051
+ return;
6052
+ }
6053
+ // A Shift press keeps the held anchor, which is what a Shift header click means today.
6054
+ if (!event.shiftKey) selectDocumentAxis("column", col, false, false);
6055
+ headerDragRef.current = {
6056
+ anchor: event.shiftKey ? selectionRef.current?.current?.cell[0] ?? col : col,
6057
+ last: col,
6058
+ moved: false,
6059
+ };
6060
+ }}
6061
  onPointerUpCapture={() => {
6062
  queueMicrotask(() => { pointerSelectingRef.current = false; });
6063
  }}
 
6080
  gives every child `flex: 1 1 auto`, so the stylesheet pins it to `flex: 0 0 auto` at a
6081
  selector specific enough to win, and the height is the band's own rows plus the one
6082
  header row it carries for both grids.
6083
+
6084
+ β›” S64-T18: `data-gridlines` below stays the LONG form, `tab.view?.gridlines
6085
+ !== false`, even though the component now derives `gridlinesVisible` once.
6086
+ `verify_grid_ux.py` 12805 and its `row-divider-ignores-gridlines` negative
6087
+ control match that attribute AS TEXT, so shortening it reds a leg belonging
6088
+ to the band divider rather than to anything this ticket changed.
6089
  ══════════════════════════════════════════════════════════════════════════ */}
6090
  {bandRows > 0 && (
6091
  <div
 
6168
  if (followCellLink(clicked)) return;
6169
  setAnchor(args.bounds);
6170
  }}
6171
+ onItemHovered={(args: GridMouseEventArgs) => onGridItemHovered(args, true)}
6172
  onCellContextMenu={(item: Item, args) => {
6173
  args.preventDefault();
6174
  setAnchor(null);
 
6334
  // ⭐ W54-T14 / LANE B β€” the note bubble's own gesture. Hover is read off the SAME
6335
  // callback for both grids, told which one is asking, so a note on a frozen row opens
6336
  // its bubble at the row a person is actually pointing at.
6337
+ onItemHovered={(args: GridMouseEventArgs) => onGridItemHovered(args, false)}
6338
  // ⭐ AND THE COLUMN HEADER'S OWN CLICK, which the library offers directly. glide has
6339
  // already written a `columns` selection by the time this runs, for the same reason and
6340
  // with the same problem; this replaces it with the rectangle the acts read.
 
6382
  <div key={`${header.row}:${header.top}`} className="sheet-active-row-header"
6383
  data-row={header.label} aria-hidden="true"
6384
  style={{ left: header.left, top: header.top, width: header.width, height: header.height,
6385
+ fontSize: markerFontPx }}>
6386
  {header.label}
6387
  </div>
6388
  ))}
web/src/sheet/SheetPage.tsx CHANGED
@@ -353,6 +353,35 @@ const tabRevOf = (tab: SheetTab, book: Workbook): number => {
353
  return typeof own === "number" ? Math.max(own, book.rev) : book.rev;
354
  };
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  export default function SheetPage() {
357
  const [book, setBook] = useState<Workbook | null>(null);
358
  /** Read once for the mount decision; later opens write through `prepareWorkbookOpen`. */
@@ -522,6 +551,8 @@ export default function SheetPage() {
522
  const tabRouteRef = useRef<"unknown" | "yes" | "no">("unknown");
523
  /** Tabs holding cells in the adopted tree. Keyed `workbookId:tabId`, so books cannot collide. */
524
  const tabLoadedRef = useRef<Set<string>>(new Set());
 
 
525
  /** The pending debounce, or null when nothing is waiting. */
526
  const saveTimerRef = useRef<number | null>(null);
527
  /**
@@ -839,8 +870,22 @@ export default function SheetPage() {
839
  return () => window.removeEventListener(ITEM_DELETED_EVENT, drop);
840
  }, []);
841
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
842
  const ensureTabs = useCallback(async (
843
- workbookId: string, keys: string[], quiet = false,
844
  ): Promise<boolean> => {
845
  const wanted = keys.filter((k) => k && !tabLoadedRef.current.has(tabKeyOf(workbookId, k)));
846
  if (wanted.length === 0) return true;
@@ -848,15 +893,18 @@ export default function SheetPage() {
848
  let served = true;
849
  for (const key of wanted) {
850
  const got = await readTab(workbookId, key);
 
851
  if (!got.ok && discardMissingWorkbook(workbookId, got)) return false;
852
  if (!got.ok && got.status === 404 && got.code === "tab_missing") {
853
  const live = bookRef.current;
854
  if (live?.id === workbookId) {
855
  applyLocal({ ...live, sheets: live.sheets.filter((tab) => tab.id !== key) });
856
- if (tabIdRef.current === key) setTabId("");
 
 
 
 
857
  }
858
- setNotice("");
859
- restoreMissingOpen(workbookId, key);
860
  return false;
861
  }
862
  if (got.ok && got.value) {
@@ -868,8 +916,8 @@ export default function SheetPage() {
868
  if (!absent || tabRouteRef.current === "yes") {
869
  // β›” A TAB THAT WILL NOT LOAD IS NOT AN EMPTY TAB. Painting it as one reads exactly
870
  // like the cells having been deleted, so the reason is said instead.
871
- if (!quiet) setNotice(got.ok ? "That sheet could not be read, so it is not shown."
872
- : got.message);
873
  return false;
874
  }
875
  tabRouteRef.current = "no";
@@ -879,9 +927,10 @@ export default function SheetPage() {
879
  if (served) return true;
880
  }
881
  const fresh = await readWorkbook(workbookId);
 
882
  if (!fresh.ok) {
883
  if (discardMissingWorkbook(workbookId, fresh)) return false;
884
- if (!quiet) setNotice(fresh.message);
885
  return false;
886
  }
887
  const live = bookRef.current;
@@ -907,18 +956,20 @@ export default function SheetPage() {
907
  setUnreadableAddressTab("");
908
  setTabId(id);
909
  const current = bookRef.current;
910
- if (current) void ensureTabs(current.id, [id]);
 
 
 
911
  }, [ensureTabs, rememberOpenWorkbook]);
912
 
913
  // Wave 60 base kit: a hidden or very hidden sheet has no tab, so it is never the open one. When
914
  // the open tab is hidden (by the View ribbon, an undo, or a workbook that opened on one), the
915
  // page opens the first visible tab through the tab bar's own door, which fetches its cells.
 
916
  useEffect(() => {
917
  if (!book) return;
918
- const open = book.sheets.find((t) => t.id === tabId) ?? book.sheets[0];
919
- if (!open || (open.visibility ?? "visible") === "visible") return;
920
- const next = book.sheets.find((t) => (t.visibility ?? "visible") === "visible");
921
- if (next) openTab(next.id);
922
  }, [book, openTab, tabId]);
923
 
924
  // Read the whole hash, as the shell does: workbook changes keep the same route key.
 
353
  return typeof own === "number" ? Math.max(own, book.rev) : book.rev;
354
  };
355
 
356
+ /**
357
+ * Is a tab-navigation response still the one the user is waiting for?
358
+ *
359
+ * `requested === undefined` is a caller that does not navigate (the save drain, a chart load):
360
+ * it is never stale, because nothing about it is about which tab is on screen.
361
+ */
362
+ export function tabNavVerdict(requested: number | undefined, current: number): "apply" | "discard" {
363
+ if (requested === undefined) return "apply";
364
+ return requested === current ? "apply" : "discard";
365
+ }
366
+
367
+ /**
368
+ * Which tab the hidden-tab effect should move to, or null for "leave the page alone".
369
+ *
370
+ * Returns null when `tabId` names a tab this snapshot does not carry: that pair is a STALE
371
+ * COMPUTATION, not a hidden tab, and redirecting on it is how a late response moved the user off
372
+ * the sheet they had just clicked.
373
+ */
374
+ export function hiddenTabRedirect(
375
+ sheets: readonly { id: string; visibility?: string }[], tabId: string,
376
+ ): string | null {
377
+ const visible = (t: { visibility?: string }) => (t.visibility ?? "visible") === "visible";
378
+ const open = tabId ? sheets.find((t) => t.id === tabId) : sheets[0];
379
+ if (!open) return null; // stale pair, or an empty workbook: change nothing
380
+ if (visible(open)) return null; // the open tab is fine
381
+ const next = sheets.find(visible);
382
+ return next && next.id !== tabId ? next.id : null;
383
+ }
384
+
385
  export default function SheetPage() {
386
  const [book, setBook] = useState<Workbook | null>(null);
387
  /** Read once for the mount decision; later opens write through `prepareWorkbookOpen`. */
 
551
  const tabRouteRef = useRef<"unknown" | "yes" | "no">("unknown");
552
  /** Tabs holding cells in the adopted tree. Keyed `workbookId:tabId`, so books cannot collide. */
553
  const tabLoadedRef = useRef<Set<string>>(new Set());
554
+ /** The latest tab navigation; an older response must not move the page or paint its notice. */
555
+ const tabNavGenRef = useRef(0);
556
  /** The pending debounce, or null when nothing is waiting. */
557
  const saveTimerRef = useRef<number | null>(null);
558
  /**
 
870
  return () => window.removeEventListener(ITEM_DELETED_EVENT, drop);
871
  }, []);
872
 
873
+ /**
874
+ * Only the current tab navigation may restore a missing tab or write its refusal notice.
875
+ * Read the generation AFTER each await: another click may have won while the request was away.
876
+ *
877
+ * β›” THE CELL LOADS ARE NOT NAVIGATION. Keep merging by tab id, settling the route and marking
878
+ * loaded tabs even when the navigation is stale. `sendWholeWorkbook` awaits this same fence:
879
+ * its PUT writes `sheets` verbatim, so skipping cells behind the navigation guard could send
880
+ * the empty maps from `?tabs=meta` and silently delete unvisited sheets' data. Callers without
881
+ * a navigation generation keep their existing behavior and the same loaded/not-loaded answer.
882
+ *
883
+ * Pass a predicate rather than a generation number: the W61-T22 runner executes this function
884
+ * under `with (env)` against a fixture it owns, so a new free identifier here causes a
885
+ * ReferenceError in that gate rather than a compile error here.
886
+ */
887
  const ensureTabs = useCallback(async (
888
+ workbookId: string, keys: string[], quiet = false, stillCurrent?: () => boolean,
889
  ): Promise<boolean> => {
890
  const wanted = keys.filter((k) => k && !tabLoadedRef.current.has(tabKeyOf(workbookId, k)));
891
  if (wanted.length === 0) return true;
 
893
  let served = true;
894
  for (const key of wanted) {
895
  const got = await readTab(workbookId, key);
896
+ const still = stillCurrent === undefined || stillCurrent() ? "apply" : "discard";
897
  if (!got.ok && discardMissingWorkbook(workbookId, got)) return false;
898
  if (!got.ok && got.status === 404 && got.code === "tab_missing") {
899
  const live = bookRef.current;
900
  if (live?.id === workbookId) {
901
  applyLocal({ ...live, sheets: live.sheets.filter((tab) => tab.id !== key) });
902
+ if (still === "apply" && tabIdRef.current === key) setTabId("");
903
+ }
904
+ if (still === "apply") {
905
+ setNotice("");
906
+ restoreMissingOpen(workbookId, key);
907
  }
 
 
908
  return false;
909
  }
910
  if (got.ok && got.value) {
 
916
  if (!absent || tabRouteRef.current === "yes") {
917
  // β›” A TAB THAT WILL NOT LOAD IS NOT AN EMPTY TAB. Painting it as one reads exactly
918
  // like the cells having been deleted, so the reason is said instead.
919
+ if (!quiet && still === "apply") setNotice(got.ok ? "That sheet could not be read, so it is not shown."
920
+ : got.message);
921
  return false;
922
  }
923
  tabRouteRef.current = "no";
 
927
  if (served) return true;
928
  }
929
  const fresh = await readWorkbook(workbookId);
930
+ const still = stillCurrent === undefined || stillCurrent() ? "apply" : "discard";
931
  if (!fresh.ok) {
932
  if (discardMissingWorkbook(workbookId, fresh)) return false;
933
+ if (!quiet && still === "apply") setNotice(fresh.message);
934
  return false;
935
  }
936
  const live = bookRef.current;
 
956
  setUnreadableAddressTab("");
957
  setTabId(id);
958
  const current = bookRef.current;
959
+ if (!current) return;
960
+ const generation = ++tabNavGenRef.current;
961
+ void ensureTabs(current.id, [id], false,
962
+ () => tabNavVerdict(generation, tabNavGenRef.current) === "apply");
963
  }, [ensureTabs, rememberOpenWorkbook]);
964
 
965
  // Wave 60 base kit: a hidden or very hidden sheet has no tab, so it is never the open one. When
966
  // the open tab is hidden (by the View ribbon, an undo, or a workbook that opened on one), the
967
  // page opens the first visible tab through the tab bar's own door, which fetches its cells.
968
+ // A stale pair whose snapshot lacks the selected tab must leave the page alone.
969
  useEffect(() => {
970
  if (!book) return;
971
+ const next = hiddenTabRedirect(book.sheets, tabId);
972
+ if (next) openTab(next);
 
 
973
  }, [book, openTab, tabId]);
974
 
975
  // Read the whole hash, as the shell does: workbook changes keep the same route key.
web/src/sheet/SheetRail.tsx CHANGED
@@ -53,7 +53,7 @@ import { StarIcon } from "../ui/icons";
53
  import { openExistingItem, useItemDeletions, useStarred } from "../starred/starredApi";
54
  import { ConfirmDialog } from "../ui/ConfirmDialog";
55
  import { useRailSelection } from "../ui/useRailSelection";
56
- import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, UNAUTHORIZED_EVENT, signal } from "../apiContract";
57
  import ImportDialog from "./ImportDialog";
58
  import TemplateGallery from "./templates/TemplateGallery";
59
  import { ROOT_FOLDER_ID } from "./types";
@@ -251,289 +251,6 @@ function StarMark() {
251
  );
252
  }
253
 
254
- type CustomerIntelligenceChoice = { id: string; name?: string; label?: string };
255
- type CustomerIntelligenceAction = {
256
- kind?: string;
257
- config?: { agentId?: string; destinationId?: string };
258
- };
259
- type CustomerIntelligenceDefinition = {
260
- id?: string;
261
- name?: string;
262
- kind?: string;
263
- preset?: string;
264
- trigger?: {
265
- kind?: string;
266
- enabled?: boolean;
267
- workbookId?: string;
268
- sheetId?: string;
269
- watch?: { ranges?: string[]; bindings?: string[] };
270
- };
271
- flow?: { actions?: CustomerIntelligenceAction[] };
272
- };
273
-
274
- function intelligenceList(value: string): string[] {
275
- return [...new Set(value.split(/[\n,]+/).map((item) => item.trim()).filter(Boolean))];
276
- }
277
-
278
- /** C2's frozen Sheet payload. This is the one writer used by save, disable and test. */
279
- export function sheetCustomerIntelligencePayload(input: {
280
- workbookId: string;
281
- sheetId: string;
282
- ranges: string;
283
- bindings: string;
284
- agentId: string;
285
- destinationId: string;
286
- enabled: boolean;
287
- }) {
288
- const ranges = intelligenceList(input.ranges);
289
- const bindings = intelligenceList(input.bindings);
290
- return {
291
- preset: "customer_intelligence",
292
- name: "Sheet intelligence",
293
- kind: "plain",
294
- trigger: {
295
- kind: "sheet_insight_changed",
296
- enabled: input.enabled,
297
- workbookId: input.workbookId,
298
- sheetId: input.sheetId.trim(),
299
- watch: {
300
- ...(ranges.length ? { ranges } : {}),
301
- ...(bindings.length ? { bindings } : {}),
302
- },
303
- },
304
- flow: {
305
- actions: [
306
- { id: "insight", kind: "agent_insight", enabled: true,
307
- config: { agentId: input.agentId, workflowId: "wf_main" } },
308
- ...(input.destinationId
309
- ? [{ id: "notify", kind: "slack", enabled: true,
310
- config: { destinationId: input.destinationId, digestRows: 12 } }]
311
- : []),
312
- ],
313
- },
314
- };
315
- }
316
-
317
- async function customerIntelligenceRequest(path: string, init?: RequestInit) {
318
- const response = await fetch(`${API_V1}${path}`, {
319
- credentials: CREDENTIALS,
320
- headers: init?.body ? { "Content-Type": "application/json" } : undefined,
321
- ...init,
322
- });
323
- let body: Record<string, unknown> = {};
324
- try { body = await response.json() as Record<string, unknown>; } catch { /* status still speaks */ }
325
- if (response.status === 401) signal(UNAUTHORIZED_EVENT);
326
- if (!response.ok) {
327
- const detail = body.detail as { error?: { message?: string } } | undefined;
328
- throw new Error(detail?.error?.message || "Customer intelligence could not be loaded. Try again.");
329
- }
330
- return body;
331
- }
332
-
333
- function CustomerIntelligenceEditor({ workbookId, anchor, onDismiss }: {
334
- workbookId: string;
335
- anchor: HTMLElement;
336
- onDismiss: () => void;
337
- }) {
338
- const [loading, setLoading] = useState(true);
339
- const [busy, setBusy] = useState<"save" | "disable" | "test" | "">("");
340
- const [error, setError] = useState("");
341
- const [notice, setNotice] = useState("");
342
- const [agents, setAgents] = useState<CustomerIntelligenceChoice[]>([]);
343
- const [destinations, setDestinations] = useState<CustomerIntelligenceChoice[]>([]);
344
- const [automationId, setAutomationId] = useState("");
345
- const [sheetId, setSheetId] = useState("");
346
- const [ranges, setRanges] = useState("");
347
- const [bindings, setBindings] = useState("");
348
- const [agentId, setAgentId] = useState("");
349
- const [destinationId, setDestinationId] = useState("");
350
- const [enabled, setEnabled] = useState(false);
351
- const [receipt, setReceipt] = useState<{ preview: string; summary: string } | null>(null);
352
-
353
- const load = () => {
354
- const controller = new AbortController();
355
- setLoading(true);
356
- setError("");
357
- const definitionsRequest = customerIntelligenceRequest("/automations", { signal: controller.signal });
358
- const destinationsRequest = customerIntelligenceRequest("/agents", { signal: controller.signal })
359
- .catch(() => ({ agents: [], configured: false }));
360
- void Promise.all([definitionsRequest, destinationsRequest]).then(([body, destinationBody]) => {
361
- const definitions = Array.isArray(body.automations)
362
- ? body.automations as CustomerIntelligenceDefinition[] : [];
363
- const definition = definitions.find((row) => row.preset === "customer_intelligence"
364
- && row.trigger?.kind === "sheet_insight_changed"
365
- && row.trigger?.workbookId === workbookId) ?? {};
366
- const trigger = definition.trigger ?? {};
367
- const actions = Array.isArray(definition.flow?.actions) ? definition.flow.actions : [];
368
- const agent = actions.find((action) => action.kind === "agent_insight");
369
- const slack = actions.find((action) => action.kind === "slack");
370
- setAutomationId(definition.id ?? "");
371
- const options = body.customerIntelligence as { agents?: Array<CustomerIntelligenceChoice & { ready?: boolean }> } | undefined;
372
- setAgents((options?.agents ?? []).filter((row) => row.ready === true));
373
- setDestinations(destinationBody.configured === true && Array.isArray(destinationBody.agents)
374
- ? (destinationBody.agents as Array<CustomerIntelligenceChoice & { active?: boolean }>)
375
- .filter((row) => row.active !== false) : []);
376
- setSheetId(typeof trigger.sheetId === "string" ? trigger.sheetId : "");
377
- setRanges((trigger.watch?.ranges ?? []).join(", "));
378
- setBindings((trigger.watch?.bindings ?? []).join(", "));
379
- setAgentId(agent?.config?.agentId ?? "");
380
- setDestinationId(slack?.config?.destinationId ?? "");
381
- setEnabled(definition.preset === "customer_intelligence" && trigger.enabled === true);
382
- setLoading(false);
383
- }).catch((reason: unknown) => {
384
- if ((reason as { name?: string })?.name === "AbortError") return;
385
- setError(reason instanceof Error ? reason.message : "Customer intelligence could not be loaded. Try again.");
386
- setLoading(false);
387
- });
388
- return controller;
389
- };
390
-
391
- useEffect(() => {
392
- const controller = load();
393
- return () => controller.abort();
394
- }, [workbookId]);
395
-
396
- const rangeList = intelligenceList(ranges);
397
- const bindingList = intelligenceList(bindings);
398
- const configured = !!sheetId.trim() && !!agentId && (rangeList.length > 0 || bindingList.length > 0);
399
- const payload = (nextEnabled: boolean) => sheetCustomerIntelligencePayload({
400
- workbookId, sheetId, ranges, bindings, agentId, destinationId, enabled: nextEnabled,
401
- });
402
-
403
- const save = async (nextEnabled: boolean, mode: "save" | "disable") => {
404
- setBusy(mode);
405
- setError("");
406
- setNotice("");
407
- setReceipt(null);
408
- try {
409
- const body = await customerIntelligenceRequest(
410
- automationId ? `/automations/${encodeURIComponent(automationId)}` : "/automations", {
411
- method: automationId ? "PATCH" : "POST", body: JSON.stringify(payload(nextEnabled)),
412
- });
413
- const saved = body.automation as CustomerIntelligenceDefinition | undefined;
414
- if (saved?.id) setAutomationId(saved.id);
415
- setEnabled(nextEnabled);
416
- setNotice(nextEnabled ? "Customer intelligence is on." : "Customer intelligence is off.");
417
- } catch (reason) {
418
- setError(reason instanceof Error ? reason.message : "Customer intelligence could not be saved. Try again.");
419
- } finally {
420
- setBusy("");
421
- }
422
- };
423
-
424
- const test = async () => {
425
- setBusy("test");
426
- setError("");
427
- setNotice("");
428
- setReceipt(null);
429
- try {
430
- if (!automationId) throw new Error("Save this setting before testing it.");
431
- const body = await customerIntelligenceRequest(
432
- `/automations/${encodeURIComponent(automationId)}/customer-intelligence/dry-run`,
433
- { method: "POST" },
434
- );
435
- const proof = (body.receipt ?? {}) as {
436
- dryRun?: boolean; noDispatch?: boolean; dispatchCount?: number; providerCalls?: number;
437
- };
438
- if (proof.dryRun !== true || proof.noDispatch !== true
439
- || proof.dispatchCount !== 0 || proof.providerCalls !== 0) {
440
- throw new Error("The test stopped because the server did not return a no-send receipt.");
441
- }
442
- setReceipt({
443
- preview: String(body.insight ?? "No insight preview was returned."),
444
- summary: "No provider or Slack dispatch occurred. A committed batch produces at most one capped digest with safe links.",
445
- });
446
- } catch (reason) {
447
- setError(reason instanceof Error ? reason.message : "The no-send test could not be completed. Try again.");
448
- } finally {
449
- setBusy("");
450
- }
451
- };
452
-
453
- return (
454
- <AnchoredOverlay
455
- anchor={anchor}
456
- className="cg-pop"
457
- role="dialog"
458
- ariaLabel="Customer intelligence settings"
459
- placement="right-start"
460
- onDismiss={onDismiss}
461
- >
462
- <div style={{ width: 400, maxWidth: "calc(100vw - 48px)", display: "grid", gap: 10 }}>
463
- <div className="cg-pop-title">Customer intelligence</div>
464
- <p className="cg-pop-note" style={{ margin: 0 }}>
465
- Runs once after a committed value or Cell-database binding batch changes watched insight.
466
- Selection, formatting, and paint changes never run it.
467
- </p>
468
- {loading ? <div role="status">Loading customer intelligence…</div> : (
469
- <>
470
- <label style={{ display: "grid", gap: 4 }}>
471
- Trigger
472
- <input className="cg-input" value="When committed Sheet insight changes" readOnly />
473
- </label>
474
- <label style={{ display: "grid", gap: 4 }}>
475
- Sheet ID
476
- <input className="cg-input" value={sheetId} onChange={(event) => setSheetId(event.currentTarget.value)}
477
- placeholder="Sheet1" />
478
- </label>
479
- <label style={{ display: "grid", gap: 4 }}>
480
- Watched ranges
481
- <input className="cg-input" value={ranges} onChange={(event) => setRanges(event.currentTarget.value)}
482
- placeholder="A2:F200, Summary!B4:B20" />
483
- </label>
484
- <label style={{ display: "grid", gap: 4 }}>
485
- Cell-database bindings
486
- <input className="cg-input" value={bindings} onChange={(event) => setBindings(event.currentTarget.value)}
487
- placeholder="customers.balance, orders.status" />
488
- </label>
489
- <label style={{ display: "grid", gap: 4 }}>
490
- Agent
491
- <select className="cg-input" value={agentId} onChange={(event) => setAgentId(event.currentTarget.value)}>
492
- <option value="">Choose an agent</option>
493
- {agents.map((agent) => <option key={agent.id} value={agent.id}>{agent.name ?? agent.label ?? agent.id}</option>)}
494
- </select>
495
- </label>
496
- <label style={{ display: "grid", gap: 4 }}>
497
- Governed Slack digest
498
- <select className="cg-input" value={destinationId}
499
- onChange={(event) => setDestinationId(event.currentTarget.value)}>
500
- <option value="">No Slack digest</option>
501
- {destinations.map((destination) => (
502
- <option key={destination.id} value={destination.id}>
503
- {destination.label ?? destination.name ?? destination.id}
504
- </option>
505
- ))}
506
- </select>
507
- </label>
508
- <label style={{ display: "flex", gap: 8, alignItems: "center" }}>
509
- <input type="checkbox" checked={enabled} disabled={!configured || !!busy}
510
- onChange={(event) => setEnabled(event.currentTarget.checked)} />
511
- Enabled
512
- </label>
513
- <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
514
- <button type="button" className="cg-btn cg-btn--primary" disabled={!configured || !!busy}
515
- onClick={() => void save(enabled, "save")}>{busy === "save" ? "Saving…" : "Save"}</button>
516
- <button type="button" className="cg-btn" disabled={!!busy || !enabled}
517
- onClick={() => void save(false, "disable")}>{busy === "disable" ? "Disabling…" : "Disable"}</button>
518
- <button type="button" className="cg-btn" disabled={!configured || !automationId || !!busy}
519
- onClick={() => void test()}>{busy === "test" ? "Testing…" : "Test (no send)"}</button>
520
- </div>
521
- </>
522
- )}
523
- {error ? <p className="cg-pop-note" role="alert" style={{ margin: 0 }}>{error}</p> : null}
524
- {notice ? <p className="cg-pop-note" role="status" style={{ margin: 0 }}>{notice}</p> : null}
525
- {receipt ? (
526
- <div className="cg-pop-note" role="status">
527
- <strong>No-send preview</strong>
528
- <p>{receipt.preview}</p>
529
- <p>{receipt.summary}</p>
530
- </div>
531
- ) : null}
532
- </div>
533
- </AnchoredOverlay>
534
- );
535
- }
536
-
537
  function FindIcon() {
538
  return (
539
  <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none"
@@ -570,11 +287,6 @@ type Dragged =
570
  const mayManageWorkbook = (row: WorkbookRow | undefined) =>
571
  !!row && "role" in row && row.role === "owner";
572
 
573
- // C2's native setting is workbook content: Sheet's write wall admits owners and edit grantees.
574
- // Keep this separate from `mayManageWorkbook` so sharing, filing and deletion remain owner-only.
575
- const mayEditWorkbook = (row: WorkbookRow | undefined) =>
576
- !!row && "role" in row && (row.role === "owner" || row.role === "editor");
577
-
578
  const newFolderId = () =>
579
  "f" + Date.now().toString(36) + Math.floor(Math.random() * 46656).toString(36);
580
 
@@ -670,10 +382,6 @@ export default function SheetRail({
670
  const [step, setStep] = useState(() => at === null ? 0 : 1);
671
  const [query, setQuery] = useState("");
672
  const [menu, setMenu] = useState<Menu | null>(null);
673
- const [customerIntelligence, setCustomerIntelligence] = useState<{
674
- workbookId: string;
675
- anchor: HTMLElement;
676
- } | null>(null);
677
  const [renaming, setRenaming] = useState("");
678
  const [createAt, setCreateAt] = useState<HTMLElement | null>(null);
679
  const [namingFolder, setNamingFolder] = useState(false);
@@ -1550,19 +1258,6 @@ export default function SheetRail({
1550
  <MenuLabel icon={<ShareMark size={16} />} text="Share" />
1551
  </button>
1552
  ) : null}
1553
- {menu.kind === "workbook" && mayEditWorkbook(workbookById.get(menu.id)) ? (
1554
- <button
1555
- type="button"
1556
- role="menuitem"
1557
- onClick={() => {
1558
- const target = { workbookId: menu.id, anchor: menu.anchor };
1559
- closeMenu();
1560
- setCustomerIntelligence(target);
1561
- }}
1562
- >
1563
- <MenuLabel icon="spark" text="Customer intelligence" />
1564
- </button>
1565
- ) : null}
1566
  {/* β›”β›” R6 β€” THE DELETE ASKS FIRST, AND UNTIL THIS TICKET IT DID NOT. One click on
1567
  this row removed a workbook and everything in it with no confirmation anywhere in
1568
  `src/sheet/`: no dialog, no armed second click, not even a native confirm. The
@@ -1644,14 +1339,6 @@ export default function SheetRail({
1644
  </AnchoredOverlay>
1645
  ) : null}
1646
 
1647
- {customerIntelligence ? (
1648
- <CustomerIntelligenceEditor
1649
- workbookId={customerIntelligence.workbookId}
1650
- anchor={customerIntelligence.anchor}
1651
- onDismiss={() => setCustomerIntelligence(null)}
1652
- />
1653
- ) : null}
1654
-
1655
  {/* β›”β›” R6 / CONTRACT C8 β€” THE ONE CONFIRM DIALOG, NOT A SECOND ONE SHAPED LIKE IT. It brings
1656
  the centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap,
1657
  Escape, the backdrop and the return of focus to the opener. Re-implementing any of that
 
53
  import { openExistingItem, useItemDeletions, useStarred } from "../starred/starredApi";
54
  import { ConfirmDialog } from "../ui/ConfirmDialog";
55
  import { useRailSelection } from "../ui/useRailSelection";
56
+ import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
57
  import ImportDialog from "./ImportDialog";
58
  import TemplateGallery from "./templates/TemplateGallery";
59
  import { ROOT_FOLDER_ID } from "./types";
 
251
  );
252
  }
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  function FindIcon() {
255
  return (
256
  <svg className="cg-find-view-icon" width="14" height="14" viewBox="0 0 16 16" fill="none"
 
287
  const mayManageWorkbook = (row: WorkbookRow | undefined) =>
288
  !!row && "role" in row && row.role === "owner";
289
 
 
 
 
 
 
290
  const newFolderId = () =>
291
  "f" + Date.now().toString(36) + Math.floor(Math.random() * 46656).toString(36);
292
 
 
382
  const [step, setStep] = useState(() => at === null ? 0 : 1);
383
  const [query, setQuery] = useState("");
384
  const [menu, setMenu] = useState<Menu | null>(null);
 
 
 
 
385
  const [renaming, setRenaming] = useState("");
386
  const [createAt, setCreateAt] = useState<HTMLElement | null>(null);
387
  const [namingFolder, setNamingFolder] = useState(false);
 
1258
  <MenuLabel icon={<ShareMark size={16} />} text="Share" />
1259
  </button>
1260
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
 
1261
  {/* β›”β›” R6 β€” THE DELETE ASKS FIRST, AND UNTIL THIS TICKET IT DID NOT. One click on
1262
  this row removed a workbook and everything in it with no confirmation anywhere in
1263
  `src/sheet/`: no dialog, no armed second click, not even a native confirm. The
 
1339
  </AnchoredOverlay>
1340
  ) : null}
1341
 
 
 
 
 
 
 
 
 
1342
  {/* β›”β›” R6 / CONTRACT C8 β€” THE ONE CONFIRM DIALOG, NOT A SECOND ONE SHAPED LIKE IT. It brings
1343
  the centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap,
1344
  Escape, the backdrop and the return of focus to the opener. Re-implementing any of that
web/src/sheet/ribbonHome.tsx CHANGED
@@ -22,7 +22,9 @@
22
  //
23
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5) β€” unchanged and still binding here: icons are inline
24
  // SVG on `currentColor` and never emoji, a colour swatch is a token-styled span, colour and type
25
- // are token only, Excel's Title Case labels (R41), no em dash or en dash in any string that reaches a screen.
 
 
26
 
27
  import {
28
  CELL_FONTS, CELL_FORMAT_KINDS, DEFAULT_CELL_FONT, FONT_SIZE_STEPS, FONT_STACKS,
@@ -149,7 +151,10 @@ const ORIENTATIONS: { label: string; degrees: number }[] = [
149
  { label: "Horizontal", degrees: 0 },
150
  ];
151
 
152
- /** The fills, which are the tint end of the same hues, so ink stays readable on every one. */
 
 
 
153
  const FILLS: { token: string; label: string }[] = [
154
  { token: "--lp-surface-2", label: "Grey" },
155
  { token: "--lp-blue-tint", label: "Blue" },
@@ -414,6 +419,51 @@ export function IconCaret() {
414
  );
415
  }
416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  /**
418
  * ⭐⭐ EVERY HOME GROUP, IN R8's ORDER. Moved here whole from `Ribbon.tsx`; the shell renders the
419
  * result inside the one `role="toolbar"` row it still owns, so the DOM this paints is the DOM it
@@ -428,6 +478,13 @@ export const homeGroups = (ctx: RibbonTabContext) => {
428
  // R19: the bar reads the armed token through the cell paint door. With no fill, use the
429
  // gallery's neutral first swatch; with no ink, use its Default swatch. Neither invents a hue.
430
  const fillColour = tokenColour(style?.fill ?? FILLS[0].token, `var(${FILLS[0].token})`);
 
 
 
 
 
 
 
431
  const inkColour = tokenColour(style?.color ?? INKS[0].token, `var(${INKS[0].token})`);
432
 
433
  const swatches = (
@@ -458,6 +515,20 @@ export const homeGroups = (ctx: RibbonTabContext) => {
458
  </button>
459
  ))}
460
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  <button
462
  type="button"
463
  role="menuitem"
 
22
  //
23
  // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5) β€” unchanged and still binding here: icons are inline
24
  // SVG on `currentColor` and never emoji, a colour swatch is a token-styled span, colour and type
25
+ // are token only except a CELL FILL, which SDLC 64 R2 / contract C1 widens to the user's own
26
+ // hex through the More Colors picker, Excel's Title Case labels (R41), no em dash or en dash
27
+ // in any string that reaches a screen.
28
 
29
  import {
30
  CELL_FONTS, CELL_FORMAT_KINDS, DEFAULT_CELL_FONT, FONT_SIZE_STEPS, FONT_STACKS,
 
151
  { label: "Horizontal", degrees: 0 },
152
  ];
153
 
154
+ /**
155
+ * R2 / C1: the TOKEN HALF of the tokens-plus-custom fill door. These six remain the tint end
156
+ * of the same hues, so ink stays readable on every one; More Colors writes the user's own hex.
157
+ */
158
  const FILLS: { token: string; label: string }[] = [
159
  { token: "--lp-surface-2", label: "Grey" },
160
  { token: "--lp-blue-tint", label: "Blue" },
 
419
  );
420
  }
421
 
422
+ /**
423
+ * The chip the native picker paints itself into, sized to sit in a `.sheet-ribbon-item` row.
424
+ *
425
+ * ⭐ THE HAIRLINE IS R19's, FOR R19's REASON, ONE CONTROL OVER. `IconFill`'s colour bar carries a
426
+ * stroke because the gallery is all TINTS and a pale one measured rgb(247,247,246) on white: the
427
+ * bar could not be seen at all. A custom fill is chosen by a person and can land anywhere,
428
+ * including on that same near white, so the chip needs an EDGE for its extent to read. Border
429
+ * and colour are separate here, which is exactly what `border: 0` cost the bar.
430
+ */
431
+ const CUSTOM_FILL_SWATCH: CSSProperties = {
432
+ width: 20, height: 20, padding: 0, marginRight: 8, cursor: "pointer",
433
+ border: "1px solid var(--lp-line)", borderRadius: 2, background: "transparent",
434
+ };
435
+
436
+ /**
437
+ * ⭐⭐ R2 / C1 β€” ONE COMMIT PER PICK, WHICH IS WHY THIS IS A NATIVE `change` LISTENER AND NOT
438
+ * `onChange`.
439
+ *
440
+ * β›” REACT MAPS `onChange` ON AN INPUT TO THE NATIVE `input` EVENT, and a colour dialog fires
441
+ * that CONTINUOUSLY while the cursor moves across the spectrum. Each one would reach
442
+ * `SheetGrid.tsx::applyStyle` as its own `styleCells` commit, and `SheetPage.tsx::commitCells`
443
+ * pushes a HISTORY STEP per commit: choosing one colour would cost a person twenty presses of
444
+ * Ctrl+Z to undo, and the undo stack would be full of hues nobody chose. The native `change`
445
+ * event fires ONCE, when the colour is committed, which is the act the ribbon means.
446
+ *
447
+ * ⚠ BOUND ONCE PER ELEMENT, AND IT CARRIES THE CURRENT `apply`. The listener dies with the
448
+ * element when the popover unmounts, so nothing has to remove it; the `dataset` flag stops a
449
+ * re-render from stacking a second copy. `apply` is re-stamped on every render instead of being
450
+ * captured, because the closure `homeGroups` had at mount holds the tab as it was THEN, and a
451
+ * background refresh between opening the popover and picking a colour would otherwise commit
452
+ * against a stale snapshot.
453
+ */
454
+ type CustomFillInput = HTMLInputElement & { lpApplyFill?: (patch: CellStylePatch) => void };
455
+
456
+ const bindCustomFill = (apply: (patch: CellStylePatch) => void) =>
457
+ (el: CustomFillInput | null) => {
458
+ if (!el) return;
459
+ el.lpApplyFill = apply;
460
+ if (el.dataset.lpFillBound === "1") return;
461
+ el.dataset.lpFillBound = "1";
462
+ el.addEventListener("change", () => {
463
+ el.lpApplyFill?.({ fill: el.value.toLowerCase() } as CellStylePatch);
464
+ });
465
+ };
466
+
467
  /**
468
  * ⭐⭐ EVERY HOME GROUP, IN R8's ORDER. Moved here whole from `Ribbon.tsx`; the shell renders the
469
  * result inside the one `role="toolbar"` row it still owns, so the DOM this paints is the DOM it
 
478
  // R19: the bar reads the armed token through the cell paint door. With no fill, use the
479
  // gallery's neutral first swatch; with no ink, use its Default swatch. Neither invents a hue.
480
  const fillColour = tokenColour(style?.fill ?? FILLS[0].token, `var(${FILLS[0].token})`);
481
+ // ⭐⭐ R2 / C1: THE NATIVE PICKER ONLY READS SIX-DIGIT HEX. An armed token can resolve to
482
+ // rgb(...) or nothing, and feeding that to type="color" silently shows black. Preserve a
483
+ // stored lowercase hex byte for byte; otherwise resolve the token and keep only that form.
484
+ const resolvedFillHex = style?.fill && /^#[0-9a-f]{6}$/.test(style.fill)
485
+ ? style.fill
486
+ : tokenColour(style?.fill ?? FILLS[0].token, "#ffffff");
487
+ const customFillHex = /^#[0-9a-f]{6}$/.test(resolvedFillHex) ? resolvedFillHex : "#ffffff";
488
  const inkColour = tokenColour(style?.color ?? INKS[0].token, `var(${INKS[0].token})`);
489
 
490
  const swatches = (
 
515
  </button>
516
  ))}
517
  </div>
518
+ {/* R2 / C1: focus opens the native picker, so this input must not cancel mouse-down. */}
519
+ {which === "fill" && (
520
+ <label role="menuitem" className="sheet-ribbon-item sheet-ribbon-custom">
521
+ <input
522
+ type="color"
523
+ className="sheet-ribbon-custom-input"
524
+ aria-label="More Colors"
525
+ defaultValue={customFillHex}
526
+ style={CUSTOM_FILL_SWATCH}
527
+ ref={bindCustomFill(apply)}
528
+ />
529
+ More Colors
530
+ </label>
531
+ )}
532
  <button
533
  type="button"
534
  role="menuitem"
web/src/sheet/sheetState.ts CHANGED
@@ -48,8 +48,8 @@ import { replaceCellStyle } from "./cellStyleOps";
48
  import type { PasteMode } from "./clipboardOps";
49
  import { parseRange, withRuleRange } from "./rules";
50
 
51
- /** R19's three MARKS. `refused` is a fourth state and not one of the three: it replaces the value
52
- * rather than qualifying it, so it gets its own treatment in the renderer. */
53
  export type CellMark = "bound-fresh" | "bound-stale" | "typed" | "refused" | "none";
54
 
55
  /**
@@ -66,14 +66,17 @@ export const markOf = (cell: Cell | null | undefined): CellMark => {
66
  // all. There is nothing to mark on a cell that holds no value, which is what `none` says.
67
  if (cell.kind === "empty") return "none";
68
  if (cell.state === "refused") return "refused";
69
- if (cell.kind === "literal") return "typed";
 
 
 
70
  // ⭐⭐ W53-T01 / R2 β€” A FORMULA THAT COMPUTED IN THIS BROWSER IS NOT A DATABASE READING, AND
71
  // THE FALL-THROUGH WOULD HAVE SAID IT WAS. Every formula cell used to be `stale` (nothing on
72
  // the client could compute one), so it always took the line above and wore the YELLOW triangle.
73
  // Now that R2 computes one on commit it becomes `fresh`, and one line lower `bound-fresh` would
74
  // paint R19's BLUE triangle: "this number came from a database, and it is current". A hand
75
- // typed `=F6+G6` came from no database at all, so it wears the grey dot a hand typed value
76
- // wears. A formula still WAITING on a bound dependency keeps the yellow, because that is
77
  // exactly what it means there: a database reading that is not fresh yet.
78
  if (cell.kind === "formula") return cell.state === "stale" ? "bound-stale" : "typed";
79
  if (cell.state === "stale") return "bound-stale";
 
48
  import type { PasteMode } from "./clipboardOps";
49
  import { parseRange, withRuleRange } from "./rules";
50
 
51
+ /** Corner marks distinguish database freshness, locally computed formulas (`typed`) and refusals.
52
+ * Empty cells and hand typed literals use `none`. */
53
  export type CellMark = "bound-fresh" | "bound-stale" | "typed" | "refused" | "none";
54
 
55
  /**
 
66
  // all. There is nothing to mark on a cell that holds no value, which is what `none` says.
67
  if (cell.kind === "empty") return "none";
68
  if (cell.state === "refused") return "refused";
69
+ // S64-T17 / owner instruction 9: the corner mark says where a value came from.
70
+ // A hand typed literal came from nobody and wears no mark. `bound-fresh` and
71
+ // `bound-stale` mean a cell database and are the only source marks a reader should interpret.
72
+ if (cell.kind === "literal") return "none";
73
  // ⭐⭐ W53-T01 / R2 β€” A FORMULA THAT COMPUTED IN THIS BROWSER IS NOT A DATABASE READING, AND
74
  // THE FALL-THROUGH WOULD HAVE SAID IT WAS. Every formula cell used to be `stale` (nothing on
75
  // the client could compute one), so it always took the line above and wore the YELLOW triangle.
76
  // Now that R2 computes one on commit it becomes `fresh`, and one line lower `bound-fresh` would
77
  // paint R19's BLUE triangle: "this number came from a database, and it is current". A hand
78
+ // typed `=F6+G6` came from no database at all, so it keeps the grey dot for a locally
79
+ // computed formula. A formula still WAITING on a bound dependency keeps the yellow, because that is
80
  // exactly what it means there: a database reading that is not fresh yet.
81
  if (cell.kind === "formula") return cell.state === "stale" ? "bound-stale" : "typed";
82
  if (cell.state === "stale") return "bound-stale";
web/src/sheet/types.ts CHANGED
@@ -451,9 +451,19 @@ export const bindingAdoptedFrom = (binding: unknown): BindingAdoptedFrom | null
451
  // reads, so accepting one the server cannot apply would show a value formatted differently from
452
  // what was asked, with nobody told. One is cosmetic, the other is a wrong number on a screen.
453
  //
454
- // ⚠ COLOURS ARE STORED AS TOKEN NAMES (`--lp-red-deep`), never as hex. DESIGN.md 3 is token
455
- // only, and a hex written into a stored document is a palette decision that outlives every
456
- // palette change. `SheetGrid.tsx` resolves the token against the document at paint time.
 
 
 
 
 
 
 
 
 
 
457
 
458
  /**
459
  * β›” Mirrored in `platform/core/sheets.py::CELL_FORMAT_KINDS`, and parity checked.
@@ -701,9 +711,17 @@ export interface CellStyle {
701
  bold?: boolean;
702
  italic?: boolean;
703
  underline?: boolean;
704
- /** A `--lp-*` token name for the ink. */
 
 
 
 
705
  color?: string;
706
- /** A `--lp-*` token name for the cell background. */
 
 
 
 
707
  fill?: string;
708
  align?: CellAlign;
709
  /**
 
451
  // reads, so accepting one the server cannot apply would show a value formatted differently from
452
  // what was asked, with nobody told. One is cosmetic, the other is a wrong number on a screen.
453
  //
454
+ // ⭐⭐ SDLC 64 R2 / CONTRACT C1 REVOKES THE TOKEN-ONLY RULE FOR CELL FILL. A cell's fill is
455
+ // USER DATA, not chrome, so its document may carry a hex literal. Every `--lp-*` token keeps
456
+ // working exactly as before, and the six gallery swatches still write those token names.
457
+ // `cellBorders.ts::tokenColour` already returns a `#` value verbatim at paint time, so a stored
458
+ // hex needs no renderer change. The server must keep it too, or it vanishes on the next reload.
459
+
460
+ /**
461
+ * R2 / C1: mirrored byte for byte in `platform/core/sheets.py::CELL_COLOUR_PATTERN`.
462
+ * `verify_sheet.py`'s C1 leg compares the two SOURCE STRINGS, so the two halves cannot drift.
463
+ */
464
+ export const CELL_COLOUR_PATTERN = "^(--lp-[a-z0-9-]{1,40}|#[0-9a-f]{6})$";
465
+ const CELL_COLOUR_RE = new RegExp(CELL_COLOUR_PATTERN);
466
+ export const isCellColour = (value: string): boolean => CELL_COLOUR_RE.test(value);
467
 
468
  /**
469
  * β›” Mirrored in `platform/core/sheets.py::CELL_FORMAT_KINDS`, and parity checked.
 
711
  bold?: boolean;
712
  italic?: boolean;
713
  underline?: boolean;
714
+ /**
715
+ * A `--lp-*` token name for the ink. STORAGE accepts the same form as `fill` under C1,
716
+ * because the server runs one guard for both keys. The ribbon's ink gallery stays a closed
717
+ * token list: that is a UI decision, not a storage one.
718
+ */
719
  color?: string;
720
+ /**
721
+ * A `--lp-*` token name OR a `#rrggbb` lowercase hex literal, both matching
722
+ * {@link CELL_COLOUR_PATTERN}. R2 / C1: a cell's fill is USER DATA, so the document
723
+ * may carry the hue itself and not only a name the palette resolves.
724
+ */
725
  fill?: string;
726
  align?: CellAlign;
727
  /**
web/src/shell/Shell.tsx CHANGED
@@ -60,11 +60,10 @@ import type { MouseEvent as ReactMouseEvent, ReactNode, RefObject } from "react"
60
  *
61
  * ⚠ EVERY ONE OF THESE WAS ALREADY BEHIND A CONDITION IN THE JSX, and that is what makes the
62
  * split real rather than cosmetic: a `lazy` whose mount renders unconditionally downloads on the
63
- * first paint anyway and buys a Suspense boundary for nothing. `CustomerGrid` is deliberately NOT
64
- * in this list, for the mirror-image reason β€” it IS the first paint on nearly every route, so
65
- * splitting it would add a round trip to the common case. (The build reports it as an INEFFECTIVE
66
- * dynamic import from `RecordDetail`; that is expected and correct β€” that import exists to break
67
- * a module CYCLE, not to move bytes. See the note beside it.)
68
  *
69
  * ⚠ `SettingsModal` is a NAMED export, so its loader maps to `{ default }`. A default-import
70
  * `lazy()` over a named export fails at RUNTIME, on click, and only for that one surface.
@@ -83,7 +82,11 @@ import "../styles/wave55/apps.css";
83
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
84
  // so it no longer has to tell the grid that it did.
85
  import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
86
- import { PageSurface } from "../pages/PageSurface";
 
 
 
 
87
  const SettingsModal = lazy(() =>
88
  import("../settings/SettingsModal").then((m) => ({ default: m.SettingsModal })));
89
  import type { SettingsSection } from "../settings/SettingsModal";
@@ -110,8 +113,8 @@ import type { TemplateModule } from "../sheet/templates/templatesApi";
110
  /* ⭐ W35-T09 β€” the assistant's EXISTING door for opening an AI-built view: hash + a retry
111
  ladder, returning a canceller. A second emit here would be a second answer. */
112
  import { openBuiltView } from "../assistant/AssistantPage";
113
- import { FINANCE_NAV_GROUP, financeNavigation, parseModuleFolderIndex } from "../home/homeModel";
114
- import type { ModuleFolderIndex, NavigationApplication } from "../home/homeModel";
115
  const HomePage = lazy(() => import("../home/HomePage"));
116
  const SheetGalleryPage = lazy(() =>
117
  import("../home/HomePage").then((m) => ({ default: m.SheetGalleryPage })));
@@ -1345,27 +1348,6 @@ function AppIcon() {
1345
  );
1346
  }
1347
 
1348
- /** W63-T33 / C4: one ledger mark for the Finance group, not six competing app glyphs. */
1349
- function FinanceIcon() {
1350
- return (
1351
- <svg className="shell-nav-icon" viewBox="0 0 16 16" aria-hidden="true">
1352
- <path d="M2.3 5.2h11.4M3.5 5.2v7.4M6.5 5.2v7.4M9.5 5.2v7.4M12.5 5.2v7.4" />
1353
- <path d="M1.8 5.2 8 2.1l6.2 3.1M1.8 12.7h12.4" />
1354
- </svg>
1355
- );
1356
- }
1357
-
1358
- function FinanceDisclosure({ collapsed }: { collapsed: boolean }) {
1359
- return (
1360
- <svg viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"
1361
- style={{ marginLeft: "auto", transform: collapsed ? "rotate(-90deg)" : undefined,
1362
- transition: "transform 120ms ease" }}>
1363
- <path d="m2.5 4.2 3.5 3.5 3.5-3.5" fill="none" stroke="currentColor"
1364
- strokeWidth="1.35" strokeLinecap="round" strokeLinejoin="round" />
1365
- </svg>
1366
- );
1367
- }
1368
-
1369
  /** ⭐ WAVE 35 Β· T05 (owner item 6) β€” Templates. Owner, of Airtable's rail: *"a 'Templates and apps'
1370
  * section? I want our app to have it too but just call it Templates ... located just above our
1371
  * User button."* A sheet of cards, which is what a template gallery is: one outlined page with a
@@ -1627,21 +1609,10 @@ type NavFold = "0" | "1" | "auto";
1627
  /** The one key both halves of the fold read and write. */
1628
  const NAV_FOLD_KEY = "aios-nav-collapsed";
1629
 
1630
- /** W63-T07: a manual reopen on Sheet is a browser-session override, not a durable preference. */
1631
- const SHEET_MAIN_RAIL_HOLD_KEY = "aios-sheet-main-rail-held-open";
1632
-
1633
  type FinanceNavState =
1634
  | { phase: "idle" | "loading" }
1635
  | { phase: "error"; message: string }
1636
- | { phase: "ready"; applications: NavigationApplication[]; index: ModuleFolderIndex };
1637
-
1638
- function readSheetMainRailHold(): boolean {
1639
- try { return sessionStorage.getItem(SHEET_MAIN_RAIL_HOLD_KEY) === "1"; } catch { return false; }
1640
- }
1641
-
1642
- function writeSheetMainRailHold(): void {
1643
- try { sessionStorage.setItem(SHEET_MAIN_RAIL_HOLD_KEY, "1"); } catch { /* in-memory state remains */ }
1644
- }
1645
 
1646
  /**
1647
  * ⭐⭐ WAVE 53 Β· T32 (ruling R1) β€” WHO FOLDED THE RAIL, not merely whether it is folded.
@@ -1684,10 +1655,8 @@ function ShellFrame() {
1684
  const navRequestEpoch = useRef(0);
1685
  const [applicationsEpoch, setApplicationsEpoch] = useState(0);
1686
  const applicationCheckEpoch = useRef(0);
1687
- const [financeIndexEpoch, setFinanceIndexEpoch] = useState(0);
1688
  const [financeNav, setFinanceNav] = useState<FinanceNavState>({ phase: "idle" });
1689
  const financeRequestEpoch = useRef(0);
1690
- const financeWritePending = useRef(false);
1691
  const [dataError, setDataError] = useState("");
1692
  const [toast, setToast] = useState("");
1693
  // `null` = closed. The SECTION is the open state, so "Settings" and
@@ -1780,8 +1749,6 @@ function ShellFrame() {
1780
  // or automatically when the user clicks into the work surface (NAV_MINIMIZE_EVENT from the
1781
  // grid). Remembered per browser; expanding is always one click on the same toggle.
1782
  const [navCollapsed, setNavCollapsed] = useState<boolean>(() => readNavFold() !== "0");
1783
- const [sheetMainRailHeldOpen, setSheetMainRailHeldOpen] = useState(readSheetMainRailHold);
1784
- const [sheetMainRailAutoFolded, setSheetMainRailAutoFolded] = useState(false);
1785
  /**
1786
  * ⭐⭐ W53-T32 (R1) β€” was the fold on screen the SURFACE's or the READER's? A ref, not state,
1787
  * because it is read by the effects below at the moment they run and never by the render: a
@@ -1829,11 +1796,7 @@ function ShellFrame() {
1829
  const expandRail = useCallback(() => {
1830
  setNavCollapsed(false);
1831
  navFoldWasAuto.current = false;
1832
- if (route === SHEET_ROUTE) {
1833
- setSheetMainRailHeldOpen(true);
1834
- writeSheetMainRailHold();
1835
- }
1836
- }, [route]);
1837
  /**
1838
  * ⭐⭐ W53-T33 (owner instruction 6) β€” A RAIL ICON OPENS ITS MODULE **AND** OPENS THE RAIL.
1839
  *
@@ -2019,9 +1982,11 @@ function ShellFrame() {
2019
  // out, which is also the honest place for it: these three pages never had anything to fold for.
2020
  useEffect(() => {
2021
  if (NAV_STAYS_EXPANDED_ROUTES.has(route)) return;
2022
- // W63-T07 / R5: Sheet focus gets one automatic fold per Sheet visit. A reader who reopens
2023
- // this rail opts out for this browser session; the event handler itself stays unconditional.
2024
- if (route === SHEET_ROUTE && (sheetMainRailHeldOpen || sheetMainRailAutoFolded)) return;
 
 
2025
  // ⭐⭐ W38-T04 (R9) β€” THE AUTOMATIC FOLD IS UNCONDITIONAL, AND THAT IS THE WHOLE RULE.
2026
  // `NAV_MINIMIZE_EVENT` fires from `CustomerGrid` on EVERY cell click and EVERY view switch;
2027
  // this is its only listener, and it folds, every time, with nothing in front of it. W34-T12's
@@ -2037,16 +2002,10 @@ function ShellFrame() {
2037
  // as its own last statement, so the order here is what makes the automatic fold
2038
  // distinguishable from the minimize button pressing the same door one instruction later.
2039
  navFoldWasAuto.current = true;
2040
- if (route === SHEET_ROUTE) setSheetMainRailAutoFolded(true);
2041
  };
2042
  window.addEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
2043
  return () => window.removeEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
2044
- }, [collapseRail, route, sheetMainRailHeldOpen, sheetMainRailAutoFolded]);
2045
-
2046
- // A new Sheet visit gets one fresh auto-fold unless this browser session carries a manual hold.
2047
- useEffect(() => {
2048
- if (route !== SHEET_ROUTE) setSheetMainRailAutoFolded(false);
2049
- }, [route]);
2050
 
2051
  // ── ⭐⭐ W53-T32 (ruling R1): AN AUTOMATIC FOLD DOES NOT OUTLIVE THE SURFACE THAT MADE IT ──
2052
  //
@@ -2158,16 +2117,6 @@ function ShellFrame() {
2158
  };
2159
  }, [leaveDeletedApplication]);
2160
 
2161
- useEffect(() => {
2162
- const changed = (event: Event) => {
2163
- if ((event as CustomEvent<{ module?: string }>).detail?.module === "app") {
2164
- setFinanceIndexEpoch((epoch) => epoch + 1);
2165
- }
2166
- };
2167
- window.addEventListener("aios:module-index-changed", changed);
2168
- return () => window.removeEventListener("aios:module-index-changed", changed);
2169
- }, []);
2170
-
2171
  useEffect(() => {
2172
  const requestEpoch = ++applicationCheckEpoch.current;
2173
  const database = dataPath?.database;
@@ -2193,44 +2142,34 @@ function ShellFrame() {
2193
 
2194
  useEffect(() => {
2195
  const requestEpoch = ++financeRequestEpoch.current;
2196
- financeWritePending.current = false;
2197
  if (!who) {
2198
  setFinanceNav({ phase: "idle" });
2199
  return;
2200
  }
2201
  const controller = new AbortController();
2202
  setFinanceNav((current) => current.phase === "ready" ? current : { phase: "loading" });
2203
- void Promise.all([
2204
- fetch(`${API_V1}/finance/applications`, { credentials: CREDENTIALS, signal: controller.signal }),
2205
- fetch(`${API_V1}/module-index/app`, { credentials: CREDENTIALS, signal: controller.signal }),
2206
- ]).then(async ([applicationsResponse, indexResponse]) => {
2207
- const [applicationsBody, indexBody] = await Promise.all([
2208
- applicationsResponse.json(), indexResponse.json(),
2209
- ]);
2210
- if (!applicationsResponse.ok) {
2211
- throw new Error(applicationsBody?.detail?.error?.message || "Finance applications could not be loaded.");
2212
- }
2213
- if (!indexResponse.ok) {
2214
- throw new Error(indexBody?.detail?.error?.message || "Finance navigation preferences could not be loaded.");
2215
- }
2216
- if (!Array.isArray(applicationsBody?.applications)) {
2217
- throw new Error("Finance applications could not be read.");
2218
- }
2219
- const index = parseModuleFolderIndex(indexBody?.index);
2220
- if (!index) throw new Error("Finance navigation preferences could not be read.");
2221
- if (!controller.signal.aborted && requestEpoch === financeRequestEpoch.current) {
2222
- setFinanceNav({ phase: "ready", applications: financeNavigation(applicationsBody.applications), index });
2223
- }
2224
- }).catch((error: unknown) => {
2225
- if (!controller.signal.aborted && requestEpoch === financeRequestEpoch.current) {
2226
- setFinanceNav((current) => current.phase === "ready" ? current : {
2227
- phase: "error",
2228
- message: error instanceof Error ? error.message : "Finance navigation could not be loaded.",
2229
- });
2230
- }
2231
- });
2232
  return () => controller.abort();
2233
- }, [who, applicationsEpoch, financeIndexEpoch]);
2234
 
2235
  useEffect(() => {
2236
  const onWorkspaceStale = () => {
@@ -3136,43 +3075,8 @@ function ShellFrame() {
3136
  const automationSlot: RailSlot = railSlot(!!automation);
3137
  const analystSlot: RailSlot = railSlot(!!analyst);
3138
  const financeApplications = financeNav.phase === "ready" ? financeNav.applications : [];
3139
- const financeCollapsed = financeNav.phase === "ready"
3140
- && (financeNav.index.collapsedGroups ?? []).includes(FINANCE_NAV_GROUP);
3141
  const financeAppKey = /^#\/finance\/([^/?#]+)/.exec(hash)?.[1];
3142
  const financeCurrent = Boolean(financeAppKey);
3143
- const toggleFinanceGroup = () => {
3144
- if (navCollapsed) {
3145
- expandOnNavClick();
3146
- return;
3147
- }
3148
- if (financeNav.phase !== "ready" || financeWritePending.current) return;
3149
- financeRequestEpoch.current += 1;
3150
- const previous = financeNav;
3151
- const collapsedGroups = financeCollapsed
3152
- ? (previous.index.collapsedGroups ?? []).filter((group) => group !== FINANCE_NAV_GROUP)
3153
- : [...new Set([...(previous.index.collapsedGroups ?? []), FINANCE_NAV_GROUP])];
3154
- setFinanceNav({ ...previous, index: { ...previous.index, collapsedGroups } });
3155
- financeWritePending.current = true;
3156
- void fetch(`${API_V1}/module-index/app`, {
3157
- method: "PUT",
3158
- credentials: CREDENTIALS,
3159
- headers: { "Content-Type": "application/json" },
3160
- body: JSON.stringify({ folders: previous.index.folders,
3161
- itemFolders: previous.index.itemFolders, collapsedGroups, rev: previous.index.rev }),
3162
- }).then(async (response) => {
3163
- const body = await response.json();
3164
- if (!response.ok) throw new Error(body?.detail?.error?.message || "Finance navigation could not be saved.");
3165
- const index = parseModuleFolderIndex(body?.index);
3166
- if (!index) throw new Error("Finance navigation could not confirm the saved preference.");
3167
- setFinanceNav((current) => current.phase === "ready"
3168
- ? { ...current, index }
3169
- : current);
3170
- window.dispatchEvent(new CustomEvent("aios:module-index-changed", { detail: { module: "app" } }));
3171
- }).catch((error: unknown) => {
3172
- setFinanceNav(previous);
3173
- setToast(error instanceof Error ? error.message : "Finance navigation could not be saved.");
3174
- }).finally(() => { financeWritePending.current = false; });
3175
- };
3176
  // WAVE 23 C10 β€” the flyout's search. A plain label substring, case-folded: this list is at
3177
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
3178
  // nobody can predict over a set small enough to read.
@@ -3277,20 +3181,20 @@ function ShellFrame() {
3277
  // brand button below ("Expand navigation"), which is what a keyboard reaches.
3278
  onClick={navCollapsed ? expandOnBlank : undefined}
3279
  >
3280
- {/* D-405: the removed spacer restored Home to the top. A visible band would bring
3281
- that gap back; a zero-height band in flow would double the topbar's line at y=0.
3282
- Paint at the shared 44 px band with no layout, outside nav's loading selector.
3283
- ⚠ THE `- 1px` IS MEASURED, NOT DECORATION. `.cg-views-top` and `.auto-rail-top` are
3284
- `height: var(--lp-rail-head-h)` with a `border-bottom`, and under border-box that
3285
- border is the band's LAST row, not the row after it. At a plain
3286
- `top: var(--lp-rail-head-h)` this line landed at y=88 while both rails drew theirs at
3287
- y=87: one pixel out, which is a broken line rather than a continuous one. Counted off
3288
- the frame with Pillow, not by eye, because a 1 px offset is exactly what an eye
3289
- forgives. */}
3290
- <div aria-hidden="true" style={{ position: "absolute",
3291
- top: "calc(var(--lp-rail-head-h) - 1px)",
3292
- height: 0, borderTop: "1px solid var(--lp-line)", left: 0, right: 0,
3293
- pointerEvents: "none" }} />
3294
  {/* β›”β›” WAVE 38 Β· T05 (owner instruction 2) β€” `<div className="shell-side-head" aria-hidden />`
3295
  STOOD HERE AND IS DELETED, WITH ITS RULE IN `index.css`. Owner: *"Move the 'Home' button
3296
  into the empty space above it, and every other module button upward, so there is no
@@ -3574,56 +3478,28 @@ function ShellFrame() {
3574
  <span className="shell-nav-label">App</span>
3575
  </a>
3576
 
3577
- {/* W63-T33 / C4: one metadata-driven Finance group. `/applications` is already the
3578
- permission wall, so the shell only composes rows it received and omits the whole
3579
- group on a readable empty answer. Each child keeps the ordinary Application deep
3580
- link; there is deliberately no `#/finance` home and no copied app registry here. */}
3581
- {financeNav.phase === "ready" && financeApplications.length > 0 ? (
3582
- <div className="shell-nav-finance-group">
3583
- <button
3584
- type="button"
3585
- className={"shell-nav-item shell-nav-finance" + (financeCurrent ? " is-active" : "")}
3586
- aria-expanded={!navCollapsed && !financeCollapsed}
3587
- aria-controls="shell-finance-apps"
3588
- onClick={toggleFinanceGroup}
3589
- onMouseEnter={navCollapsed ? tipEnter("Finance") : undefined}
3590
- onMouseLeave={navCollapsed ? tipLeave : undefined}
 
 
3591
  >
3592
- <FinanceIcon />
3593
- <span className="shell-nav-label" style={{ display: "flex", alignItems: "center", minWidth: 0, flex: 1 }}>
3594
- Finance
3595
- <FinanceDisclosure collapsed={financeCollapsed} />
3596
- </span>
3597
- </button>
3598
- {!navCollapsed && !financeCollapsed ? (
3599
- <div id="shell-finance-apps">
3600
- {financeApplications.map((application) => {
3601
- if (!application.deepLink?.startsWith("/finance/")) return null;
3602
- const current = financeAppKey === application.id;
3603
- return (
3604
- <a
3605
- key={application.id}
3606
- className={"shell-nav-item shell-nav-finance-app" + (current ? " is-active" : "")}
3607
- href={`#${application.deepLink}`}
3608
- aria-current={current ? "page" : undefined}
3609
- onClick={expandOnNavClick}
3610
- style={{ paddingLeft: 34 }}
3611
- >
3612
- <span aria-hidden="true" style={{ width: 16, textAlign: "center", color: "var(--lp-muted)" }}>Β·</span>
3613
- <span className="shell-nav-label">{application.name}</span>
3614
- </a>
3615
- );
3616
- })}
3617
- </div>
3618
- ) : null}
3619
- </div>
3620
- ) : financeNav.phase === "error" ? (
3621
- <div className="shell-nav-item shell-nav-finance is-unavailable" title={financeNav.message}>
3622
- <FinanceIcon />
3623
- <span className="shell-nav-label shell-nav-label--muted">Finance</span>
3624
- <span className="shell-nav-note-dot" aria-hidden="true" />
3625
- </div>
3626
- ) : null}
3627
 
3628
  {/* Agents stays permission-aware after App. Its label still comes from the server
3629
  registry when present; moving all three arms together prevents a missing grant from
@@ -3836,7 +3712,14 @@ function ShellFrame() {
3836
  // EXIT wave 2 β€” a Y1-envelope page. The KEY is the only thing that
3837
  // varies: wave 3's Collections and Procurement come through this same
3838
  // branch, which is the whole return on the envelope contract.
3839
- <PageSurface key={active.key} pageKey={active.key} label={active.label} />
 
 
 
 
 
 
 
3840
  ) : active?.kind === "native" && active.key === "automation" ? (
3841
  // Wave 18 (C-AUTONAV): the Automation surface β€” its OWN secondary rail + editor,
3842
  // props-free by contract (it fetches /api/v1/automations itself). SESSION D's tree.
@@ -3909,7 +3792,6 @@ function ShellFrame() {
3909
  }}
3910
  onOpenView={openViewInDatabase}
3911
  onOpenQuery={(qid) => {
3912
- viewEmitCancel.current?.();
3913
  viewEmitCancel.current = openBuiltView(qid);
3914
  }}
3915
  />
@@ -4052,7 +3934,6 @@ function ShellFrame() {
4052
  }}
4053
  onOpenView={openViewInDatabase}
4054
  onOpenQuery={(qid) => {
4055
- viewEmitCancel.current?.();
4056
  viewEmitCancel.current = openBuiltView(qid);
4057
  }}
4058
  />
@@ -4241,7 +4122,6 @@ function ShellFrame() {
4241
  differently, and two copies of "route then ask" is how they would. */
4242
  onOpenView={openViewInDatabase}
4243
  onOpenQuery={(qid) => {
4244
- viewEmitCancel.current?.();
4245
  viewEmitCancel.current = openBuiltView(qid);
4246
  }}
4247
  />
 
60
  *
61
  * ⚠ EVERY ONE OF THESE WAS ALREADY BEHIND A CONDITION IN THE JSX, and that is what makes the
62
  * split real rather than cosmetic: a `lazy` whose mount renders unconditionally downloads on the
63
+ * first paint anyway and buys a Suspense boundary for nothing. `CustomerGrid` is lazy too:
64
+ * only routes that mount a grid need its component chunk. The shell's synchronous cache and
65
+ * scope helpers remain eager because invalidation and alert scope reads must precede navigation
66
+ * and session changes.
 
67
  *
68
  * ⚠ `SettingsModal` is a NAMED export, so its loader maps to `{ default }`. A default-import
69
  * `lazy()` over a named export fails at RUNTIME, on click, and only for that one surface.
 
82
  // ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
83
  // so it no longer has to tell the grid that it did.
84
  import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
85
+ // Envelope dashboards are conditional routes; their renderer is not needed to paint the shell.
86
+ // Locked production build: entry 422.44 -> 393.41 kB (422,447 -> 393,416 bytes on disk).
87
+ // The mount keeps PageSurface's heading and spinner visible while its chunk loads.
88
+ const PageSurface = lazy(() =>
89
+ import("../pages/PageSurface").then((m) => ({ default: m.PageSurface })));
90
  const SettingsModal = lazy(() =>
91
  import("../settings/SettingsModal").then((m) => ({ default: m.SettingsModal })));
92
  import type { SettingsSection } from "../settings/SettingsModal";
 
113
  /* ⭐ W35-T09 β€” the assistant's EXISTING door for opening an AI-built view: hash + a retry
114
  ladder, returning a canceller. A second emit here would be a second answer. */
115
  import { openBuiltView } from "../assistant/AssistantPage";
116
+ import { financeNavigation } from "../home/homeModel";
117
+ import type { NavigationApplication } from "../home/homeModel";
118
  const HomePage = lazy(() => import("../home/HomePage"));
119
  const SheetGalleryPage = lazy(() =>
120
  import("../home/HomePage").then((m) => ({ default: m.SheetGalleryPage })));
 
1348
  );
1349
  }
1350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1351
  /** ⭐ WAVE 35 Β· T05 (owner item 6) β€” Templates. Owner, of Airtable's rail: *"a 'Templates and apps'
1352
  * section? I want our app to have it too but just call it Templates ... located just above our
1353
  * User button."* A sheet of cards, which is what a template gallery is: one outlined page with a
 
1609
  /** The one key both halves of the fold read and write. */
1610
  const NAV_FOLD_KEY = "aios-nav-collapsed";
1611
 
 
 
 
1612
  type FinanceNavState =
1613
  | { phase: "idle" | "loading" }
1614
  | { phase: "error"; message: string }
1615
+ | { phase: "ready"; applications: NavigationApplication[] };
 
 
 
 
 
 
 
 
1616
 
1617
  /**
1618
  * ⭐⭐ WAVE 53 Β· T32 (ruling R1) β€” WHO FOLDED THE RAIL, not merely whether it is folded.
 
1655
  const navRequestEpoch = useRef(0);
1656
  const [applicationsEpoch, setApplicationsEpoch] = useState(0);
1657
  const applicationCheckEpoch = useRef(0);
 
1658
  const [financeNav, setFinanceNav] = useState<FinanceNavState>({ phase: "idle" });
1659
  const financeRequestEpoch = useRef(0);
 
1660
  const [dataError, setDataError] = useState("");
1661
  const [toast, setToast] = useState("");
1662
  // `null` = closed. The SECTION is the open state, so "Settings" and
 
1749
  // or automatically when the user clicks into the work surface (NAV_MINIMIZE_EVENT from the
1750
  // grid). Remembered per browser; expanding is always one click on the same toggle.
1751
  const [navCollapsed, setNavCollapsed] = useState<boolean>(() => readNavFold() !== "0");
 
 
1752
  /**
1753
  * ⭐⭐ W53-T32 (R1) β€” was the fold on screen the SURFACE's or the READER's? A ref, not state,
1754
  * because it is read by the effects below at the moment they run and never by the render: a
 
1796
  const expandRail = useCallback(() => {
1797
  setNavCollapsed(false);
1798
  navFoldWasAuto.current = false;
1799
+ }, []);
 
 
 
 
1800
  /**
1801
  * ⭐⭐ W53-T33 (owner instruction 6) β€” A RAIL ICON OPENS ITS MODULE **AND** OPENS THE RAIL.
1802
  *
 
1982
  // out, which is also the honest place for it: these three pages never had anything to fold for.
1983
  useEffect(() => {
1984
  if (NAV_STAYS_EXPANDED_ROUTES.has(route)) return;
1985
+ // ⭐⭐ S64-T05 / R4 REVOKES S63-T07 / R5 FOR THE MAIN RAIL: owner instruction 8 is ASYMMETRIC.
1986
+ // The main rail folds on EVERY cell click, with no per-visit memory and no session hold.
1987
+ // The SECONDARY rail in `SheetRail.tsx` keeps its once-per-visit fold and its manual hold β€”
1988
+ // that is the half R4 preserved. β›” A future guard here is the exact shape W38-T04 / R9 and
1989
+ // R4 both forbid: an unconditional handler cannot fold a rail it never hears about.
1990
  // ⭐⭐ W38-T04 (R9) β€” THE AUTOMATIC FOLD IS UNCONDITIONAL, AND THAT IS THE WHOLE RULE.
1991
  // `NAV_MINIMIZE_EVENT` fires from `CustomerGrid` on EVERY cell click and EVERY view switch;
1992
  // this is its only listener, and it folds, every time, with nothing in front of it. W34-T12's
 
2002
  // as its own last statement, so the order here is what makes the automatic fold
2003
  // distinguishable from the minimize button pressing the same door one instruction later.
2004
  navFoldWasAuto.current = true;
 
2005
  };
2006
  window.addEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
2007
  return () => window.removeEventListener(NAV_MINIMIZE_EVENT, onNavMinimize);
2008
+ }, [collapseRail, route]);
 
 
 
 
 
2009
 
2010
  // ── ⭐⭐ W53-T32 (ruling R1): AN AUTOMATIC FOLD DOES NOT OUTLIVE THE SURFACE THAT MADE IT ──
2011
  //
 
2117
  };
2118
  }, [leaveDeletedApplication]);
2119
 
 
 
 
 
 
 
 
 
 
 
2120
  useEffect(() => {
2121
  const requestEpoch = ++applicationCheckEpoch.current;
2122
  const database = dataPath?.database;
 
2142
 
2143
  useEffect(() => {
2144
  const requestEpoch = ++financeRequestEpoch.current;
 
2145
  if (!who) {
2146
  setFinanceNav({ phase: "idle" });
2147
  return;
2148
  }
2149
  const controller = new AbortController();
2150
  setFinanceNav((current) => current.phase === "ready" ? current : { phase: "loading" });
2151
+ void fetch(`${API_V1}/nav/applications`, { credentials: CREDENTIALS, signal: controller.signal })
2152
+ .then(async (applicationsResponse) => {
2153
+ const applicationsBody = await applicationsResponse.json();
2154
+ if (!applicationsResponse.ok) {
2155
+ throw new Error(applicationsBody?.detail?.error?.message || "Finance applications could not be loaded.");
2156
+ }
2157
+ if (!Array.isArray(applicationsBody?.applications)) {
2158
+ throw new Error("Finance applications could not be read.");
2159
+ }
2160
+ if (!controller.signal.aborted && requestEpoch === financeRequestEpoch.current) {
2161
+ setFinanceNav({ phase: "ready", applications: financeNavigation(applicationsBody.applications) });
2162
+ }
2163
+ }).catch((error: unknown) => {
2164
+ if (!controller.signal.aborted && requestEpoch === financeRequestEpoch.current) {
2165
+ setFinanceNav((current) => current.phase === "ready" ? current : {
2166
+ phase: "error",
2167
+ message: error instanceof Error ? error.message : "Finance navigation could not be loaded.",
2168
+ });
2169
+ }
2170
+ });
 
 
 
 
 
 
 
 
 
2171
  return () => controller.abort();
2172
+ }, [who, applicationsEpoch]);
2173
 
2174
  useEffect(() => {
2175
  const onWorkspaceStale = () => {
 
3075
  const automationSlot: RailSlot = railSlot(!!automation);
3076
  const analystSlot: RailSlot = railSlot(!!analyst);
3077
  const financeApplications = financeNav.phase === "ready" ? financeNav.applications : [];
 
 
3078
  const financeAppKey = /^#\/finance\/([^/?#]+)/.exec(hash)?.[1];
3079
  const financeCurrent = Boolean(financeAppKey);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3080
  // WAVE 23 C10 β€” the flyout's search. A plain label substring, case-folded: this list is at
3081
  // most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
3082
  // nobody can predict over a set small enough to read.
 
3181
  // brand button below ("Expand navigation"), which is what a keyboard reaches.
3182
  onClick={navCollapsed ? expandOnBlank : undefined}
3183
  >
3184
+ {/* S64-T06 / R8 (owner instruction 7, 2026-09-21) β€” D-405'S ABSOLUTE HAIRLINE
3185
+ STOOD HERE AND IS DELETED. Owner: *"Why in the hell is Home under main Navigation
3186
+ separate from Inbox / Assistant, remove the line that separate the button."*
3187
+ It continued the shared rail-head-height band line across `.shell-side`, without
3188
+ taking up space. W38-T05 made Home the rail's topmost row, but this line stayed at
3189
+ the old head's height: measured y = 87 against Home 52..86 and Inbox 86..120, so it
3190
+ painted a full-width line between Home and Inbox despite their flush row boxes.
3191
+ THE ACCEPTED TRADE: on Data and Agents, `.cg-views-top` / `.auto-rail-top` still draw
3192
+ their own band, which now begins at the rail's right edge instead of crossing it.
3193
+ On Sheet and Home there was never anything to its right to join, which is where
3194
+ the owner was looking. Home, Inbox and Assistant remain one unbroken group; the
3195
+ `shell-nav-sep` below Assistant still closes that group.
3196
+ RESTORING THIS LINE RE-CREATES THE DEFECT IN INSTRUCTION 7. A future "the rails'
3197
+ lines do not meet" fix belongs in the CONTENT pane's band, never in `.shell-side`. */}
3198
  {/* β›”β›” WAVE 38 Β· T05 (owner instruction 2) β€” `<div className="shell-side-head" aria-hidden />`
3199
  STOOD HERE AND IS DELETED, WITH ITS RULE IN `index.css`. Owner: *"Move the 'Home' button
3200
  into the empty space above it, and every other module button upward, so there is no
 
3478
  <span className="shell-nav-label">App</span>
3479
  </a>
3480
 
3481
+ {/* S64-T07 / R6 / owner instruction 2: Finance stopped being a top-level rail
3482
+ module and became Application records reached through GET /nav/applications,
3483
+ the same path Routing and Catalog ride. FinanceWorkspace is still the opener.
3484
+ The collapsed-group preference went with the disclosure because there is no
3485
+ longer a group to collapse. */}
3486
+ {financeApplications.map((application) => {
3487
+ if (!application.deepLink?.startsWith("/finance/")) return null;
3488
+ const current = financeAppKey === application.deepLink.slice("/finance/".length).split(/[/?#]/)[0];
3489
+ return (
3490
+ <a
3491
+ key={application.id}
3492
+ className={"shell-nav-item shell-nav-app-child" + (current ? " is-active" : "")}
3493
+ href={`#${application.deepLink}`}
3494
+ aria-current={current ? "page" : undefined}
3495
+ onClick={expandOnNavClick}
3496
+ style={{ paddingLeft: 34 }}
3497
  >
3498
+ <span aria-hidden="true" style={{ width: 16, textAlign: "center", color: "var(--lp-muted)" }}>Β·</span>
3499
+ <span className="shell-nav-label">{application.name}</span>
3500
+ </a>
3501
+ );
3502
+ })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3503
 
3504
  {/* Agents stays permission-aware after App. Its label still comes from the server
3505
  registry when present; moving all three arms together prevents a missing grant from
 
3712
  // EXIT wave 2 β€” a Y1-envelope page. The KEY is the only thing that
3713
  // varies: wave 3's Collections and Procurement come through this same
3714
  // branch, which is the whole return on the envelope contract.
3715
+ <Suspense key={active.key} fallback={
3716
+ <div className="pg-state">
3717
+ <h1>{active.label}</h1>
3718
+ <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading" />
3719
+ </div>
3720
+ }>
3721
+ <PageSurface key={active.key} pageKey={active.key} label={active.label} />
3722
+ </Suspense>
3723
  ) : active?.kind === "native" && active.key === "automation" ? (
3724
  // Wave 18 (C-AUTONAV): the Automation surface β€” its OWN secondary rail + editor,
3725
  // props-free by contract (it fetches /api/v1/automations itself). SESSION D's tree.
 
3792
  }}
3793
  onOpenView={openViewInDatabase}
3794
  onOpenQuery={(qid) => {
 
3795
  viewEmitCancel.current = openBuiltView(qid);
3796
  }}
3797
  />
 
3934
  }}
3935
  onOpenView={openViewInDatabase}
3936
  onOpenQuery={(qid) => {
 
3937
  viewEmitCancel.current = openBuiltView(qid);
3938
  }}
3939
  />
 
4122
  differently, and two copies of "route then ask" is how they would. */
4123
  onOpenView={openViewInDatabase}
4124
  onOpenQuery={(qid) => {
 
4125
  viewEmitCancel.current = openBuiltView(qid);
4126
  }}
4127
  />
web/src/styles/wave61/sheet-grid.css CHANGED
@@ -151,7 +151,9 @@
151
  color: var(--lp-blue-deep);
152
  background: var(--lp-blue-tint);
153
  border-bottom: 1px solid var(--lp-blue-deep);
154
- font-family: Inter, sans-serif;
155
- font-weight: 600;
 
 
156
  line-height: 1;
157
  }
 
151
  color: var(--lp-blue-deep);
152
  background: var(--lp-blue-tint);
153
  border-bottom: 1px solid var(--lp-blue-deep);
154
+ /* Highlight with background and border only; face and weight deliberately mirror
155
+ lightTheme so an active row's glyphs do not move. */
156
+ font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
157
+ font-weight: 400;
158
  line-height: 1;
159
  }