fsanyoto commited on
Commit
a49dcef
·
verified ·
1 Parent(s): c1278e4

Prune files not in the deploy set (stale build context)

Browse files
api/routes_brand.py DELETED
@@ -1,140 +0,0 @@
1
- """routes_brand.py — THE CONNECTOR BRAND-ASSET DOOR (wave 33, owner item 6 / ruling R4 / contract C6).
2
-
3
- ⭐ WHAT THE OWNER ASKED FOR, verbatim: *"Do not generate your own logo for Connectors, they look
4
- really uncanny /browse them the PNG, cut appropriately for our needs, verify visually."* So the marks
5
- are the VENDORS' OWN artwork, on disk, with their provenance recorded — `web/public/brand/` and its
6
- `SOURCES.md`. This module is the door R4 asks for and nothing else: it maps a brand KEY to a file,
7
- serves it, and refuses anything else.
8
-
9
- ⛔ WHY A NEW DOOR AND NOT `routes_assets.py`. That module gates EVERY one of its routes behind
10
- `module_gate("product_data")` (`routes_assets.py:45`) because it serves product imagery and the grant
11
- that owns product imagery is the right wall for it. A connector logo is not product data: an account
12
- with no product grant still opens Connectors, still opens the automation pickers, and would have got
13
- a 403 where a picture should be. Contract C6 says session-gated, NOT product-gated, and that is the
14
- whole reason this file exists rather than one more path over there.
15
-
16
- ⚠ SESSION-GATED, AND THAT IS AN HONEST WALL RATHER THAN A SECRET. Public brand artwork is public by
17
- definition, and the same bytes are ALSO reachable through the static bundle — `web/public/**` is
18
- copied into `web/dist/**` by `vite build`, which `main.py` mounts unauthenticated at `/`. So the
19
- session gate here is consistency with every other `/api/v1` route, not a claim that these files are
20
- confidential. What the door actually buys, and what a raw static path could not:
21
-
22
- · ONE KEY VOCABULARY. The client asks for `instagram`, the same string `BRAND_OF_CONNECTOR` maps
23
- to — never a filename. The extension is ours to change (a vendor publishing SVG tomorrow moves
24
- one line here) and no caller learns about it.
25
- · A CLEAN 404 for a key we have no art for, which is what lets the client keep its two-letter tile
26
- fallback honest instead of painting a broken-image glyph.
27
- · IMMUTABLE CACHING on a response the browser then never re-fetches.
28
-
29
- ⛔ THE FALLBACK IS NOT DEAD CODE AND MUST NOT BE "TIDIED". `ConnectorsPage.tsx:204 tileText` draws two
30
- letters for any connector with no entry in `BRAND_OF_CONNECTOR` — which is most of the planned list,
31
- by design, because the directory deliberately lists things we have not built (R8). A 404 from here is
32
- the *correct* answer for those rows, not a failure.
33
- """
34
- from __future__ import annotations
35
-
36
- import os
37
- import re
38
- from pathlib import Path
39
-
40
- from fastapi import APIRouter, Depends
41
- from fastapi.responses import FileResponse
42
-
43
- from deps import Session, err, require_session
44
-
45
- router = APIRouter(prefix="/api/v1")
46
-
47
- #: ⛔ CLOSED CHARSET, CHECKED BEFORE THE KEY TOUCHES A PATH — same discipline as
48
- #: `routes_assets._CODE_RE`. No dot, no slash, no backslash, no colon, so `..` and every absolute
49
- #: path are refused at the door (400) rather than resolved and then defended against.
50
- _KEY_RE = re.compile(r"^[a-z][a-z0-9_]{0,31}$")
51
-
52
- #: A year, immutable. The artwork is versioned by its own key: a NEW mark for a vendor is a new file
53
- #: with the same name, so a rebrand ships with a deploy and a hard reload, not with a cache bust.
54
- #: ⚠ Deliberately the same string as `routes_assets._IMMUTABLE` — two asset doors telling a browser
55
- #: two different things about the same class of file would be a defect nobody could see.
56
- _IMMUTABLE = "public, max-age=31536000, immutable"
57
-
58
- _MEDIA = {".png": "image/png", ".svg": "image/svg+xml"}
59
-
60
- #: ⭐ THE ROOTS, IN ORDER, AND THE ORDER IS THE POINT.
61
- #:
62
- #: `web/dist/brand` FIRST because that is what a container has: `deploy_web.py::_web_source_files`
63
- #: SKIPS `dist`, so the Space uploads `web/public/**` as source and its own `vite build` produces
64
- #: `dist/`. `web/public/brand` SECOND because that is what a DEV BOX has before anything is built —
65
- #: and a door that only works after `npm run build` is a door that fails for the person writing it.
66
- #: `AIOS_BRAND_DIR` FIRST OF ALL, so an operator can point at either without a redeploy.
67
- #:
68
- #: ⚠ RESOLVED PER REQUEST, NOT AT IMPORT. A module-level constant computed at import is a fact about
69
- #: the process's startup, and this one would be wrong for the whole life of any container that built
70
- #: its bundle after the API module was first imported.
71
- #:
72
- #: ⚠ THE ONE TRAP THIS ORDER CREATES, AND IT ONLY BITES A DEV BOX. `dist` winning means a mark
73
- #: replaced in `public/brand/` is NOT served until the next `npm run build` — locally the two can
74
- #: disagree, and the door will confidently serve yesterday's logo. In the image they cannot: the
75
- #: Space uploads `public/` (`deploy_web.py::_web_source_files` SKIPS `dist`) and builds `dist/` from
76
- #: it in the same step. If a local mark looks stale, rebuild before believing the door is wrong.
77
- _HERE = Path(__file__).resolve().parent
78
-
79
-
80
- def _roots():
81
- env = (os.environ.get("AIOS_BRAND_DIR") or "").strip()
82
- out = [Path(env)] if env else []
83
- web = _HERE.parent / "web" # _HERE is `aios-web/api`; its parent is `aios-web`
84
- out.append(web / "dist" / "brand")
85
- out.append(web / "public" / "brand")
86
- return out
87
-
88
-
89
- def brand_path(key):
90
- """The file for a brand key, or None. Pure and importable, so the gate answers this question
91
- without a request — the same shape `routes_connectors.directory` uses for the same reason."""
92
- k = str(key or "")
93
- if not _KEY_RE.match(k):
94
- return None
95
- for root in _roots():
96
- for ext in (".png", ".svg"):
97
- p = root / f"{k}{ext}"
98
- # ⚠ `is_file()` and not `exists()`: a DIRECTORY named `instagram.png` would otherwise
99
- # resolve and then fail inside FileResponse as a 500.
100
- if p.is_file():
101
- return p
102
- return None
103
-
104
-
105
- def available():
106
- """Every brand key that has artwork on disk, sorted. The directory listing this module can
107
- answer cheaply — used by `verify_meta` to assert parity against `BRAND_OF_CONNECTOR` rather than
108
- against a list somebody typed twice."""
109
- keys = set()
110
- for root in _roots():
111
- if not root.is_dir():
112
- continue
113
- for p in root.iterdir():
114
- if p.is_file() and p.suffix in _MEDIA and _KEY_RE.match(p.stem):
115
- keys.add(p.stem)
116
- return sorted(keys)
117
-
118
-
119
- @router.get("/brand/{key}")
120
- def brand_asset(key: str, session: Session = Depends(require_session)):
121
- """R4/C6: one connector's official mark, to any authenticated session.
122
-
123
- ⛔ THREE ANSWERS, AND THE THIRD IS THE ONE THE TICKET ASKS ABOUT: 400 for a key that is not a
124
- key (it never reaches the filesystem), **404 for a key we simply have no art for**, and the file
125
- otherwise. A stack trace is not one of the answers — an unknown key is an ordinary, expected
126
- request from a client whose connector list is longer than our logo set.
127
- ⚠ `session` is required and then unused, which is intentional: the dependency IS the wall, and
128
- naming it in the signature is what puts it there. Deleting the "unused" parameter would open the
129
- route to the internet with no other symptom.
130
- """
131
- if not _KEY_RE.match(str(key or "")):
132
- raise err(400, "bad_brand_key", "that is not a brand key")
133
- p = brand_path(key)
134
- if p is None:
135
- raise err(404, "brand_not_found", f"no brand mark for '{key}'")
136
- return FileResponse(
137
- str(p),
138
- media_type=_MEDIA.get(p.suffix, "application/octet-stream"),
139
- headers={"Cache-Control": _IMMUTABLE},
140
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/routes_publish.py DELETED
@@ -1,812 +0,0 @@
1
- """routes_publish.py — PUBLISH AN INTERFACE VIEW AS A LINK (wave 33, owner item 8b, ruling R5).
2
-
3
- The owner, verbatim: *"Have the ability to publish interface, when a user's view is an interface
4
- (e.g. Map or Catalog), we should have the ability to publish a link that can be either accessed
5
- publicly or with a password that the user that share it can toggle."*
6
-
7
- R5, in five clauses, and every one of them is load-bearing:
8
- * publish = a per-view secret token in a **server-only bucket**;
9
- * a `public | password` toggle the SHARER owns, with a **hashed** passphrase beside it;
10
- * an **unauthenticated** read-only route plus a `#/v/<token>` client route;
11
- * the publish surface **projects only the columns the view shows** — never the whole table;
12
- * **creator-or-admin** may publish, and **revoke ROTATES** the token.
13
-
14
- ⛔ THIS FILE COPIES `routes_forms.py`'S CONSTRUCTION ON PURPOSE, AND THE TICKET SAID TO. That door
15
- has been public since wave 23 and carries scar tissue no fresh design would reproduce: ONE refusal
16
- for every resolution failure (so the route is not an oracle for which tokens are real), a
17
- constant-time compare, a STREAMING body bound rather than `Body(...)` (FastAPI reads and parses the
18
- whole body before the handler's first line, and `content-length` is caller-supplied), a sliding
19
- rate window rather than a fixed bucket, and an index that is a POINTER, never a permission.
20
-
21
- ⚠ WHAT IS DELIBERATELY *NOT* SHARED WITH `routes_forms.py`: the bucket. A form token buys a WRITE
22
- door into a table; a publish token buys a READ projection of one view. Folding them into one index
23
- would make a single leaked string ambiguous about which of the two it opens, and would make
24
- `_resolve` return an object whose capability depends on a field rather than on which door was
25
- knocked. Two buckets, two resolvers, one shape.
26
-
27
- ⚠ AND NOT SHARED WITH SHARING. **Three systems now answer some version of "who can see this"** and
28
- they are not the same question (audit S-4): the grant registry drives *Shared with me*,
29
- `table_store.is_shared` GATES opening a view inside the app, and a published link is a THIRD thing
30
- — an unauthenticated read of a projection, bound to a secret rather than to an account. A published
31
- link is NOT a grant: it creates no registry row, appears in nobody's *Shared with me*, and cannot
32
- be revoked by removing a person, because there is no person.
33
-
34
- python verify_forms.py # this file's gate; section 6 onward
35
- """
36
- import hashlib
37
- import hmac
38
- import os
39
- import secrets
40
- import time
41
-
42
- from fastapi import APIRouter, Depends, Request
43
-
44
- from deps import Session, err, require_session
45
-
46
- router = APIRouter(prefix="/api/v1")
47
-
48
- #: The SERVER-ONLY index: `{token: {table, view, access, pw?, salt?, iter?, createdBy, createdAt}}`.
49
- #: ⛔ IT IS NEVER `display.*`. Contract C1 puts two PRESENTATIONAL flags on the view spec
50
- #: (`published`, `publishAccess`) precisely so the client has something to render, and the browser
51
- #: writes that spec on every autosave — so anything secret living there would be echoed back to the
52
- #: browser by construction. `aios_grid._clean_display`'s allowlist enforces the other half.
53
- TOKENS_KEY = "publish_tokens"
54
- TOKEN_BYTES = 24
55
-
56
- #: Passphrase storage. PBKDF2-HMAC-SHA256 with a per-link salt.
57
- #: ⚠ D-130 IS THE SCAR THIS AVOIDS: a form's "invited addresses" list is IDENTIFICATION — it says
58
- #: who you claim to be and anyone may claim it. A passphrase is AUTHENTICATION. The difference is
59
- #: not a stronger string, it is that the secret is never stored, never logged and never echoed.
60
- PW_ITERATIONS = 240_000
61
- PW_SALT_BYTES = 16
62
- MIN_PASSPHRASE = 6
63
- MAX_PASSPHRASE = 128
64
-
65
- #: v1 request protections, the same shape and the same numbers as the form door (contract C9), so
66
- #: the two public routes cannot drift into different postures. ⚠ In-process, therefore PER WORKER.
67
- RATE_WINDOW_S = 60
68
- RATE_PER_WINDOW = 30
69
- MAX_BODY_BYTES = 16 * 1024
70
-
71
- _HITS: dict = {}
72
-
73
- #: The view kinds that may be published, i.e. R5's "interface".
74
- #: ⚠ THE CLIENT'S SOURCE OF TRUTH IS `customer-grid/iconShapes.ts::MODE_GROUP` (wave 33 item 9
75
- #: moved `swipe` and `timeseries` into this group). This constant is the SERVER's copy and the two
76
- #: are held in step by `verify_forms.py`, which parses `MODE_GROUP` and compares — because a
77
- #: server list that silently drifts from the picker means a mode a user can create and cannot
78
- #: publish, with nothing anywhere going red. A `grid` or `kanban` view is a re-shaping of a row
79
- #: set; publishing one would be publishing the table, which is exactly what R5's projection clause
80
- #: exists to prevent.
81
- PUBLISHABLE_MODES = ("map", "catalog", "form", "swipe", "timeseries")
82
-
83
-
84
- def _refuse():
85
- """THE ONE REFUSAL, for every way a published link can fail to resolve.
86
-
87
- Wrong token, revoked link, deleted view, deleted table, a view that stopped being an
88
- interface, a wrong passphrase. ⛔ Callers must not branch a more specific message out of it:
89
- the difference between "no such link" and "that link was revoked" tells an enumerator which
90
- tokens are real, and the difference between "no such link" and "wrong passphrase" tells them
91
- which links are worth guessing at.
92
- """
93
- return err(403, "bad_publish_token", "that link is not valid")
94
-
95
-
96
- def _same(a: str, b: str) -> bool:
97
- """Constant-time. A `==` leaks a secret's prefix through timing, one character at a time."""
98
- return hmac.compare_digest(str(a or ""), str(b or ""))
99
-
100
-
101
- def _client_ip(request: Request) -> str:
102
- """⚠ Caller-controlled, therefore a rate-limit key and NOTHING else — never a permission."""
103
- fwd = request.headers.get("x-forwarded-for") or ""
104
- first = fwd.split(",")[0].strip()
105
- return first or (request.client.host if request.client else "?")
106
-
107
-
108
- def _rate_ok(ip: str, now: float) -> bool:
109
- """A SLIDING window. A fixed bucket lets a caller spend a whole allowance at 11:59:59 and the
110
- whole next one at 12:00:00 — i.e. double the limit, back to back, against a door whose entire
111
- protection is that guessing a 24-byte token is slow."""
112
- seen = [t for t in _HITS.get(ip, ()) if now - t < RATE_WINDOW_S]
113
- seen.append(now)
114
- _HITS[ip] = seen
115
- if len(_HITS) > 4096:
116
- for k in [k for k, v in _HITS.items() if not v or now - v[-1] > RATE_WINDOW_S]:
117
- _HITS.pop(k, None)
118
- return len(seen) <= RATE_PER_WINDOW
119
-
120
-
121
- def _public_base() -> str:
122
- return (os.environ.get("AIOS_PUBLIC_BASE") or os.environ.get("APP_BASE_URL") or "").rstrip("/")
123
-
124
-
125
- def _link_of(token: str) -> str:
126
- return f"{_public_base()}/#/v/{token}"
127
-
128
-
129
- def _tokens(rt) -> dict:
130
- """This tenant's publish index, always a dict."""
131
- try:
132
- found = rt.get(TOKENS_KEY) or {}
133
- except Exception: # noqa: BLE001
134
- return {}
135
- return found if isinstance(found, dict) else {}
136
-
137
-
138
- def _hash_pw(passphrase: str, salt: bytes, iterations: int = PW_ITERATIONS) -> str:
139
- return hashlib.pbkdf2_hmac("sha256", str(passphrase).encode("utf-8"),
140
- salt, int(iterations)).hex()
141
-
142
-
143
- def _pw_ok(entry: dict, passphrase: str) -> bool:
144
- """Constant-time verify against the stored digest.
145
-
146
- ⛔ RETURNS FALSE, NEVER RAISES, and never distinguishes "this link has no passphrase stored"
147
- from "the passphrase is wrong" — a `password` link whose hash went missing must refuse, not
148
- fall open. [[default-must-pass-its-own-guard]]
149
- """
150
- stored, salt_hex = str(entry.get("pw") or ""), str(entry.get("salt") or "")
151
- if not stored or not salt_hex:
152
- return False
153
- try:
154
- salt = bytes.fromhex(salt_hex)
155
- except ValueError:
156
- return False
157
- got = _hash_pw(passphrase, salt, int(entry.get("iter") or PW_ITERATIONS))
158
- return _same(got, stored)
159
-
160
-
161
- def _find_view(rt, table_key: str, view_id: str):
162
- """`(view, owner_username)` from the table's workspace bucket, or `(None, "")`.
163
-
164
- The bucket shape is `{username: {views: {id: view}}}` — the same walk `routes_forms._find_view`
165
- does, and the reason a view is addressable by id ALONE here: the id is unique within the table,
166
- while the owner is what we are trying to discover.
167
- """
168
- if not table_key or not view_id:
169
- return None, ""
170
- try:
171
- bucket = rt.get(f"{table_key}_table_workspace") or {}
172
- except Exception: # noqa: BLE001
173
- return None, ""
174
- if not isinstance(bucket, dict):
175
- return None, ""
176
- for owner, blob in bucket.items():
177
- views = (blob or {}).get("views") if isinstance(blob, dict) else None
178
- if isinstance(views, dict) and isinstance(views.get(view_id), dict):
179
- return views[view_id], str(owner)
180
- return None, ""
181
-
182
-
183
- def _mode_of(view: dict) -> str:
184
- """The view's display mode. Absent means `grid` — the stored default is "say nothing"."""
185
- cfg = (view or {}).get("config") if isinstance(view, dict) else None
186
- disp = (cfg or {}).get("display") if isinstance(cfg, dict) else None
187
- return str((disp or {}).get("mode") or "grid") if isinstance(disp, dict) else "grid"
188
-
189
-
190
- def _may_administer_view(session: Session, table_key: str, view_id: str):
191
- """`(view, mode)` when this caller may publish THIS view, else raises. R5's creator-or-admin.
192
-
193
- ⛔ `session.uname` / `session.admin`, NOT `username` / `is_admin`. `Session` has no such
194
- attributes, and reading one raises ABOVE this route's own `try:` — which is how D-107 arrived
195
- as a bare plain-text 500 rather than as our JSON envelope.
196
- """
197
- import core.table_store as table_store
198
-
199
- if not table_key.startswith("ut_"):
200
- # The Odoo/registry grids are read-through mirrors with their own permission wall; a
201
- # published projection of one would be a second, secret-gated door onto tenant data whose
202
- # visibility the module gate is supposed to decide.
203
- raise err(400, "not_a_database", "you can publish views on your own databases only")
204
- # ⛔ A READ-THROUGH DATABASE CANNOT BE PUBLISHED, AND THE REFUSAL SAYS SO RATHER THAN MINTING
205
- # A LINK THAT WILL NOT OPEN. `startswith("ut_")` admits `ut_odoo_*` and `ut_meta_*`, whose rows
206
- # do not live in the tenant document at all — they are windowed out of the DuckDB mirror
207
- # through a Session-bound path (`ut_assembly`, which 409s `window_required` on the big ones,
208
- # D-174's lineage). An unauthenticated route has no session and therefore no such path, so a
209
- # token minted here would resolve to a page that could never render.
210
- # ⚠ THIS IS R6's SECOND SENTENCE, WHICH IS THE HALF THAT GETS DROPPED: a limit that genuinely
211
- # cannot be removed must be REPORTED, with its cause, never silently enforced. Refusing at the
212
- # MINT — where a person is standing in front of the answer — is the only place that reads as a
213
- # sentence rather than as an empty page.
214
- import core.user_tables as user_tables
215
-
216
- if user_tables.is_connected(table_key, st=session.runtime):
217
- raise err(400, "connected_source",
218
- "a database that reads through a connected source (Odoo, Meta Ads) cannot be "
219
- "published as a public link: its rows are served from the tenant's mirror by a "
220
- "signed-in request, and a public link has no session to serve them with")
221
- view, owner = _find_view(session.runtime, table_key, view_id)
222
- if not isinstance(view, dict):
223
- raise err(404, "no_such_view", "that view no longer exists")
224
- if not (owner == session.uname
225
- or table_store._may_administer(view, session.uname, session.admin)):
226
- raise err(403, "not_yours", "only this view's creator or an admin can publish it")
227
- mode = _mode_of(view)
228
- if mode not in PUBLISHABLE_MODES:
229
- raise err(400, "not_an_interface",
230
- "only an interface view (Map, Catalog, Swipe, Time-series, Form) can be "
231
- "published as a link")
232
- cfg = view.get("config") or {}
233
- if cfg.get("cohortLock"):
234
- raise err(400, "reader_scoped",
235
- "this view is locked to a cohort, and a cohort's membership is resolved for "
236
- "the person reading it — a public link has no reader, so the page would show "
237
- "no rows at all. Publish a copy without the cohort lock.")
238
- if _needs_a_reader(cfg.get("filters")):
239
- raise err(400, "reader_scoped",
240
- "this view filters on a cohort, a measure rule or a top-N slice, and each of "
241
- "those is resolved for the person reading it — a public link has no reader, so "
242
- "the page would show no rows at all. Publish a copy filtered on columns.")
243
- return view, mode
244
-
245
-
246
- #: How many rows a published page will serve. ⚠ R6 (no cap on connected-source data) does not
247
- #: reach here twice over: a publishable database is `records_mutable`, i.e. the EDITABLE substrate
248
- #: that keeps its bound (`user_tables.MAX_ROWS`), and a connected one is refused at the mint. What
249
- #: R6's SECOND sentence does reach here is the reporting duty — a page that serves fewer rows than
250
- #: the view has must SAY SO on the wire, with the cause, never just stop.
251
- PUBLIC_ROW_CAP = 5000
252
-
253
-
254
- def _needs_a_reader(tree) -> bool:
255
- """Does this filter tree contain a leaf that only a SIGNED-IN reader could resolve?
256
-
257
- ⛔ COHORTS, MEASURE RULES AND RANK SLICES ARE NOT PROPERTIES OF THE VIEW. Each is a SET the
258
- host computes for the person asking — `filter_eval.EvalCtx`'s own docstring: *"each is an
259
- answer a single ROW cannot compute … absent, the condition matches NOTHING rather than
260
- everything"*. That default is right (it fails closed) and it is unusable here: an anonymous
261
- page whose every row was silently filtered out is indistinguishable from a broken link, and
262
- the reader has nobody to ask. Worse, `rank_sets` has NO server-side resolver anywhere in this
263
- repo — `routes_alerts._evaluate` passes cohort/measure/today and nothing else — so a `topN`
264
- view would serve zero rows on the server while showing twenty in the browser.
265
-
266
- ⭐ So such a view is refused AT THE MINT, where a person is standing in front of the answer.
267
- That is R6's second sentence: a limit that genuinely cannot be removed is REPORTED with its
268
- cause, never silently enforced.
269
-
270
- ⚠ THE PREDICATES ARE `filter_eval`'S OWN. Re-implementing "is this a cohort leaf?" here would
271
- be a second evaluator that agrees today and drifts the day the leaf shape changes — and it
272
- would drift SILENTLY, because the two answers only differ on views nobody has published yet.
273
- [[one-evaluator-per-question]]
274
- """
275
- from harness import filter_eval
276
-
277
- def walk(node) -> bool:
278
- if isinstance(node, list):
279
- return any(walk(n) for n in node)
280
- if not isinstance(node, dict):
281
- return False
282
- if node.get("kind") == "group" or isinstance(node.get("children"), list):
283
- return any(walk(n) for n in (node.get("children") or []))
284
- if filter_eval._is_cohort(node) or filter_eval._is_measure(node):
285
- return True
286
- return node.get("op") in filter_eval.RANK_OPS
287
-
288
- return walk(tree)
289
-
290
-
291
- def _mirror_display(rt, table_key: str, view_id: str, published: bool, access: str = "password"):
292
- """Keep contract C1's two PRESENTATIONAL flags on the stored view in step with this bucket.
293
-
294
- ⛔ WHY THIS EXISTS AT ALL, and it was found by a reviewer rather than by a gate: revoking a
295
- link dropped the token and left `config.display.published: true` on the view, so the grid's
296
- own UI would go on saying "published" about a link that no longer resolves. Two records of one
297
- fact, and only one of them moving, is the [[flag-shipped-without-its-writer]] shape — here with
298
- the writer present and the OTHER half forgotten.
299
-
300
- ⚠ THE BUCKET REMAINS THE TRUTH. These flags exist so the client has something to render
301
- without asking; they are a MIRROR, never a source, and nothing in this module reads them back
302
- to decide anything. `read_view_link` deliberately reports both so a drift is visible rather
303
- than assumed away.
304
-
305
- ⚠ ONLY THE TWO LEGAL KEYS ARE WRITTEN, with E's fail-closed coercion reproduced exactly
306
- (`aios_grid._clean_display`: `published: True` always carries a `publishAccess`, and anything
307
- that is not the literal `public` stores as `password`) — so a value written here and a value
308
- written by the browser cannot disagree.
309
- """
310
- def _set(cur):
311
- cur = dict(cur or {})
312
- for owner, blob in list(cur.items()):
313
- views = (blob or {}).get("views") if isinstance(blob, dict) else None
314
- view = views.get(view_id) if isinstance(views, dict) else None
315
- if not isinstance(view, dict):
316
- continue
317
- cfg = dict(view.get("config") or {})
318
- disp = dict(cfg.get("display") or {})
319
- if not disp.get("mode"):
320
- # No display block means no interface view; nothing here should invent one.
321
- continue
322
- if published:
323
- disp["published"] = True
324
- disp["publishAccess"] = "public" if access == "public" else "password"
325
- else:
326
- disp.pop("published", None)
327
- disp.pop("publishAccess", None)
328
- cfg["display"] = disp
329
- cur[owner] = {**blob, "views": {**views, view_id: {**view, "config": cfg}}}
330
- return cur
331
-
332
- try:
333
- rt.update(f"{table_key}_table_workspace", _set, flush="sync")
334
- except Exception: # noqa: BLE001
335
- # ⚠ SWALLOWED, and deliberately: the token bucket is the truth and it has already been
336
- # written. A mirror that failed to update leaves the UI one refresh out of date, which is
337
- # strictly better than a 500 on a publish that actually succeeded.
338
- pass
339
-
340
-
341
- def _entry_for(rt, table_key: str, view_id: str):
342
- """`(token, entry)` for a view's existing link, or `(None, None)`."""
343
- for token, where in _tokens(rt).items():
344
- if (isinstance(where, dict) and where.get("table") == table_key
345
- and where.get("view") == view_id):
346
- return str(token), where
347
- return None, None
348
-
349
-
350
- def _state_of(token, entry) -> dict:
351
- """The link's state as the SHARER may see it. Built key by key.
352
-
353
- ⛔ NO `**entry`. The stored blob carries `pw` and `salt`; a spread would put both on the wire
354
- to the browser, which is the whole failure this file's bucket exists to avoid, and it would do
355
- it silently the first time somebody added a field.
356
- """
357
- if not token or not isinstance(entry, dict):
358
- return {"published": False, "access": "password", "token": "", "url": ""}
359
- return {
360
- "published": True,
361
- "access": "public" if entry.get("access") == "public" else "password",
362
- "token": str(token),
363
- "url": _link_of(str(token)),
364
- # A boolean, never the digest and never the salt.
365
- "hasPassphrase": bool(entry.get("pw")),
366
- "createdBy": str(entry.get("createdBy") or ""),
367
- }
368
-
369
-
370
- def _resolve(token: str):
371
- """`(runtime, tenant_slug, table_key, view, entry)` for a token, or None.
372
-
373
- ⛔ THE INDEX IS A POINTER, NEVER A PERMISSION. Holding a token means the sharer minted it for
374
- THIS view; it does not mean the holder may read anything else, and nothing downstream of here
375
- may widen the subject beyond the `(table, view)` pair the entry names.
376
-
377
- ⚠ IT WALKS EVERY TENANT, because an unauthenticated request carries no tenant. That is the
378
- form door's shape too, and the reason `_same` is constant-time: the walk compares the caller's
379
- string against every stored token in the deployment.
380
- """
381
- from harness import runtime as _rt
382
-
383
- if not token or len(token) < 16:
384
- return None
385
- for slug in _rt.known_tenants():
386
- try:
387
- rt = _rt.get_runtime(slug)
388
- except Exception: # noqa: BLE001
389
- continue
390
- for stored, where in _tokens(rt).items():
391
- if not _same(str(stored), token) or not isinstance(where, dict):
392
- continue
393
- table_key = str(where.get("table") or "")
394
- view, _owner = _find_view(rt, table_key, str(where.get("view") or ""))
395
- # A view deleted, or re-saved as a grid, since the link was minted. Both answer the
396
- # ONE refusal — "that link is not valid" — rather than explaining which.
397
- if not table_key or not isinstance(view, dict):
398
- return None
399
- if _mode_of(view) not in PUBLISHABLE_MODES:
400
- return None
401
- return rt, slug, table_key, view, where
402
- return None
403
-
404
-
405
- def _coord(value, limit: float):
406
- """A real coordinate, or `None`. THE WALL that lets a map publish without publishing a column.
407
-
408
- ⛔ A VALUE TEST, NEVER A NAME TEST. A field merely CALLED `lat` proves nothing — a verifier put
409
- the string `CANARY-LAT-AAA` in one and watched it reach the wire under the first version of
410
- this code. Anything that is not a finite number inside the earth's range is not a location and
411
- does not travel.
412
- ⚠ `bool` is rejected explicitly: `isinstance(True, int)` is True in Python, and `float(True)`
413
- is `1.0` — a checkbox column named `lat` would otherwise publish as a point off the coast of
414
- Ghana.
415
- """
416
- if value is None or isinstance(value, bool):
417
- return None
418
- try:
419
- n = float(value)
420
- except (TypeError, ValueError):
421
- return None
422
- return n if n == n and abs(n) <= limit else None
423
-
424
-
425
- def _visible_keys(view: dict, fields: list) -> list:
426
- """The columns this view SHOWS, in the view's own order. R5's projection clause, in one place.
427
-
428
- ⛔ `config.order` IS NOT THE ANSWER AND IS THE OBVIOUS WRONG ONE. `aios_grid._default_view_config`
429
- builds `order` as `shown + hidden`, and `grid_events`' `view_upsert` APPENDS every remaining
430
- field to it — so `order` is every column the table has, hidden ones included. `visible` is the
431
- only allowlist that exists; there is no stored "hidden" key to subtract.
432
-
433
- ⚠ AND AN EMPTY `visible` IS NOT "NO COLUMNS". `CustomerGrid` falls back to the table's default
434
- set when a saved view carries none, so a public page that read `[]` as an empty allowlist would
435
- render blank — and one that read it as "all fields" would LEAK. The fallback is the same
436
- predicate the default config uses (`field.default is not False`), taken from `aios_grid` rather
437
- than restated here.
438
- """
439
- import aios_grid
440
-
441
- by_key = {str(f.get("key")): f for f in fields if isinstance(f, dict)}
442
- stored = [str(k) for k in (((view or {}).get("config") or {}).get("visible") or [])]
443
- keep = [k for k in stored if k in by_key]
444
- if keep:
445
- return keep
446
- try:
447
- default_visible = (aios_grid._default_view_config(fields) or {}).get("visible") or []
448
- except Exception: # noqa: BLE001
449
- default_visible = []
450
- fallback = [str(k) for k in default_visible if str(k) in by_key]
451
- return fallback or [str(f.get("key")) for f in fields if f.get("default") is not False]
452
-
453
-
454
- def _public_view(rt, table_key: str, view: dict) -> dict:
455
- """The ONLY bytes a valid token buys. Built KEY BY KEY — there is no `**row` in this function.
456
-
457
- ⛔ THE REASON THAT IS A RULE AND NOT A STYLE. `aios_grid.rows_from_pool` puts `pid`, `_created`,
458
- `lat` and `lon` on EVERY row regardless of what the view shows, and the stored row dict carries
459
- every column the table has. Serialising a row and deleting the fields we do not want inverts
460
- the failure: a column added next wave is INCLUDED by default and nobody notices, whereas an
461
- allowlist that has not learned about it merely omits it. `routes_forms._public_form` is the
462
- shipped precedent and says the same thing about itself.
463
- """
464
- import core.user_tables as user_tables
465
- from harness import filter_eval
466
-
467
- defn = user_tables.get(table_key, st=rt) or {}
468
- fields = [f for f in (defn.get("fields") or []) if isinstance(f, dict)]
469
- by_key = {str(f.get("key")): f for f in fields}
470
- keys = _visible_keys(view, fields)
471
- cfg = (view or {}).get("config") or {}
472
-
473
- # The row pool: the table's own rows, narrowed to the fields it declares, exactly as
474
- # `routes_tables.scoped_pool` builds it for a materialised table. ⚠ A read-through table has
475
- # no rows here and is refused at the MINT, so this branch is the only one that can be reached.
476
- rows_src = []
477
- for rid, row in (defn.get("rows") or {}).items():
478
- if not str(rid).isdigit():
479
- continue
480
- r = {k: v for k, v in (row or {}).items() if k in by_key}
481
- r["pid"] = int(rid)
482
- rows_src.append(r)
483
- rows_src.sort(key=lambda r: r["pid"])
484
-
485
- # The view's own row selection, through the SHARED evaluator. `_needs_a_reader` has already
486
- # refused anything this context could not answer, so an empty result here means the filter
487
- # genuinely matches nothing — not that we failed to resolve it.
488
- ctx = filter_eval.EvalCtx(today=time.strftime("%Y-%m-%d"))
489
- keep = set(filter_eval.visible_pids(cfg.get("filters"), rows_src, fields, ctx,
490
- member_pids=cfg.get("memberPids")))
491
- chosen = [r for r in rows_src if r.get("pid") in keep]
492
-
493
- # ⛔⛔ COORDINATES RIDE A MAP WHEN THEY ARE COORDINATES — NOT WHEN THEY ARE VISIBLE, AND NOT
494
- # BECAUSE OF WHAT A COLUMN IS CALLED. Two verifiers, one from each side, are why this reads
495
- # the way it does; the first fix I wrote was wrong and the second report proved it.
496
- #
497
- # ⚠ THE LEAK (verifier #1, driven): a HIDDEN field keyed `lat` holding the string
498
- # `CANARY-LAT-AAA` came out on the wire, because the pair was emitted before the `keys`
499
- # projection and the bypass keyed on the FIELD NAME rather than on the value being a
500
- # coordinate. So a column called `lat` could carry anything — a note, an address — and publish
501
- # it. That is the real defect.
502
- #
503
- # ⛔ MY FIRST FIX GATED ON VISIBILITY, AND IT BROKE THE FEATURE (verifier #2): hiding the raw
504
- # decimals is the NORMAL way somebody builds a Map view — nobody wants `38.7223` in the column
505
- # list — so gating on `visible` meant an ordinary map published a page with no map, under two
506
- # messages that contradicted each other ("no rows carry a location" vs "this view hides its
507
- # location columns").
508
- #
509
- # ⭐ THE RULE THAT SATISFIES BOTH: publishing a MAP is publishing WHERE THE ROWS ARE — that is
510
- # what the sharer chose — so a real coordinate rides whether or not its column is shown, and a
511
- # value that is not a coordinate never rides at all. `_coord` is the whole wall, and it is a
512
- # VALUE test, so no naming convention can smuggle anything past it.
513
- # ⚠ It mirrors `PublishedView.MapPlot`'s own `coord()` deliberately: the client must not plot
514
- # what the server would not send, and the server must not send what the client would discard.
515
- # Two normalizers on one question is a smell [[one-question-two-normalizers]] — kept here
516
- # because they sit on opposite sides of a trust boundary, where the server's copy is the wall
517
- # and the client's is display hygiene.
518
- mode = _mode_of(view)
519
- plotted = 0
520
- if mode == "map":
521
- for r in chosen:
522
- if _coord(r.get("lat"), 90) is not None and _coord(r.get("lon"), 180) is not None:
523
- plotted += 1
524
-
525
- limits = []
526
- if mode == "map" and chosen and not plotted:
527
- # R6's second sentence. A map with nothing on it must say WHY — and this says the true
528
- # why, which is about the DATA, because visibility is no longer part of the answer.
529
- limits.append({
530
- "subject": "map", "effect": "not_plotted",
531
- "detail": f"none of these {len(chosen)} rows carry a usable location",
532
- "recommendation": "add `lat` and `lon` values to the records, then reload this link",
533
- })
534
- if len(chosen) > PUBLIC_ROW_CAP:
535
- # R6's second sentence. A short page that does not say it is short is the silent
536
- # truncation the rule is actually about.
537
- limits.append({
538
- "subject": "rows", "effect": "windowed",
539
- "detail": f"this view has {len(chosen)} rows and a published page serves the first "
540
- f"{PUBLIC_ROW_CAP}",
541
- "recommendation": "narrow the view's filters, or share it with named people instead "
542
- "of publishing a link",
543
- })
544
- chosen = chosen[:PUBLIC_ROW_CAP]
545
-
546
- # ⛔ THE DISPLAY REFS ARE INTERSECTED WITH `visible`, NOT UNIONED INTO IT. A Map that colours
547
- # by a column the view HIDES would otherwise put that column's value on every public row —
548
- # the projection leak, arriving through the renderer rather than through the column list. The
549
- # fail-closed choice is to drop the ref and render the map without colour; a published page
550
- # that is slightly plainer beats one that ships a hidden column.
551
- disp_in = (cfg.get("display") or {})
552
- display = {"mode": mode}
553
- for ref in ("dateField", "stackField", "titleField", "colorField", "sizeField"):
554
- if disp_in.get(ref) in keys:
555
- display[ref] = disp_in[ref]
556
-
557
- return {
558
- "title": str((view or {}).get("name") or "")[:200],
559
- "mode": display["mode"],
560
- "display": display,
561
- "columns": [{"key": k,
562
- "label": str(by_key[k].get("label") or k),
563
- "type": str(by_key[k].get("type") or "text"),
564
- **({"options": [str(o) for o in by_key[k]["options"]][:200]}
565
- if isinstance(by_key[k].get("options"), list) and by_key[k].get("options")
566
- else {})}
567
- for k in keys],
568
- # KEY BY KEY. `pid` rides because the client needs a stable row identity to render a list;
569
- # it is a row NUMBER within this table and names nothing outside it.
570
- # ⛔⛔ `lat`/`lon` RIDE ONLY ON A MAP **AND ONLY WHEN THE VIEW SHOWS THEM** — and the second
571
- # half was missing, which was a LEAK. Found by a verifier that drove this route with a
572
- # hidden field keyed `lat` carrying the string `CANARY-LAT-AAA`, and watched it come out
573
- # on the wire.
574
- #
575
- # The first version emitted the pair BEFORE the `keys` projection, so `_visible_keys` never
576
- # gated it. On a `ut_*` table coordinates are not magic: `routes_tables.scoped_pool` builds
577
- # its row as `{k: v for k, v in row.items() if k in field_keys}`, so a value only survives
578
- # if the table DECLARES a field keyed `lat`/`lon` — i.e. they are ORDINARY COLUMNS, and a
579
- # view can hide them like any other. Hiding them therefore has to work here, because on a
580
- # published page **the projection is the only wall there is** (`ut_*` databases have no
581
- # hidden-field closure behind it, `routes_shares.py`'s docstring).
582
- #
583
- # ⚠ The bypass was keyed on the FIELD NAME, never on the value being a coordinate, so it
584
- # forwarded whatever a column called `lat` happened to hold — a string, a note, anything.
585
- # ⚠ And the shipped gate could not see it: it asserted the key NAMES rode on a map and not
586
- # on a catalog, over a fixture whose rows carried no `lat` key at all — so it pinned the
587
- # names while both values were `None` [[gate-answers-the-wrong-question]].
588
- # KEY BY KEY. `pid` rides because the client needs a stable row identity; it is a row
589
- # NUMBER within this table and names nothing outside it. `lat`/`lon` ride only on a map,
590
- # and only when they PARSE as coordinates — see the block above for why that is the test.
591
- "rows": [{"pid": r.get("pid"),
592
- **({"lat": _coord(r.get("lat"), 90), "lon": _coord(r.get("lon"), 180)}
593
- if mode == "map"
594
- and _coord(r.get("lat"), 90) is not None
595
- and _coord(r.get("lon"), 180) is not None else {}),
596
- **{k: r.get(k) for k in keys}} for r in chosen],
597
- "total": len(chosen),
598
- **({"limits": limits} if limits else {}),
599
- }
600
-
601
-
602
- async def _bounded_body(request: Request) -> dict:
603
- """The request body, read WITH A BOUND — never `Body(...)`, never `await request.body()`.
604
-
605
- FastAPI reads and JSON-parses the WHOLE body before the handler's first line runs, so a
606
- declared model is not a bound at all; `content-length` is caller-supplied, so checking it is
607
- not one either. Streaming with a running total is the actual bound.
608
- """
609
- size, chunks = 0, []
610
- async for chunk in request.stream():
611
- size += len(chunk)
612
- if size > MAX_BODY_BYTES:
613
- raise err(413, "body_too_large", "that request is too large")
614
- chunks.append(chunk)
615
- import json
616
- try:
617
- parsed = json.loads(b"".join(chunks) or b"{}")
618
- except ValueError:
619
- raise err(400, "bad_request", "that request could not be read")
620
- return parsed if isinstance(parsed, dict) else {}
621
-
622
-
623
- # ── THE SHARER'S DOOR (authenticated, creator-or-admin) ──────────────────────────────────────
624
- #
625
- # ⚠ THE NOUN IS `/view-link`, DELIBERATELY NOT `/views/{...}/publish`, and it mirrors the form
626
- # door's `/form-link` for the same reason: a literal path segment sitting beside a `/{token}`
627
- # wildcard is resolved by DECLARATION ORDER, and a noun that cannot collide with a token has no
628
- # order to get wrong.
629
-
630
-
631
- @router.get("/view-link")
632
- def read_view_link(topic: str = "", view: str = "",
633
- session: Session = Depends(require_session)):
634
- """This view's link state. ⛔ A GET MUST NOT MINT — opening the panel is not publishing."""
635
- v, _mode = _may_administer_view(session, str(topic or ""), str(view or ""))
636
- token, entry = _entry_for(session.runtime, str(topic), str(view))
637
- out = _state_of(token, entry)
638
- # The presentational flags contract C1 put on the view spec, echoed back so the client can
639
- # tell whether the two agree. They are a MIRROR of this bucket, never its source.
640
- disp = ((v.get("config") or {}).get("display") or {}) if isinstance(v, dict) else {}
641
- out["displayPublished"] = disp.get("published") is True
642
- return out
643
-
644
-
645
- @router.post("/view-link")
646
- async def mint_view_link(request: Request, session: Session = Depends(require_session)):
647
- """Publish this view, or change its access. `{topic, view, access?, passphrase?, rotate?}`.
648
-
649
- IDEMPOTENT WITHOUT `rotate`: opening the panel twice, or switching public↔password, must not
650
- invalidate a link somebody already sent. `rotate: true` mints a fresh token and the previous
651
- one dies in the SAME write, so there is never a window where both open the view.
652
- """
653
- body = await _bounded_body(request)
654
- topic, view = str(body.get("topic") or ""), str(body.get("view") or "")
655
- _v, _mode = _may_administer_view(session, topic, view)
656
-
657
- access = "public" if body.get("access") == "public" else "password"
658
- raw_pw = body.get("passphrase")
659
- passphrase = "" if raw_pw is None else str(raw_pw)
660
- if len(passphrase) > MAX_PASSPHRASE:
661
- raise err(400, "passphrase_too_long",
662
- f"a passphrase can be at most {MAX_PASSPHRASE} characters")
663
-
664
- existing_token, existing = _entry_for(session.runtime, topic, view)
665
- rotate = bool(body.get("rotate"))
666
- fresh = secrets.token_urlsafe(TOKEN_BYTES)
667
-
668
- # ⛔ A `password` LINK MUST END UP WITH A HASH, and there are exactly two ways to have one:
669
- # the caller supplied a passphrase now, or one was already stored and is being kept. Anything
670
- # else is refused HERE rather than stored and refused later — a link that cannot be opened by
671
- # anybody is not a safe default, it is a broken feature that reads as a permission bug.
672
- if access == "password":
673
- if passphrase and len(passphrase) < MIN_PASSPHRASE:
674
- raise err(400, "passphrase_too_short",
675
- f"a passphrase needs at least {MIN_PASSPHRASE} characters")
676
- if not passphrase and not (existing or {}).get("pw"):
677
- raise err(400, "passphrase_required",
678
- "a password-protected link needs a passphrase")
679
-
680
- minted = {"token": existing_token or fresh}
681
-
682
- def _set(cur):
683
- cur = dict(cur or {})
684
- prev = None
685
- for stored, where in list(cur.items()):
686
- if (isinstance(where, dict) and where.get("table") == topic
687
- and where.get("view") == view):
688
- prev = dict(where)
689
- cur.pop(stored, None)
690
- if not rotate:
691
- minted["token"] = str(stored)
692
- if rotate or prev is None:
693
- minted["token"] = fresh
694
- entry = {"table": topic, "view": view, "access": access,
695
- "createdBy": str((prev or {}).get("createdBy") or session.uname),
696
- "createdAt": float((prev or {}).get("createdAt") or time.time())}
697
- # ⛔ THE STORED PASSPHRASE SURVIVES A TRIP THROUGH `public`, and the first version DROPPED
698
- # it — found by a verifier that traced the toggle rather than the happy path. Publishing
699
- # as `public` skipped this block entirely, so the hash was destroyed while the TOKEN was
700
- # kept; switching back to `password` then demanded a new passphrase, silently, while the
701
- # panel's own sentence promised the opposite ("leave blank to keep the current one").
702
- # ⚠ Carrying it is inert, not lax: `_pw_ok` is consulted ONLY when `access == "password"`
703
- # (`get_published`/`open_published` both test it first), and `_state_of` exposes a boolean,
704
- # never the digest. A hash nobody can reach is not a secret in use — but a promise the UI
705
- # makes and the store breaks is a defect either way, and the honest fix is to keep the
706
- # promise rather than to reword it.
707
- if passphrase:
708
- salt = secrets.token_bytes(PW_SALT_BYTES)
709
- entry["salt"] = salt.hex()
710
- entry["iter"] = PW_ITERATIONS
711
- entry["pw"] = _hash_pw(passphrase, salt)
712
- elif (prev or {}).get("pw"):
713
- # Carried key by key, so a future field on the entry is not silently inherited.
714
- entry["salt"] = str((prev or {}).get("salt") or "")
715
- entry["iter"] = int((prev or {}).get("iter") or PW_ITERATIONS)
716
- entry["pw"] = str((prev or {}).get("pw") or "")
717
- cur[minted["token"]] = entry
718
- return cur
719
-
720
- session.runtime.update(TOKENS_KEY, _set, flush="sync")
721
- _mirror_display(session.runtime, topic, view, True, access)
722
- token, entry = _entry_for(session.runtime, topic, view)
723
- # ⛔ NO FABRICATED FALLBACK ENTRY HERE. The first version answered
724
- # `_state_of(token or minted["token"], entry or {"access": access, "pw": "x"})`, and that
725
- # `"pw": "x"` would have reported `hasPassphrase: true` about a PUBLIC link if the read-back
726
- # ever came back empty — a lie in the safe-looking direction, which is the kind that survives.
727
- # If the write cannot be read back, say so; do not describe a state nobody verified.
728
- if not entry:
729
- raise err(503, "not_saved",
730
- "the link was minted but could not be read back — reload and try again")
731
- return _state_of(token, entry)
732
-
733
-
734
- @router.delete("/view-link")
735
- async def revoke_view_link(request: Request, session: Session = Depends(require_session)):
736
- """Unpublish. `{topic, view}`.
737
-
738
- ⛔ REVOKE ROTATES — it does not merely unset a flag. The token STRING is dropped from the
739
- index in this write, so the old link stops resolving immediately; and because a later publish
740
- mints `secrets.token_urlsafe(24)` afresh, the revoked string can never come back. An
741
- implementation that kept the token and flipped an `enabled` flag would leave the secret live
742
- in the store, one bug away from working again, and would make "revoked" a property somebody
743
- could forget to check on a code path added later.
744
- """
745
- body = await _bounded_body(request)
746
- topic, view = str(body.get("topic") or ""), str(body.get("view") or "")
747
- _may_administer_view(session, topic, view)
748
-
749
- def _drop(cur):
750
- cur = dict(cur or {})
751
- for stored, where in list(cur.items()):
752
- if (isinstance(where, dict) and where.get("table") == topic
753
- and where.get("view") == view):
754
- cur.pop(stored, None)
755
- return cur
756
-
757
- session.runtime.update(TOKENS_KEY, _drop, flush="sync")
758
- # ⛔ AND THE MIRROR COMES DOWN IN THE SAME BREATH. Without this the grid goes on showing
759
- # "published" about a link that no longer resolves — the half a reviewer caught.
760
- _mirror_display(session.runtime, topic, view, False)
761
- return {"published": False, "access": "password", "token": "", "url": ""}
762
-
763
-
764
- # ── THE PUBLIC DOOR (no session — this is the whole feature) ─────────────────────────────────
765
- #
766
- # ⛔ NO `Depends(require_session)` ON EITHER ROUTE BELOW, DELIBERATELY. "Public" in this app is not
767
- # a flag or an allow-list entry — `main.py` has no auth middleware and no exempt-path table; a
768
- # route is public exactly by omitting the dependency. Which is why the two are kept together,
769
- # under one banner, rather than filed beside the sharer's routes they resemble.
770
-
771
-
772
- @router.get("/published/{token}")
773
- def get_published(token: str, request: Request):
774
- """The published view. Read-only, unauthenticated, projected to the view's own columns."""
775
- if not _rate_ok(_client_ip(request), time.time()):
776
- raise err(429, "too_many_requests", "too many requests — wait a moment and try again")
777
- found = _resolve(token)
778
- if not found:
779
- raise _refuse()
780
- rt, _slug, table_key, view, entry = found
781
- if entry.get("access") == "password":
782
- # ⛔ THE SHAPE OF THE PASSWORD ANSWER, and it is not a refusal. A locked link must render
783
- # a passphrase prompt, so this 200 says "there is something here and it is locked" and
784
- # NOTHING else — no title, no column names, no row count. A 403 here would be
785
- # indistinguishable from a bad token, which is right for a WRONG passphrase and wrong for
786
- # a link the holder has not tried to open yet.
787
- return {"locked": True}
788
- return _public_view(rt, table_key, view)
789
-
790
-
791
- @router.post("/published/{token}")
792
- async def open_published(token: str, request: Request):
793
- """Open a password-protected link. `{passphrase}`.
794
-
795
- ⛔ A WRONG PASSPHRASE AND A WRONG TOKEN ANSWER THE SAME 403, from the same `_refuse`. If they
796
- differed, the route would confirm which tokens are real to anybody willing to send one guess —
797
- and a 24-byte token's entire protection is that it cannot be found by guessing.
798
- ⚠ The passphrase is compared against a PBKDF2 digest with `hmac.compare_digest`, and is never
799
- stored, logged or echoed. D-130's scar: a form's invited-address list is IDENTIFICATION and
800
- anyone may claim an identity; this is AUTHENTICATION and is treated as one.
801
- """
802
- now = time.time()
803
- if not _rate_ok(_client_ip(request), now):
804
- raise err(429, "too_many_requests", "too many requests — wait a moment and try again")
805
- body = await _bounded_body(request)
806
- found = _resolve(token)
807
- if not found:
808
- raise _refuse()
809
- rt, _slug, table_key, view, entry = found
810
- if entry.get("access") == "password" and not _pw_ok(entry, str(body.get("passphrase") or "")):
811
- raise _refuse()
812
- return _public_view(rt, table_key, view)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
api/routes_slack.py DELETED
@@ -1,756 +0,0 @@
1
- """routes_slack.py — MANAGE AGENT: a bot per Slack channel, walled by the engine that walls a
2
- person. (wave 33, owner item 10 · `W33-T38` / `W33-T39` / `W33-T67`.)
3
-
4
- Owner, verbatim (2026-08-14): *"Expand Slack we need to be able to configure an AI bot PER channel
5
- whose permissions we can toggle based on Fields etc of the databases, exactly like how we toggle
6
- permissioning per user."*
7
-
8
- ────────────────────────────────────────────────────────────────────────────────────────────────
9
- ⛔⛔ D-84 SAID THIS WAS "adapted from OpenTag" AND THAT PREMISE IS FALSE (PRD amendment A1).
10
-
11
- `PENDING.md` D-84 has named OpenTag as the model for per-Slack-channel permissioning since
12
- 2026-08-08. **OpenTag has no permission model to adapt.** `app/runtime-host.ts` is
13
- `identifyUser: () => OPENTAG_SERVICE_USER` — ONE constant identity for every request — and its own
14
- `sender-context.ts` says the Slack sender is *"informational only… not gating access."* Its
15
- authorization ceiling is whole-MCP-server, decided once at process boot from env vars. It is a
16
- live specimen of identity that LOOKS like a permission and is not.
17
-
18
- `core/perm_scope.py` is already strictly more expressive: per database, per row, per FIELD, per
19
- principal. So item 10 is OUR engine projected onto a CHANNEL principal — see `agent_principal`
20
- below, which is the whole projection and is nine lines. Study:
21
- `.claude/wiki/research/opentag-adoption.md` (licence gate: MIT, PASSED).
22
-
23
- What OpenTag genuinely contributes is the WRITE-APPROVAL interceptor (`W33-T67`, `approval_card`
24
- below) and nothing else. Its TRANSPORT is AVOID wholesale — hosted CopilotKit Intelligence, a
25
- second Node process, a persistent outbound socket and each tenant's Slack credentials held by a
26
- third party, against ONE process on the HF free tier. The door here is `routes_forms.py`'s proven
27
- unauthenticated-public shape plus Slack's signing-secret check.
28
-
29
- ────────────────────────────────────────────────────────────────────────────────────────────────
30
- ⚠ A CHANNEL IS A PRINCIPAL, NOT A PERSON. The wall binds to the Slack conversation id, so every
31
- human in that channel reads through the same rules. That is the honest reading of "a bot per
32
- channel" and the pane says it out loud, because the alternative is an admin assuming per-person
33
- scoping from a screen that looks exactly like the per-person one.
34
-
35
- ⚠ AND THE IDENTITY IS THE CHANNEL ID, NEVER ITS NAME. A channel can be renamed; its id cannot.
36
- A wall bound to `#sales` silently re-points the day somebody renames the channel.
37
- """
38
- import hmac
39
- import json
40
- import os
41
- import secrets
42
- import time
43
- from datetime import datetime, timezone
44
-
45
- from fastapi import APIRouter, Body, Depends, Request
46
-
47
- from deps import Session, err, require_session
48
- from routes_admin import admin_gate
49
-
50
- router = APIRouter(prefix="/api/v1")
51
-
52
- #: The tenant's channel agents: `{id: record}`. A per-tenant bucket, so it rides
53
- #: `runtime.store_key`'s prefix and never lands in tenant #0's namespace.
54
- AGENTS_KEY = "slack_agents"
55
-
56
- #: Pending mutations awaiting a human's click (`W33-T67`). Server-only, per tenant.
57
- PENDING_KEY = "slack_pending_writes"
58
-
59
- #: How long an approval card stays clickable. An approval is a statement about the world as it was
60
- #: when the card was rendered; an hour later the values it names may no longer be the values it
61
- #: would write. Expiring is the honest behaviour, and an expired card says so rather than 403ing.
62
- APPROVAL_TTL_S = 15 * 60
63
-
64
- #: Slack rejects a replayed request older than 5 minutes; so do we, before any signature work.
65
- SLACK_MAX_SKEW_S = 60 * 5
66
-
67
- MAX_BODY_BYTES = 64 * 1024
68
-
69
- #: ⛔ ROW-CAPPED BECAUSE AN APPROVER WHO CANNOT READ THE CARD CANNOT APPROVE IT. Copied
70
- #: deliberately from OpenTag's `agent/write_confirmation.py`, which caps for the same reason:
71
- #: past a certain length Slack collapses a message behind "Show more", and a human clicking
72
- #: Approve on a card whose tail they never saw is worse than no card at all.
73
- APPROVAL_MAX_ROWS = 12
74
-
75
-
76
- # ── the tenant's agent records ───────────────────────────────────────────────────────────────
77
- def _agents(rt):
78
- """`{id: record}` for one tenant. `{}` on any failure — an unreadable bucket must degrade to
79
- "this tenant has no agents", never to a 500 on the settings pane."""
80
- try:
81
- found = rt.get(AGENTS_KEY) or {}
82
- except Exception: # noqa: BLE001
83
- return {}
84
- return found if isinstance(found, dict) else {}
85
-
86
-
87
- def _clean_agent(raw, prior=None):
88
- """One stored record, built KEY BY KEY.
89
-
90
- ⛔ Never `dict(raw)` and never `**raw`. This record is the SUBJECT of a permission decision;
91
- a client-supplied key landing in it is a client-supplied input to `perm_scope`. The same rule
92
- `routes_forms._public_form` follows on the way out, applied here on the way in.
93
- """
94
- prior = prior if isinstance(prior, dict) else {}
95
- out = {
96
- "id": str(prior.get("id") or raw.get("id") or ""),
97
- "channel": str(raw.get("channel") or prior.get("channel") or "").strip()[:64],
98
- "channelName": str(raw.get("channelName") or prior.get("channelName") or "").strip()[:80],
99
- "label": " ".join(str(raw.get("label") or prior.get("label") or "").split())[:80],
100
- "active": bool(raw.get("active", prior.get("active", True))),
101
- # ⛔ DEFAULT TRUE, AND `is not False` RATHER THAN TRUTHINESS. A record written before this
102
- # key existed must read as "approval required": the one direction a default here is
103
- # allowed to be wrong in is the safe one, because an unattended write cannot be undone by
104
- # revoking the bot afterwards [[default-must-pass-its-own-guard]].
105
- "writeApproval": raw.get("writeApproval", prior.get("writeApproval", True)) is not False,
106
- # The permission block. Same shape, same validator, same engine as a user's.
107
- "perms": prior.get("perms") if isinstance(prior.get("perms"), dict) else {},
108
- "perms_v": int(prior.get("perms_v") or 0),
109
- "createdBy": str(prior.get("createdBy") or raw.get("createdBy") or ""),
110
- "createdAt": str(prior.get("createdAt") or raw.get("createdAt") or ""),
111
- }
112
- return out
113
-
114
-
115
- def _put_agent(session, agent_id, mutate):
116
- """Read-modify-write ONE agent under the tenant's bucket, synchronously.
117
-
118
- `flush="sync"` because the client re-reads the list immediately after every write here, and an
119
- async flush would let the refetch win the race and paint the pre-write state — the
120
- [[refetch-eats-its-own-write]] shape.
121
- """
122
- def _set(cur):
123
- cur = dict(cur or {})
124
- rec = cur.get(agent_id) if isinstance(cur.get(agent_id), dict) else None
125
- nxt = mutate(rec)
126
- if nxt is None:
127
- cur.pop(agent_id, None)
128
- else:
129
- cur[agent_id] = nxt
130
- return cur
131
-
132
- session.runtime.update(AGENTS_KEY, _set, flush="sync")
133
-
134
-
135
- # ── ⭐⭐ THE PROJECTION — THE WHOLE OF "the same engine that permissions a user" ───────────────
136
- def agent_principal(agent):
137
- """A channel agent, as a PRINCIPAL `core/perm_scope` already understands.
138
-
139
- ⭐⭐ THIS IS THE ENTIRE POINT OF THE TICKET AND IT IS NINE LINES. `perm_scope` takes a user
140
- RECORD — a plain dict with `perms`, `perms_v` and `role` — not a User object and not a session.
141
- So a channel agent carrying a `perms` block simply IS such a record, and `may_access`,
142
- `visible_fields`, `hidden_keys` and `apply_row_scope` work on it unmodified. There is no second
143
- engine, no parallel vocabulary, and nothing about a channel to keep in step with anything about
144
- a person. That is what the owner's *"exactly like how we toggle permissioning per user"* means
145
- when it is true in code rather than in appearance.
146
-
147
- ⛔ `role` IS HARDCODED NON-ADMIN AND MUST STAY SO. `perm_scope.may_access` returns True
148
- unconditionally for `role == 'admin'` — the break-glass clause that keeps the owner out of a
149
- locked store. A bot has no such emergency and no hands: an agent record that could carry
150
- `role: 'admin'` would be one stored key away from bypassing every wall on this page. The key is
151
- not copied from the record; it is written here, every time.
152
-
153
- ⛔ AND `perms_v` IS FORCED TO THE CURRENT VERSION, which makes an UNDECLARED database DENY
154
- (C-PERM amendment 4). Without it a fresh agent would fall through to `perms.may_open`'s legacy
155
- grant wall and read `modules: 'all'`-shaped defaults — i.e. a brand-new bot would start with
156
- access to everything. Fail-closed from the first byte.
157
- """
158
- import core.perm_scope as perm_scope
159
- return {
160
- "username": f"slack:{(agent or {}).get('channel') or '?'}",
161
- "role": "agent",
162
- "perms": (agent or {}).get("perms") or {},
163
- "perms_v": perm_scope.PERMS_VERSION,
164
- # No `bus`, no `agent`: a channel is not a business unit and not a salesperson. Absent
165
- # rather than 'all' — `perms.allowed_bu_labels` narrows on absence, which is the direction
166
- # this must fail in.
167
- }
168
-
169
-
170
- def agent_may_read(agent, module):
171
- """May this channel open `module` at all?"""
172
- import core.perm_scope as perm_scope
173
- if not (agent or {}).get("active", True):
174
- return False
175
- return bool(perm_scope.may_access(agent_principal(agent), module))
176
-
177
-
178
- def agent_visible_fields(agent, fields, module):
179
- """`fields` minus this channel's hidden closure — the SAME transitive closure a person gets,
180
- so a formula over a hidden column cannot leak it back through arithmetic."""
181
- import core.perm_scope as perm_scope
182
- return perm_scope.visible_fields(fields, agent_principal(agent), module)
183
-
184
-
185
- def agent_rows(agent, rows, module, fields, ctx=None):
186
- """The rows this channel may receive — `permits()`, so an unanswerable permanent filter DENIES
187
- rather than being ignored."""
188
- import core.perm_scope as perm_scope
189
- p = agent_principal(agent)
190
- hide = perm_scope.hidden_keys(p, module, fields)
191
- kept = perm_scope.apply_row_scope(rows, p, module, fields, ctx)
192
- # Both wires, never one: the field list and the row payload are separate, and stripping only
193
- # the first leaves the value sitting in the second where anyone can read it.
194
- return [perm_scope.strip_row(r, hide) for r in kept]
195
-
196
-
197
- # ── the credential ───────────────────────────────────────────────────────────────────────────
198
- def slack_creds(rt):
199
- """This TENANT's Slack credentials from its own keychain, or None.
200
-
201
- ⛔ NO ENVIRONMENT FALLBACK, DELIBERATELY, AND THIS IS D-202's LESSON APPLIED BEFORE IT
202
- HAPPENS AGAIN. Meta Ads shipped loading end-to-end and was still not a connector, because
203
- `keychain.meta_creds` had no caller and the token came from the owner's `.env` — making it a
204
- tenant-#0 FACT indistinguishable from a screenshot. `keychain.meta_creds`' own docstring spells
205
- out the rule: handing the environment's credential to a tenant whose admin has not stored one
206
- is the leak the resolver exists to prevent. So a tenant with no entry gets None and the pane
207
- SAYS so.
208
-
209
- ⚠ Reads through `list_entries` + `read_fields` (both public) rather than `keychain._first_creds`
210
- (private, and in a file outside this lane's fence). Same deterministic rule: entries are
211
- id-sorted, so "first" is stable across reads rather than dict-order luck.
212
- """
213
- try:
214
- import core.keychain as keychain
215
- for row in keychain.list_entries(rt):
216
- if str(row.get("type") or "") != "slack":
217
- continue
218
- fields = keychain.read_fields(rt, row.get("id"))
219
- if isinstance(fields, dict) and fields.get("signing_secret"):
220
- return fields
221
- except Exception: # noqa: BLE001
222
- # A locked or unreadable keychain reads as "not configured" for the PANE, which is honest;
223
- # the signature check below fails closed regardless, so this cannot widen anything.
224
- return None
225
- return None
226
-
227
-
228
- # ── the authenticated doors (the Manage agent surface) ───────────────────────────────────────
229
- def _summary(agent, modules):
230
- """One sentence per agent for the list row — computed here, because the alternative is one
231
- round trip per row to fill one cell (the same reason `AdminUser.access` exists)."""
232
- governed = [m for m in modules if m.get("enforced")]
233
- perms = agent.get("perms") or {}
234
- open_n = sum(1 for m in governed if (perms.get(m["key"]) or {}).get("access"))
235
- if not governed:
236
- return ""
237
- if open_n == 0:
238
- return "No access"
239
- restricted = sum(1 for m in governed
240
- if (perms.get(m["key"]) or {}).get("access")
241
- and ((perms.get(m["key"]) or {}).get("filter")
242
- or (perms.get(m["key"]) or {}).get("hiddenFields")))
243
- head = (f"All {open_n} database{'' if open_n == 1 else 's'}" if open_n == len(governed)
244
- else f"{open_n} of {len(governed)} databases")
245
- return f"{head}, {restricted} restricted" if restricted else head
246
-
247
-
248
- @router.get("/agents")
249
- def list_channel_agents(session: Session = Depends(admin_gate)):
250
- """This tenant's channel agents, plus whether Slack is reachable at all."""
251
- import routes_admin
252
- modules = routes_admin._perm_modules(session)
253
- rows = []
254
- for aid, a in sorted(_agents(session.runtime).items()):
255
- if not isinstance(a, dict):
256
- continue
257
- rows.append({"id": aid, "channel": a.get("channel") or "",
258
- "channelName": a.get("channelName") or "",
259
- "label": a.get("label") or "", "active": a.get("active", True) is not False,
260
- "writeApproval": a.get("writeApproval", True) is not False,
261
- "summary": _summary(a, modules)})
262
- return {"agents": rows, "configured": slack_creds(session.runtime) is not None}
263
-
264
-
265
- @router.post("/agents")
266
- def create_channel_agent(body: dict = Body(default=None),
267
- session: Session = Depends(admin_gate)):
268
- body = body if isinstance(body, dict) else {}
269
- channel = str(body.get("channel") or "").strip()
270
- if not channel:
271
- raise err(400, "no_channel", "a Slack channel ID is required")
272
- existing = _agents(session.runtime)
273
- # ⚠ ONE AGENT PER CHANNEL. Two records for one conversation would mean two walls, and nothing
274
- # anywhere decides which one applies — the [[one-question-two-normalizers]] shape, in the one
275
- # place where the two answers are "may read" and "may not".
276
- for a in existing.values():
277
- if isinstance(a, dict) and str(a.get("channel") or "") == channel:
278
- raise err(409, "channel_taken",
279
- "that channel already has an agent — edit it instead of adding a second")
280
- aid = secrets.token_urlsafe(9)
281
- rec = _clean_agent(dict(body, id=aid, createdBy=session.uname,
282
- createdAt=datetime.now(timezone.utc).isoformat(timespec="seconds")))
283
- _put_agent(session, aid, lambda _prior: rec)
284
- fresh = _agents(session.runtime).get(aid)
285
- if not isinstance(fresh, dict):
286
- # The store took the write and did not record it. A 200 here would tell an administrator
287
- # the agent exists when it does not.
288
- raise err(503, "store_unavailable", "the agent was NOT created")
289
- return {"agent": {"id": aid, "channel": rec["channel"], "channelName": rec["channelName"],
290
- "label": rec["label"], "active": rec["active"],
291
- "writeApproval": rec["writeApproval"], "summary": "No access"}}
292
-
293
-
294
- @router.get("/agents/{agent_id}")
295
- def get_channel_agent(agent_id: str, session: Session = Depends(admin_gate)):
296
- """The agent PLUS the permission envelope — the SAME shape `get_perms` answers with.
297
-
298
- ⭐ ONE PAYLOAD SHAPE FOR TWO ROOMS. `permsModel.parsePermsPayload` parses this, and
299
- `settings/ModulePermsList` renders it, because they are literally the same client code. A
300
- second envelope here would mean a second parser and a second set of defaults within a wave.
301
- """
302
- import routes_admin
303
- a = _agents(session.runtime).get(str(agent_id))
304
- if not isinstance(a, dict):
305
- raise err(404, "no_such_agent", "no agent with that id")
306
- modules = routes_admin._perm_modules(session)
307
- enforced = [m["key"] for m in modules if m.get("enforced")]
308
- stored = a.get("perms") or {}
309
- principal = agent_principal(a)
310
- import core.perm_scope as perm_scope
311
- perms_out = {}
312
- for k in enforced:
313
- e = stored.get(k)
314
- perms_out[k] = e if isinstance(e, dict) else {
315
- "access": bool(perm_scope.may_access(principal, k)), "filter": None,
316
- "hiddenFields": []}
317
- return {"id": str(agent_id), "channel": a.get("channel") or "",
318
- "channelName": a.get("channelName") or "", "label": a.get("label") or "",
319
- "active": a.get("active", True) is not False,
320
- "writeApproval": a.get("writeApproval", True) is not False,
321
- "perms": perms_out,
322
- # ⛔ ALWAYS THE CURRENT VERSION, because `agent_principal` forces it: the editor must
323
- # render "undeclared = denied", not the legacy-grant reading it would show at 0.
324
- "perms_v": perm_scope.PERMS_VERSION,
325
- # A bot is NEVER an admin — see `agent_principal`. Sent so the editor never paints
326
- # the "Everything (admin)" state for a principal that cannot have it.
327
- "is_admin": False,
328
- "modules": modules,
329
- "fields_by_module": {k: routes_admin._module_fields(k) for k in enforced}}
330
-
331
-
332
- @router.put("/agents/{agent_id}/perms")
333
- def put_channel_agent_perms(agent_id: str, body: dict = Body(default=None),
334
- session: Session = Depends(admin_gate)):
335
- """Replace this agent's permission block wholesale — the same validator a user's block gets."""
336
- import routes_admin
337
- body = body if isinstance(body, dict) else {}
338
- if not isinstance(_agents(session.runtime).get(str(agent_id)), dict):
339
- raise err(404, "no_such_agent", "no agent with that id")
340
- if "perms" not in body:
341
- raise err(400, "empty_patch", "no perms to save")
342
- mods = routes_admin._perm_modules(session)
343
- # ⭐ THE SAME `_clean_perms`, NOT A COPY OF IT. It refuses a filter this module cannot
344
- # evaluate, refuses a hiddenFields key that names nothing, refuses an unenforced `ut_*` key,
345
- # and refuses a BU condition the pushdown cannot read. Every one of those is exactly as true
346
- # for a channel as for a person, and a second validator here is a second place for one of
347
- # them to go missing.
348
- cleaned = routes_admin._clean_perms(
349
- body.get("perms"),
350
- enforced_keys={m["key"] for m in mods if m.get("enforced")},
351
- listed_keys={m["key"] for m in mods}) or {}
352
-
353
- import core.perm_scope as perm_scope
354
-
355
- def _mut(prior):
356
- if not isinstance(prior, dict):
357
- return None
358
- nxt = dict(prior)
359
- nxt["perms"] = cleaned
360
- nxt["perms_v"] = perm_scope.PERMS_VERSION
361
- return nxt
362
-
363
- _put_agent(session, str(agent_id), _mut)
364
- fresh = _agents(session.runtime).get(str(agent_id)) or {}
365
- if (fresh.get("perms") or {}) != cleaned:
366
- # The one direction this must never fail in: telling an administrator the wall is up when
367
- # it is not.
368
- raise err(503, "store_unavailable", "the permissions were not saved — the agent is UNCHANGED")
369
- return {"id": str(agent_id), "perms": fresh.get("perms") or {},
370
- "perms_v": int(fresh.get("perms_v") or 0)}
371
-
372
-
373
- @router.patch("/agents/{agent_id}")
374
- def patch_channel_agent(agent_id: str, body: dict = Body(default=None),
375
- session: Session = Depends(admin_gate)):
376
- body = body if isinstance(body, dict) else {}
377
- if not isinstance(_agents(session.runtime).get(str(agent_id)), dict):
378
- raise err(404, "no_such_agent", "no agent with that id")
379
- #: ⛔ `perms` IS NOT PATCHABLE HERE. It has its own door with its own validator; accepting it
380
- #: on the metadata route would be a second, unvalidated way to write the wall.
381
- allowed = {k: v for k, v in body.items()
382
- if k in ("label", "active", "writeApproval", "channelName")}
383
- if not allowed:
384
- raise err(400, "empty_patch", "nothing to change")
385
-
386
- def _mut(prior):
387
- return _clean_agent(allowed, prior=prior) if isinstance(prior, dict) else None
388
-
389
- _put_agent(session, str(agent_id), _mut)
390
- import routes_admin
391
- a = _agents(session.runtime).get(str(agent_id)) or {}
392
- return {"agent": {"id": str(agent_id), "channel": a.get("channel") or "",
393
- "channelName": a.get("channelName") or "", "label": a.get("label") or "",
394
- "active": a.get("active", True) is not False,
395
- "writeApproval": a.get("writeApproval", True) is not False,
396
- "summary": _summary(a, routes_admin._perm_modules(session))}}
397
-
398
-
399
- @router.delete("/agents/{agent_id}")
400
- def delete_channel_agent(agent_id: str, session: Session = Depends(admin_gate)):
401
- if not isinstance(_agents(session.runtime).get(str(agent_id)), dict):
402
- raise err(404, "no_such_agent", "no agent with that id")
403
- _put_agent(session, str(agent_id), lambda _prior: None)
404
- if isinstance(_agents(session.runtime).get(str(agent_id)), dict):
405
- raise err(503, "store_unavailable", "the agent was NOT removed")
406
- return {"ok": True}
407
-
408
-
409
- # ── ⭐ W33-T67: THE WRITE-APPROVAL GATE ───────────────────────────────────────────────────────
410
- def _is_empty(value):
411
- """Is this value ABSENT, as opposed to falsy?
412
-
413
- ⛔ COPIED EXACTLY FROM OpenTag's `agent/write_confirmation.py`, and the exactness is the point:
414
- `0` and `False` are VALUES a human must see on the card. Setting a price to 0 or a flag to
415
- False is precisely the kind of write somebody needs to approve, and a naive `if not value`
416
- drops both rows silently — the approver then reads a card that does not describe the write
417
- they are approving. The MIT licence gate for this borrowing is recorded in
418
- `.claude/wiki/research/opentag-adoption.md`.
419
- """
420
- return value is None or (isinstance(value, str) and value.strip() == "")
421
-
422
-
423
- def approval_card(action, values, agent=None):
424
- """The card a human reads before a bot writes. `{action, rows, truncated, note}`.
425
-
426
- ⛔ ROW-CAPPED, and the cap is a SAFETY property rather than a layout one: past a certain
427
- length Slack collapses a message behind "Show more", and **an approver who cannot read the
428
- card cannot approve it.** When rows are dropped the card SAYS how many — a truncation nobody
429
- was told about is the violation, not the truncation (wave-30 R6's second sentence).
430
- """
431
- rows = [{"field": str(k), "value": v}
432
- for k, v in (values or {}).items() if not _is_empty(v)]
433
- rows.sort(key=lambda r: r["field"])
434
- shown, dropped = rows[:APPROVAL_MAX_ROWS], max(0, len(rows) - APPROVAL_MAX_ROWS)
435
- return {
436
- "action": str(action or "")[:80],
437
- "rows": shown,
438
- "truncated": dropped,
439
- "note": (f"{dropped} more field(s) not shown — open the record to review them before "
440
- f"approving." if dropped else ""),
441
- "agent": (agent or {}).get("label") or (agent or {}).get("channel") or "",
442
- }
443
-
444
-
445
- def intercept_write(agent, action, values, stash):
446
- """THE INTERCEPTOR. Returns `("commit", None)` or `("await_approval", card)`.
447
-
448
- ⭐ The one thing worth taking from OpenTag: a MUTATING tool call is halted, rendered as a card
449
- naming the action and its values, and committed only on an explicit human accept. Everything
450
- else in that repo — the transport, the runtime, the identity model — is AVOID (amendment A1).
451
-
452
- ⛔ FAIL-CLOSED ON A MISSING FLAG: `is not False`, so a record written before `writeApproval`
453
- existed requires approval. The unsafe direction here is not recoverable — revoking a bot does
454
- not un-write what it wrote.
455
- """
456
- if (agent or {}).get("writeApproval", True) is not False:
457
- card = approval_card(action, values, agent)
458
- stash(card)
459
- return "await_approval", card
460
- return "commit", None
461
-
462
-
463
- def _pending(rt):
464
- try:
465
- found = rt.get(PENDING_KEY) or {}
466
- except Exception: # noqa: BLE001
467
- return {}
468
- return found if isinstance(found, dict) else {}
469
-
470
-
471
- def stash_pending(rt, agent, action, values, now=None):
472
- """Store one awaiting-approval mutation and return its token.
473
-
474
- The token is what rides the card's button, so it is `secrets.token_urlsafe` and not the
475
- action's id: a guessable value on an unauthenticated door is a way to approve somebody else's
476
- write. Server-only bucket, per tenant, exactly as `routes_forms.TOKENS_KEY` is.
477
- """
478
- token = secrets.token_urlsafe(18)
479
- row = {"at": float(now if now is not None else time.time()),
480
- "channel": str((agent or {}).get("channel") or ""),
481
- "action": str(action or "")[:80],
482
- "values": values if isinstance(values, dict) else {}}
483
- rt.update(PENDING_KEY, lambda cur: {**(cur or {}), token: row}, flush="sync")
484
- return token
485
-
486
-
487
- #: `{action kind: fn(rt, row) -> None}`. Registered by whatever can actually perform a mutation.
488
- #:
489
- #: ⛔⛔ EMPTY IN PRODUCTION TODAY, AND SAYING SO IS THE POINT. `commit_pending` below is the ONE
490
- #: place an approved write may be performed, so it is the place a negative control can bite — but
491
- #: a gate is only as honest as what it guards. Until something registers here, an approved card
492
- #: performs NOTHING and `commit_pending` returns `no_committer` rather than pretending. That is a
493
- #: declared absence, not a silent one [[flag-shipped-without-its-writer]].
494
- _COMMITTERS = {}
495
-
496
-
497
- def register_committer(kind, fn):
498
- """Declare who may perform an approved mutation of `kind`. Idempotent by key."""
499
- _COMMITTERS[str(kind)] = fn
500
-
501
-
502
- def commit_pending(rt, token, approved, now=None):
503
- """Resolve ONE approval card. Returns one of
504
- `expired` · `unknown` · `rejected` · `no_committer` · `committed` · `failed`.
505
-
506
- ⛔⛔ THIS IS THE WRITE GATE, AND IT IS A SEPARATE FUNCTION FROM THE ROUTE ON PURPOSE. T67's
507
- `done-when` asks for an NC proving a REJECTED card writes nothing. A control aimed at the
508
- route could not bite while the route had no write in it at all — it would stay green with the
509
- guard deleted, because there would be nothing for the guard to be protecting anything from
510
- ([[gate-can-report-green-on-nothing]], and a verifier caught exactly that on this ticket's
511
- first draft). Putting the commit behind ONE named seam gives the control a real subject: the
512
- gate registers a recorder, and `rejected` must leave it untouched while `approve` must call it
513
- exactly once.
514
-
515
- ⛔ THE TOKEN IS CONSUMED BEFORE EITHER BRANCH, and before any committer runs. A card that
516
- survives its own click is a replayable write, and "approve twice" must never mean "write
517
- twice". The delete is `flush="sync"` for the same reason.
518
- """
519
- now = float(now if now is not None else time.time())
520
- row = _pending(rt).get(str(token))
521
- if not isinstance(row, dict):
522
- return "unknown"
523
- # Consume FIRST — before the TTL verdict, before the approve/reject branch, before any write.
524
- rt.update(PENDING_KEY,
525
- lambda cur: {k: v for k, v in (cur or {}).items() if k != str(token)},
526
- flush="sync")
527
- if now - float(row.get("at") or 0) > APPROVAL_TTL_S:
528
- return "expired"
529
- if not approved:
530
- # ⛔ NOTHING BELOW THIS LINE RUNS FOR A REJECTED CARD. The whole gate is this return.
531
- return "rejected"
532
- fn = _COMMITTERS.get(str(row.get("action") or ""))
533
- if fn is None:
534
- return "no_committer"
535
- try:
536
- fn(rt, row)
537
- except Exception: # noqa: BLE001
538
- # A committer that raises must not read as a commit. The card is already consumed, so the
539
- # honest report is that it failed, and the human asks again.
540
- return "failed"
541
- return "committed"
542
-
543
-
544
- # ── the UNAUTHENTICATED Slack door ───────────────────────────────────────────────────────────
545
- #: Sliding window, keyed on the SLACK TEAM, never the client IP.
546
- #:
547
- #: ⛔ WHY NOT THE IP, WHICH IS WHAT `routes_forms` DOES. Every Slack event arrives from Slack's own
548
- #: infrastructure, so an IP window is one shared bucket for every workspace on the platform: one
549
- #: busy tenant would spend the allowance for all of them, and the symptom would be another
550
- #: tenant's bot going quiet. The team id is the closest thing to the actual noisy party.
551
- #: ⚠ It is attacker-CONTROLLED before the signature is checked, so the window is applied AFTER
552
- #: verification, never before — an unsigned request is refused on cost grounds anyway (a signature
553
- #: check is a single HMAC).
554
- RATE_WINDOW_S, RATE_PER_WINDOW = 60, 60
555
- _HITS: dict = {}
556
-
557
-
558
- def _rate_ok(key, now):
559
- seen = [t for t in _HITS.get(key, ()) if now - t < RATE_WINDOW_S]
560
- seen.append(now)
561
- _HITS[key] = seen
562
- if len(_HITS) > 4096:
563
- for k in [k for k, v in _HITS.items() if not v or now - v[-1] > RATE_WINDOW_S]:
564
- _HITS.pop(k, None)
565
- return len(seen) <= RATE_PER_WINDOW
566
-
567
-
568
- async def _raw_body(request):
569
- """The body as RAW BYTES, capped.
570
-
571
- ⛔⛔ RAW, NOT PARSED, AND THAT IS NOT A STYLE CHOICE. Slack signs the literal string
572
- `v0:{timestamp}:{body}` byte for byte. `routes_forms._bounded_body` — the function this is
573
- otherwise copied from — returns only the parsed dict and DISCARDS the bytes, so a verbatim
574
- copy of it could not verify a Slack signature at all: re-serialising the dict changes
575
- whitespace and key order and the HMAC no longer matches. The bug would look like "Slack
576
- signatures are always invalid", which is indistinguishable from a wrong secret.
577
-
578
- ⚠ And it streams rather than calling `request.body()`: FastAPI would otherwise have buffered
579
- the whole body before the handler's first line, so a content-length check inside the handler
580
- caps nothing (`routes_forms`' own scar, recorded in its docstring).
581
- """
582
- size, chunks = 0, []
583
- async for chunk in request.stream():
584
- size += len(chunk)
585
- if size > MAX_BODY_BYTES:
586
- raise err(413, "body_too_large", "that request is too large")
587
- chunks.append(chunk)
588
- return b"".join(chunks)
589
-
590
-
591
- def _refuse():
592
- """ONE refusal for every reason. No oracle.
593
-
594
- A wrong signature, a stale timestamp, an unknown team, an unconfigured tenant and a channel
595
- with no agent all answer identically — otherwise the door tells an unauthenticated caller
596
- which tenants exist and which channels are configured, which is the question it was built to
597
- not answer. `routes_forms._refuse` takes the same posture for the same reason.
598
- """
599
- return err(403, "bad_request", "that request could not be verified")
600
-
601
-
602
- def _verify(secret, timestamp, raw, signature, now):
603
- """Slack's v0 signature, with the replay window checked FIRST."""
604
- try:
605
- ts = int(str(timestamp or "0"))
606
- except ValueError:
607
- return False
608
- if abs(now - ts) > SLACK_MAX_SKEW_S:
609
- return False
610
- base = b"v0:" + str(ts).encode("ascii") + b":" + (raw or b"")
611
- import hashlib
612
- expected = "v0=" + hmac.new(str(secret).encode("utf-8"), base, hashlib.sha256).hexdigest()
613
- return hmac.compare_digest(expected, str(signature or ""))
614
-
615
-
616
- def _resolve_tenant(raw, timestamp, signature, now):
617
- """`(slug, runtime, creds)` for the tenant whose signing secret verifies this request.
618
-
619
- ⛔ THE TENANT IS DECIDED BY THE SIGNATURE, NEVER BY THE PAYLOAD. A body-supplied `team_id`
620
- would let an unauthenticated caller name the tenant it wants to be — the exact widening
621
- `deps._user_for`'s tenant-equality check closes on the authenticated side. So every configured
622
- tenant's secret is tried and the one that VERIFIES names the tenant.
623
-
624
- ⚠ NO EARLY `break` ON A FAILED CANDIDATE and no per-tenant error: the loop's cost must not
625
- depend on which tenant matched. `routes_forms._resolve` walks tenants the same way, for the
626
- same reason — a public door has no session to ask.
627
- """
628
- from harness import runtime as _rt
629
- hit = None
630
- try:
631
- slugs = list(_rt.known_tenants())
632
- except Exception: # noqa: BLE001
633
- return None, None, None
634
- for slug in slugs:
635
- try:
636
- rt = _rt.get_runtime(slug)
637
- except Exception: # noqa: BLE001
638
- continue
639
- creds = slack_creds(rt)
640
- if not creds:
641
- continue
642
- if _verify(creds.get("signing_secret"), timestamp, raw, signature, now) and hit is None:
643
- hit = (slug, rt, creds)
644
- return hit if hit else (None, None, None)
645
-
646
-
647
- @router.post("/slack/events")
648
- async def slack_events(request: Request):
649
- """Slack's Events API. UNAUTHENTICATED BY CONSTRUCTION — no `Depends(require_session)`.
650
-
651
- ⭐ Built like `routes_forms.py`'s public door and not like OpenTag's: one process, no vendor,
652
- no second runtime, no persistent outbound socket, and this tenant's Slack secret never leaves
653
- this deployment (amendment A1).
654
- """
655
- now = time.time()
656
- raw = await _raw_body(request)
657
- ts = request.headers.get("x-slack-request-timestamp")
658
- sig = request.headers.get("x-slack-signature")
659
- slug, rt, _creds = _resolve_tenant(raw, ts, sig, now)
660
- if not rt:
661
- raise _refuse()
662
-
663
- try:
664
- payload = json.loads(raw or b"{}")
665
- except ValueError:
666
- raise _refuse()
667
- if not isinstance(payload, dict):
668
- raise _refuse()
669
-
670
- # Slack's one-time endpoint handshake. Answered ONLY after the signature verified — an
671
- # unsigned challenge echo would confirm the endpoint exists to anyone who probes it.
672
- if payload.get("type") == "url_verification":
673
- return {"challenge": str(payload.get("challenge") or "")[:512]}
674
-
675
- team = str(payload.get("team_id") or slug)
676
- if not _rate_ok(f"{slug}:{team}", now):
677
- raise err(429, "too_many_requests", "too many requests — wait a moment and try again")
678
-
679
- event = payload.get("event") if isinstance(payload.get("event"), dict) else {}
680
- channel = str(event.get("channel") or "")
681
- agent = None
682
- for a in _agents(rt).values():
683
- if isinstance(a, dict) and str(a.get("channel") or "") == channel:
684
- agent = a
685
- break
686
- # ⛔ NO AGENT, OR AN INACTIVE ONE, IS SILENCE — a 200 with no action. Not a 403: Slack retries
687
- # a non-2xx up to three times, so refusing here would turn "this channel is not configured"
688
- # into three refusals per message, and the retry storm would be the only visible symptom.
689
- # ⚠ And it must not say WHICH — a distinguishable answer tells an unauthenticated caller which
690
- # channels this workspace has configured.
691
- if not isinstance(agent, dict) or agent.get("active", True) is False:
692
- return {"ok": True}
693
-
694
- # ⛔⛔ THE ANSWERING HALF IS NOT BUILT YET, AND SAYING SO IS THE POINT. What ships here is the
695
- # DOOR and the WALL: a verified request, resolved to a tenant by signature, matched to a
696
- # channel agent whose `perms` block is a `perm_scope` principal (`agent_principal`). Composing
697
- # a reply means an LLM call on the cheap-first ladder plus the read path, and a half-built
698
- # answerer that returns something plausible is worse than one that returns nothing.
699
- # Booked rather than faked [[flag-shipped-without-its-writer]].
700
- return {"ok": True}
701
-
702
-
703
- @router.post("/slack/interact")
704
- async def slack_interact(request: Request):
705
- """The approval card's button (`W33-T67`). UNAUTHENTICATED, signature-verified, same shape."""
706
- now = time.time()
707
- raw = await _raw_body(request)
708
- slug, rt, _creds = _resolve_tenant(raw, request.headers.get("x-slack-request-timestamp"),
709
- request.headers.get("x-slack-signature"), now)
710
- if not rt:
711
- raise _refuse()
712
- # Slack posts interactions as `application/x-www-form-urlencoded` with a `payload=` field.
713
- from urllib.parse import parse_qs
714
- try:
715
- form = parse_qs(raw.decode("utf-8"))
716
- payload = json.loads((form.get("payload") or ["{}"])[0])
717
- except Exception: # noqa: BLE001
718
- raise _refuse()
719
- if not isinstance(payload, dict):
720
- raise _refuse()
721
- if not _rate_ok(f"{slug}:interact", now):
722
- raise err(429, "too_many_requests", "too many requests — wait a moment and try again")
723
-
724
- actions = payload.get("actions") if isinstance(payload.get("actions"), list) else []
725
- choice = (actions[0] if actions and isinstance(actions[0], dict) else {})
726
- token = str(choice.get("value") or "")
727
- # ⭐ ANYTHING THAT IS NOT LITERALLY "approve" IS A REJECT. Fail-closed on a malformed,
728
- # truncated or unknown action id: the direction that can be wrong here without anyone
729
- # noticing is the one that writes.
730
- approved = str(choice.get("action_id") or "") == "approve"
731
- # ⛔ THE ROUTE DOES NOT DECIDE — `commit_pending` does, and it is the ONE seam a negative
732
- # control can aim at. Consumption, the TTL, the reject branch and the committer lookup all
733
- # live there; this handler only turns its verdict into a sentence.
734
- verdict = commit_pending(rt, token, approved, now=now)
735
- return {"text": {
736
- # An unknown, already-used or expired token is not an error: a person clicking a stale
737
- # card should be told it is stale, not shown a failure.
738
- "unknown": "That approval is no longer available. Ask the bot again.",
739
- "expired": "That approval expired before it was answered. Ask the bot again.",
740
- "rejected": "Rejected. Nothing was changed.",
741
- # ⚠ HONEST, not reassuring: the answering half that would register a committer is booked,
742
- # so an approved card today performs nothing and says exactly that rather than "Approved."
743
- "no_committer": "Approved — but this workspace has nothing configured to carry it out yet.",
744
- "failed": "That change could not be completed. Nothing was saved; ask the bot again.",
745
- "committed": "Approved.",
746
- }.get(verdict, "That approval is no longer available. Ask the bot again.")}
747
-
748
-
749
- @router.get("/slack/health")
750
- def slack_health(session: Session = Depends(require_session)):
751
- """Is Slack configured for THIS tenant? Session-gated, and it answers about one tenant only —
752
- enumerating the others would answer a question about our customer list."""
753
- creds = slack_creds(session.runtime)
754
- return {"configured": creds is not None,
755
- "agents": len(_agents(session.runtime)),
756
- "hasBotToken": bool((creds or {}).get("bot_token"))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_accounts.yml DELETED
@@ -1,60 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_accounts
9
- label: "Odoo GL accounts"
10
- entity: account.account
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: ut_odoo_accounts
13
- subject: "odoo:account.account"
14
- grain: "one row per GL account in the chart of accounts"
15
- scope:
16
- population: "every account.account record (192 measured)"
17
- store:
18
- table: account_account
19
- alias: a
20
- # NO date_col — a registry is not a dated event stream. Stated rather than
21
- # omitted, so its absence reads as a fact and not as an unfinished file.
22
- dims:
23
- account_type: {label: "Account type"}
24
-
25
- # key / label / type / kind, derived from the grid contract. `kind` says where the
26
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
27
- # from another topic; a `link` points at another database.
28
- fields:
29
- - key: account_code
30
- label: "Code"
31
- type: text
32
- kind: data
33
- - key: account_name
34
- label: "Account"
35
- type: text
36
- kind: data
37
- - key: odoo_id
38
- label: "Odoo ID"
39
- type: int
40
- kind: data
41
- means: "The `account.account` id. Also this row's id."
42
- - key: account_type
43
- label: "Type"
44
- type: select
45
- kind: data
46
- - key: is_expense
47
- label: "Expense account"
48
- type: checkbox
49
- kind: data
50
- means: "Ticked for the expense family - the same predicate the semantic layer's gl_lines topic uses, so this column and that topic cannot disagree."
51
- - key: refreshed
52
- label: "Refreshed"
53
- type: date
54
- kind: data
55
- means: "When this row was last reconciled against Odoo."
56
-
57
- ai_context: >
58
- The chart of accounts — the registry gl_lines posts against.
59
- Use it to resolve an account code to a name or a type.
60
- ⚠ `is_expense` is a DERIVED boolean standing in for Odoo's five-value `internal_group` (asset/liability/equity/income/expense), which the mirror does not yet carry.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_agents.yml DELETED
@@ -1,59 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_agents
9
- label: "Odoo agents"
10
- entity: res.partner
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: ut_odoo_agents
13
- subject: "odoo:res.partner.agent"
14
- grain: "one row per sales agent"
15
- scope:
16
- population: "a UNION of two disagreeing sources — partners carrying commission lines, and partners flagged res_partner.agent = TRUE"
17
- why_union: "measured 2026-08-09: 16 carry commission lines, 17 carry the flag, and the union is 19 — either source alone silently drops real agents"
18
- store:
19
- table: res_partner
20
- alias: p
21
- # NO date_col — a registry is not a dated event stream. Stated rather than
22
- # omitted, so its absence reads as a fact and not as an unfinished file.
23
-
24
- # key / label / type / kind, derived from the grid contract. `kind` says where the
25
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
26
- # from another topic; a `link` points at another database.
27
- fields:
28
- - key: agent
29
- label: "Agent"
30
- type: text
31
- kind: data
32
- - key: odoo_id
33
- label: "Odoo ID"
34
- type: int
35
- kind: data
36
- means: "The `res.partner` id. Also this row's id."
37
- - key: agent_id
38
- label: "Odoo agent id"
39
- type: int
40
- kind: data
41
- - key: flagged
42
- label: "Flagged in Odoo"
43
- type: checkbox
44
- kind: data
45
- means: "Ticked = `res.partner.agent` is set. Unticked agents were found by their commission lines instead - both are real, which is why this table is the union of the two."
46
- - key: commissioned
47
- label: "Has commission lines"
48
- type: checkbox
49
- kind: data
50
- - key: refreshed
51
- label: "Refreshed"
52
- type: date
53
- kind: data
54
- means: "When this row was last reconciled against Odoo."
55
-
56
- ai_context: >
57
- The sales-agent registry.
58
- `flagged` and `commissioned` are the two SOURCES, kept as separate columns rather than merged, because they disagree and the disagreement is information.
59
- For an agent's BOOK use sales_lines/commission_lines with the agent dim.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_bills.yml DELETED
@@ -1,86 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_bills
9
- label: "Odoo vendor bills"
10
- entity: account.move
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: ut_odoo_bills
13
- subject: "odoo:account.move.vendor"
14
- grain: "one row per posted VENDOR bill or vendor credit note (document grain)"
15
- scope:
16
- population: "move_type in (in_invoice, in_refund) AND state = posted"
17
- signs: "for payables the residual is negative on the Odoo side; take the absolute value for an AP figure"
18
- store:
19
- table: account_move
20
- alias: m
21
- date_col: "m.invoice_date"
22
- dims:
23
- vendor: {label: "Vendor"}
24
- payment_state: {label: "Payment state"}
25
- move_type: {label: "Document type"}
26
-
27
- # key / label / type / kind, derived from the grid contract. `kind` says where the
28
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
29
- # from another topic; a `link` points at another database.
30
- fields:
31
- - key: bill_no
32
- label: "Bill"
33
- type: text
34
- kind: data
35
- - key: odoo_id
36
- label: "Odoo ID"
37
- type: int
38
- kind: data
39
- means: "The `account.move` id. Also this row's id."
40
- - key: vendor
41
- label: "Vendor"
42
- type: text
43
- kind: data
44
- - key: vendor_id
45
- label: "Odoo vendor id"
46
- type: int
47
- kind: data
48
- - key: invoice_date
49
- label: "Bill date"
50
- type: date
51
- kind: data
52
- - key: due_date
53
- label: "Due date"
54
- type: date
55
- kind: data
56
- - key: amount_untaxed
57
- label: "Billed $"
58
- type: currency
59
- kind: data
60
- - key: residual
61
- label: "Outstanding $"
62
- type: currency
63
- kind: data
64
- - key: payment_state
65
- label: "Payment state"
66
- type: select
67
- kind: data
68
- - key: move_type
69
- label: "Document"
70
- type: select
71
- kind: data
72
- - key: vendor_link
73
- label: "Vendor record"
74
- type: link
75
- kind: link
76
- to_grid: ut_odoo_vendors
77
- - key: refreshed
78
- label: "Refreshed"
79
- type: date
80
- kind: data
81
- means: "When this row was last reconciled against Odoo."
82
-
83
- ai_context: >
84
- Vendor bills at DOCUMENT grain — the payables side of account_move.
85
- Use it for AP questions.
86
- ⚠ The census found `ref` (the VENDOR's own invoice number), `journal_id` and `currency_id` populated in Odoo and absent from the mirror, so they cannot be answered from here yet.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_customers.yml DELETED
@@ -1,213 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_customers
9
- label: "Odoo customers"
10
- entity: res.partner
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: customer_data
13
- subject: "odoo:res.partner"
14
- grain: "one row per customer in tenant #0's scoped book — a REGISTRY, not a dated event stream. Identity is the Odoo `res.partner` id (the row's `pid` IS that id)."
15
- scope:
16
- population: "the customer book `modules/customer_data.pool()` builds; the grid's own contract states it as one row per customer who ordered in the last 24 months"
17
- identity: "the Odoo res.partner id — exposed as the `partner_id` column (W33-T43) and used as the row pid, so there is ONE id per row and no second one"
18
- merged: "W33-T44 retired `ut_odoo_customers`, which presented this same subject. This topic describes the SURVIVING database, `customer_data`, which keeps its store bucket so no saved view, grant, cohort or formula moved"
19
- no_date: "a registry has no date dimension; ask sales_lines or customer_invoices for anything time-windowed about a customer"
20
- store:
21
- table: res_partner
22
- alias: p
23
- # NO date_col — a registry is not a dated event stream. Stated rather than
24
- # omitted, so its absence reads as a fact and not as an unfinished file.
25
- dims:
26
- agent: {label: "Sales agent"}
27
- state: {label: "State"}
28
- country: {label: "Country"}
29
-
30
- # key / label / type / kind, derived from the grid contract. `kind` says where the
31
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
32
- # from another topic; a `link` points at another database.
33
- fields:
34
- - key: customer
35
- label: "Customer"
36
- type: text
37
- kind: data
38
- means: "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
39
- - key: partner_id
40
- label: "Odoo ID"
41
- type: int
42
- kind: data
43
- means: "The Odoo res.partner id — this row's identity, and the key every Odoo document joins on. W33-T43 / owner item 12: 'One unique ID per database always.' It is DERIVED rather than read off the pool row because a customer row's pid IS the partner id, so the value is already on every row and a second copy in the pool would be a second source for one fact."
44
- - key: odoo_status
45
- label: "Odoo record"
46
- type: status
47
- kind: data
48
- means: "Whether this customer still exists in Odoo. Archived means deleted there."
49
- - key: agent
50
- label: "Agent"
51
- type: text
52
- kind: data
53
- means: "The sales agent who owns this account."
54
- - key: dba
55
- label: "DBA"
56
- type: select
57
- kind: data
58
- means: "The brand this customer buys from - Fisch, Royal, or both. Amazon-channel orders are not a DBA."
59
- - key: salesperson
60
- label: "Salesperson"
61
- type: text
62
- kind: data
63
- means: "Who keyed in most of this customer's orders — not the Agent, who owns the account."
64
- - key: street
65
- label: "Street"
66
- type: text
67
- kind: data
68
- means: "First address line, from res.partner directly - not the geocoder, so a customer the map cannot place still shows its address."
69
- - key: street2
70
- label: "Street 2"
71
- type: text
72
- kind: data
73
- means: "Second address line (suite, unit, floor) on the customer's Odoo address."
74
- - key: city
75
- label: "City"
76
- type: text
77
- kind: data
78
- means: "City on the customer's Odoo address."
79
- - key: state
80
- label: "State"
81
- type: text
82
- kind: data
83
- means: "State or province on the customer's Odoo address."
84
- - key: country
85
- label: "Country"
86
- type: text
87
- kind: data
88
- means: "Country on the customer's Odoo address."
89
- - key: zip
90
- label: "ZIP"
91
- type: text
92
- kind: data
93
- means: "Postal code on the customer's Odoo address."
94
- - key: customer_since
95
- label: "Customer since"
96
- type: date
97
- kind: data
98
- means: "When this customer was first set up in Odoo."
99
- - key: tags
100
- label: "Tags"
101
- type: text
102
- kind: data
103
- means: "Odoo labels on this customer, comma-separated."
104
- - key: pricelist
105
- label: "Price list"
106
- type: text
107
- kind: data
108
- means: "The price list this customer buys on."
109
- - key: payment_terms
110
- label: "Payment terms"
111
- type: text
112
- kind: data
113
- means: "Payment terms on this customer's account — Net 30, for example."
114
- - key: last_order
115
- label: "Last order"
116
- type: date
117
- kind: data
118
- means: "Date of the most recent confirmed order."
119
- - key: overdue_days
120
- label: "Overdue days"
121
- type: int
122
- kind: data
123
- means: "How many days late this customer is running against their own usual ordering rhythm."
124
- - key: est_missed
125
- label: "Est. missed $"
126
- type: currency
127
- kind: data
128
- means: "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
129
- - key: ar_open
130
- label: "AR current $"
131
- type: currency
132
- kind: data
133
- means: "Invoiced money owed but not yet due (a 5-day grace applies before it counts as overdue)."
134
- - key: ar_overdue
135
- label: "AR overdue $"
136
- type: currency
137
- kind: data
138
- means: "Invoiced money past due — same basis as the Collections page."
139
- - key: ar_outstanding
140
- label: "AR outstanding $"
141
- type: currency
142
- kind: data
143
- means: "Total invoiced money owed right now: AR current $ plus AR overdue $."
144
- - key: ar_exposure
145
- label: "Credit exposure $"
146
- type: currency
147
- kind: data
148
- means: "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
149
- - key: ar_aged_1_30
150
- label: "1-30 days $"
151
- type: currency
152
- kind: data
153
- means: "Overdue between 1 and 30 days. The four aging buckets sum to AR overdue $."
154
- - key: ar_aged_31_60
155
- label: "31-60 days $"
156
- type: currency
157
- kind: data
158
- means: "Overdue between 31 and 60 days. The four aging buckets sum to AR overdue $."
159
- - key: ar_aged_61_90
160
- label: "61-90 days $"
161
- type: currency
162
- kind: data
163
- means: "Overdue between 61 and 90 days. The four aging buckets sum to AR overdue $."
164
- - key: ar_aged_90_plus
165
- label: "90+ days $"
166
- type: currency
167
- kind: data
168
- means: "Overdue by more than 90 days. The four aging buckets sum to AR overdue $."
169
- - key: days_to_pay
170
- label: "Days to pay"
171
- type: int
172
- kind: data
173
- means: "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
174
- - key: top_category
175
- label: "Top category"
176
- type: text
177
- kind: data
178
- means: "The category this customer spent the most on in the last 12 months."
179
- - key: top_category_pct
180
- label: "Top category %"
181
- type: pct
182
- kind: data
183
- means: "Share of last-12-months spend that went to the top category."
184
- - key: sku_count
185
- label: "SKUs bought"
186
- type: int
187
- kind: data
188
- means: "Distinct products bought in the last 12 months."
189
- - key: top_sku
190
- label: "Top SKU"
191
- type: text
192
- kind: data
193
- means: "The product this customer spent the most on in the last 12 months."
194
- - key: days_since
195
- label: "Days since order"
196
- type: int
197
- kind: data
198
- means: "Days since the last confirmed order."
199
- - key: typical_gap_days
200
- label: "Typical gap days"
201
- type: int
202
- kind: data
203
- means: "Days this customer usually goes between orders, from their own history."
204
- - key: notes
205
- label: "Notes"
206
- type: text
207
- kind: data
208
- means: "Your notes on this customer. Saved in this app only, visible only to you."
209
-
210
- ai_context: >
211
- The customer REGISTRY as a person sees it in the app — the database labelled 'Odoo customers'.
212
- Use it to answer 'who is this customer', 'which customers exist', 'which agent owns them', 'where are they', and for the AR columns it carries (ar_open, ar_overdue, days_to_pay), which are reconciled by modules/ar.py.
213
- ⛔ For anything WINDOWED or at line grain go to sales_lines / customer_invoices / receivables — those topics own the time dimension and this one has none.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_invoices.yml DELETED
@@ -1,98 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_invoices
9
- label: "Odoo invoices"
10
- entity: account.move
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: ut_odoo_invoices
13
- subject: "odoo:account.move.customer"
14
- grain: "one row per posted CUSTOMER invoice or credit note (document grain)"
15
- scope:
16
- population: "move_type in (out_invoice, out_refund) AND state = posted"
17
- signs: "amount_residual_signed is POSITIVE for an invoice and NEGATIVE for a credit note, so summing it nets the credit notes correctly"
18
- store:
19
- table: account_move
20
- alias: m
21
- date_col: "m.invoice_date"
22
- dims:
23
- customer: {label: "Customer"}
24
- payment_state: {label: "Payment state"}
25
- move_type: {label: "Document type"}
26
-
27
- # key / label / type / kind, derived from the grid contract. `kind` says where the
28
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
29
- # from another topic; a `link` points at another database.
30
- fields:
31
- - key: invoice_no
32
- label: "Invoice"
33
- type: text
34
- kind: data
35
- - key: odoo_id
36
- label: "Odoo ID"
37
- type: int
38
- kind: data
39
- means: "The `account.move` id. Also this row's id."
40
- - key: customer
41
- label: "Customer"
42
- type: text
43
- kind: data
44
- - key: partner_id
45
- label: "Odoo partner id"
46
- type: int
47
- kind: data
48
- - key: invoice_date
49
- label: "Invoice date"
50
- type: date
51
- kind: data
52
- - key: due_date
53
- label: "Due date"
54
- type: date
55
- kind: data
56
- - key: residual
57
- label: "Outstanding $"
58
- type: currency
59
- kind: data
60
- means: "Odoo's signed residual. Exactly 0 on every settled document, which is why AR rollups need no filter."
61
- - key: amount_untaxed
62
- label: "Invoiced $"
63
- type: currency
64
- kind: data
65
- - key: payment_state
66
- label: "Payment state"
67
- type: select
68
- kind: data
69
- - key: move_type
70
- label: "Document"
71
- type: select
72
- kind: data
73
- - key: wholesale_scope
74
- label: "In wholesale scope"
75
- type: checkbox
76
- kind: data
77
- means: "Unticked = the GIFTWARE DEALS / Amazon channel, which every wholesale metric in this product excludes. The row is kept so no Odoo id is missing; filter on this column to reconcile against the AR page."
78
- - key: origin_order
79
- label: "Source order"
80
- type: text
81
- kind: data
82
- means: "Odoo's `invoice_origin` - usually the order name, sometimes blank."
83
- - key: order_link
84
- label: "Order record"
85
- type: link
86
- kind: link
87
- to_grid: ut_odoo_orders
88
- - key: refreshed
89
- label: "Refreshed"
90
- type: date
91
- kind: data
92
- means: "When this row was last reconciled against Odoo."
93
-
94
- ai_context: >
95
- Customer invoices at DOCUMENT grain — one row per invoice, not per line.
96
- Use it for AR questions: what is open, what is overdue, what was invoiced.
97
- For anything at product or line grain use invoice_lines; for the reconciled receivables view use receivables.
98
- `origin_order` is the single stored key that joins an invoice back to the order it was raised from.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_orders.yml DELETED
@@ -1,87 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_orders
9
- label: "Odoo orders"
10
- entity: sale.order
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: ut_odoo_orders
13
- subject: "odoo:sale.order"
14
- grain: "one row per confirmed sales order (document grain)"
15
- scope:
16
- population: "state in (sale, done) — quotations and cancellations excluded"
17
- vs_sales_orders: "⚠ DISTINCT from the `sales_orders` topic: that one is the wholesale-scoped analytical view (teams 5/6, house accounts excluded); THIS one is the registry a person opens as a grid, and carries the row set the app shows"
18
- store:
19
- table: sale_order
20
- alias: o
21
- date_col: "o.date_order"
22
- dims:
23
- customer: {label: "Customer"}
24
- team: {label: "Business unit"}
25
- state: {label: "State"}
26
- invoice_status: {label: "Invoice status"}
27
-
28
- # key / label / type / kind, derived from the grid contract. `kind` says where the
29
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
30
- # from another topic; a `link` points at another database.
31
- fields:
32
- - key: order_no
33
- label: "Order"
34
- type: text
35
- kind: data
36
- - key: odoo_id
37
- label: "Odoo ID"
38
- type: int
39
- kind: data
40
- means: "The `sale.order` id. Also this row's id."
41
- - key: customer
42
- label: "Customer"
43
- type: text
44
- kind: data
45
- - key: partner_id
46
- label: "Odoo partner id"
47
- type: int
48
- kind: data
49
- - key: order_date
50
- label: "Order date"
51
- type: date
52
- kind: data
53
- - key: amount_untaxed
54
- label: "Order $"
55
- type: currency
56
- kind: data
57
- - key: team
58
- label: "Business unit"
59
- type: select
60
- kind: data
61
- - key: state
62
- label: "State"
63
- type: select
64
- kind: data
65
- - key: invoice_status
66
- label: "Invoice status"
67
- type: select
68
- kind: data
69
- - key: wholesale_scope
70
- label: "In wholesale scope"
71
- type: checkbox
72
- kind: data
73
- means: "Unticked = the GIFTWARE DEALS / Amazon channel, which every wholesale metric in this product excludes. The row is kept so no Odoo id is missing; filter on this column to reconcile against the AR page."
74
- - key: invoices
75
- label: "Invoices"
76
- type: link
77
- kind: link
78
- to_grid: ut_odoo_invoices
79
- - key: refreshed
80
- label: "Refreshed"
81
- type: date
82
- kind: data
83
- means: "When this row was last reconciled against Odoo."
84
-
85
- ai_context: >
86
- Sales orders at DOCUMENT grain, as the app's grid shows them.
87
- ⛔ If you are asked for revenue, prefer `sales_lines` (line grain, wholesale scope) or `sales_orders` — this topic exists to describe the ORDER RECORD a person can open, and its scope is the grid's, not the analytical model's.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_products.yml DELETED
@@ -1,147 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_products
9
- label: "Odoo products"
10
- entity: product.product
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: product_data
13
- subject: "odoo:product.product"
14
- grain: "one row per SKU in the active catalogue — a CATALOGUE, not a dated event stream"
15
- scope:
16
- population: "every ACTIVE product, sold or not (measured 5,862). Deliberately not the sales-window universe: that lands at 2,717 and hides ~2,550 SKUs that have never sold in wholesale scope"
17
- identity: "the SKU code (`default_code`). ⚠ 33 active products carry NO code and are keyed `pid:<odoo product id>` instead, so every active product has exactly one row and none is dropped"
18
- merged: "W33-T44 retired `ut_odoo_products`, which presented this same subject on Odoo's product_id. This topic describes the SURVIVING database, `product_data`"
19
- no_date: "a catalogue has no date dimension; ask sales_lines for movement"
20
- store:
21
- table: product_product
22
- alias: pp
23
- # NO date_col — a registry is not a dated event stream. Stated rather than
24
- # omitted, so its absence reads as a fact and not as an unfinished file.
25
- dims:
26
- category: {label: "Category"}
27
- supplier: {label: "Supplier"}
28
-
29
- # key / label / type / kind, derived from the grid contract. `kind` says where the
30
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
31
- # from another topic; a `link` points at another database.
32
- fields:
33
- - key: code
34
- label: "SKU"
35
- type: text
36
- kind: data
37
- means: "The SKU code — the product's real business key. `pid` is a stable CRC32 of it because the grid keys on an integer."
38
- - key: product
39
- label: "Product"
40
- type: text
41
- kind: data
42
- means: "Product name as it appears in Odoo."
43
- - key: category
44
- label: "Category"
45
- type: select
46
- kind: data
47
- means: "Product category; '(uncategorized)' when Odoo carries none."
48
- - key: supplier
49
- label: "Supplier"
50
- type: text
51
- kind: data
52
- means: "Who makes it. Editable here and shared with everyone in the workspace; seeded from the inventory mastersheet."
53
- - key: origin_country
54
- label: "Country"
55
- type: text
56
- kind: data
57
- means: "Country of origin. Editable here and shared with everyone; seeded from the inventory mastersheet."
58
- - key: lead_days
59
- label: "Lead time (days)"
60
- type: int
61
- kind: data
62
- means: "Order-to-arrival days for this supplier. Drives the buy signal. Editable and shared with everyone."
63
- - key: first_cost
64
- label: "First cost"
65
- type: currency
66
- kind: data
67
- means: "Quoted unit cost at origin, before freight and duty. Editable and shared with everyone."
68
- - key: price_fisch
69
- label: "Fisch price"
70
- type: currency
71
- kind: data
72
- means: "Fisch pricelist price for this SKU. Blank when that list prices it nowhere."
73
- - key: price_royal_1
74
- label: "Royal 1 price"
75
- type: currency
76
- kind: data
77
- means: "Royal 1 pricelist price for this SKU. Blank when that list prices it nowhere."
78
- - key: price_royal_2
79
- label: "Royal 2 price"
80
- type: currency
81
- kind: data
82
- means: "Royal 2 pricelist price for this SKU. Blank when that list prices it nowhere."
83
- - key: rev_ytd
84
- label: "Revenue YTD"
85
- type: currency
86
- kind: data
87
- means: "Year-to-date revenue for this SKU, BU-scoped when the caller is."
88
- - key: rev_ly
89
- label: "Revenue LY"
90
- type: currency
91
- kind: data
92
- means: "Same period last year — seasonal wholesale compares like for like."
93
- - key: yoy_pct
94
- label: "YoY %"
95
- type: pct
96
- kind: data
97
- means: "Year-over-year change; null when last year was zero (a ratio to zero is not a number)."
98
- - key: qty_ytd
99
- label: "Units YTD"
100
- type: int
101
- kind: data
102
- means: "Units sold year to date."
103
- - key: orders_ytd
104
- label: "Orders YTD"
105
- type: int
106
- kind: data
107
- means: "Distinct orders containing this SKU, year to date."
108
- - key: on_hand
109
- label: "On hand"
110
- type: int
111
- kind: data
112
- means: "Units in stock. CONSOLIDATED — one physical warehouse, not brand-tagged, so this column is ABSENT for a BU-scoped caller rather than silently company-wide."
113
- - key: unit_cost
114
- label: "Unit cost"
115
- type: currency
116
- kind: data
117
- means: "Inventory unit cost. Consolidated; absent for a BU-scoped caller."
118
- - key: inv_value
119
- label: "Stock value"
120
- type: currency
121
- kind: data
122
- means: "On-hand value at cost. Consolidated; absent for a BU-scoped caller."
123
- - key: qty_ltm
124
- label: "Units LTM"
125
- type: int
126
- kind: data
127
- means: "Units sold in the last twelve months. Consolidated; absent for a BU-scoped caller."
128
- - key: dos
129
- label: "Days of supply"
130
- type: int
131
- kind: data
132
- means: "Days of supply at the LTM rate; null means it never sells through. Consolidated; absent for a BU-scoped caller."
133
- - key: cover_gap_d
134
- label: "Cover gap (days)"
135
- type: int
136
- kind: data
137
- means: "Days of supply minus lead time. Negative means it runs out before a reorder lands."
138
- - key: stock_bucket
139
- label: "Stock status"
140
- type: select
141
- kind: data
142
- means: "Dead / excess / healthy bucket from the inventory module. Consolidated; absent for a BU-scoped caller."
143
-
144
- ai_context: >
145
- The product CATALOGUE — the database labelled 'Odoo products'.
146
- Use it for 'what do we sell', 'what does it cost' (first_cost/unit_cost), 'who supplies it', 'what is on hand' and the stock-coverage columns.
147
- ⛔ Revenue and unit columns here are WINDOWED SNAPSHOTS (rev_ytd, qty_ltm); for any other window, or for line grain, go to sales_lines.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/model/topics/odoo_vendors.yml DELETED
@@ -1,103 +0,0 @@
1
- # ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
2
- # the databases a person actually opens, not only the line and document grains.
3
- #
4
- # ⛔ THE `fields:` BLOCK IS GENERATED FROM THE GRID'S OWN FIELD CONTRACT
5
- # and is held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a
6
- # field row: add the column to the grid contract and re-emit, or the agent is being
7
- # trained on a schema the product does not have.
8
- key: odoo_vendors
9
- label: "Odoo vendors"
10
- entity: res.partner
11
- # The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
12
- grid: ut_odoo_vendors
13
- subject: "odoo:res.partner.vendor"
14
- grain: "one row per partner we have posted a vendor bill to"
15
- scope:
16
- population: "DERIVED FROM THE BILLS — a partner with no posted vendor bill has no payable history to show, so the bill is the population"
17
- asymmetry: "deliberately unlike odoo_customers, which is NOT derived from its documents; there is no second document universe for vendors"
18
- overlap: "measured: only 9 of the vendors also appear in the customer population, so a vendor is not a customer row"
19
- store:
20
- table: res_partner
21
- alias: p
22
- # NO date_col — a registry is not a dated event stream. Stated rather than
23
- # omitted, so its absence reads as a fact and not as an unfinished file.
24
- dims:
25
- country: {label: "Country"}
26
-
27
- # key / label / type / kind, derived from the grid contract. `kind` says where the
28
- # value COMES FROM: a `data` column is stored on the row; a `rollup` is computed
29
- # from another topic; a `link` points at another database.
30
- fields:
31
- - key: vendor
32
- label: "Vendor"
33
- type: text
34
- kind: data
35
- - key: odoo_id
36
- label: "Odoo ID"
37
- type: int
38
- kind: data
39
- means: "The `res.partner` id. Also this row's id."
40
- - key: vendor_id
41
- label: "Odoo vendor id"
42
- type: int
43
- kind: data
44
- - key: country
45
- label: "Country"
46
- type: text
47
- kind: data
48
- - key: email
49
- label: "Email"
50
- type: text
51
- kind: data
52
- - key: phone
53
- label: "Phone"
54
- type: text
55
- kind: data
56
- - key: mobile
57
- label: "Mobile"
58
- type: text
59
- kind: data
60
- - key: vat
61
- label: "Tax ID"
62
- type: text
63
- kind: data
64
- means: "Odoo `vat` — the vendor's tax/VAT registration number."
65
- - key: vendor_ref
66
- label: "Vendor reference"
67
- type: text
68
- kind: data
69
- means: "Odoo `res.partner.ref` — our internal reference for this vendor."
70
- - key: website
71
- label: "Website"
72
- type: url
73
- kind: data
74
- - key: street
75
- label: "Street"
76
- type: text
77
- kind: data
78
- - key: street2
79
- label: "Street 2"
80
- type: text
81
- kind: data
82
- - key: city
83
- label: "City"
84
- type: text
85
- kind: data
86
- - key: zip
87
- label: "ZIP"
88
- type: text
89
- kind: data
90
- - key: bills
91
- label: "Bills"
92
- type: link
93
- kind: link
94
- to_grid: ut_odoo_bills
95
- - key: refreshed
96
- label: "Refreshed"
97
- type: date
98
- kind: data
99
- means: "When this row was last reconciled against Odoo."
100
-
101
- ai_context: >
102
- The vendor/supplier registry, with contact and tax identity (W33-T48 widened it from 5 columns to 15 after a census found 76 populated fields on the underlying partner)
103
- ⚠ The contact columns are SPARSE by nature — measured 65/393 with an email, 13/393 with a tax id — so 'blank' means Odoo has no value, never that the sync failed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/public/brand/SOURCES.md DELETED
@@ -1,83 +0,0 @@
1
- # Connector brand marks — where every file came from
2
-
3
- **Wave 33 · owner item 6 · ruling R4 · ticket `W33-T60`. Fetched 2026-08-14.**
4
-
5
- > Owner, verbatim: *"Do not generate your own logo for Connectors, they look really uncanny
6
- > /browse them the PNG, cut appropriately for our needs, verify visually"*.
7
-
8
- ⛔ **EVERY FILE IN THIS DIRECTORY IS THE VENDOR'S OWN ARTWORK, FETCHED FROM A HOST THE VENDOR
9
- CONTROLS.** Nothing here is drawn, traced, redrawn or "inspired by". That is the whole point of the
10
- ruling: the marks that shipped before this wave were hand-authored *simplifications* — honest about
11
- being simplifications in their own header comment, and the owner still read them as uncanny. **A
12
- hand-drawn substitute filed here as official artwork would be the violation**, so a brand we cannot
13
- obtain officially keeps its hand-drawn mark and is listed under MISSES below rather than faked.
14
-
15
- ⚠ **`webhooks` and `scraper` are deliberately NOT here.** They are house glyphs in `currentColor`
16
- (`connectors/brandMarks.tsx`) because they are *ours* — there is no vendor and no official artwork to
17
- fetch. Adding a picture for either would be inventing a brand, which is the thing this file exists to
18
- prevent.
19
-
20
- ## The cut (identical for all nine, so the marks sit on one grid)
21
-
22
- `_cut_brand.py`, beside these files (the `_` prefix is what keeps it out of the deploy — `deploy_web.
23
- py::_web_source_files` skips any path PART starting with one, so the recipe lives with the artwork
24
- without riding into the image). Four steps: load RGBA → *(lockups only)* keep the leftmost ink block →
25
- trim to the alpha bounding box → fit the longest edge to **116 px** and centre it on a transparent
26
- **128×128** canvas. So every mark has the same optical size and the same 6 px breathing room, which
27
- is what R4's *"trimmed to a consistent square"* means in practice. **The originals are never
28
- modified** — the transform reads the vendor's file and writes a new one.
29
-
30
- ⚠ **Two marks carry their OWN ground and that is the vendor's design, not our padding**: TikTok's app
31
- icon is a black rounded square and Stripe's press icon is a solid `#635BFF` square. They are left
32
- exactly as the vendor draws them — squaring them onto a transparent canvas would be redrawing the
33
- mark, and both already read correctly on a light *and* a dark chip, which is the property the
34
- hand-drawn set was built for.
35
-
36
- ## The nine
37
-
38
- | key | file | vendor's brand/press page | the exact asset fetched | what was cut |
39
- |---|---|---|---|---|
40
- | `instagram` | `instagram.png` | https://about.meta.com/brand/resources/instagram/instagram-brand/ | `IG_brand_asset_pack_2023.zip` → `01 Static Glyph/01 Gradient Glyph/Instagram_Glyph_Gradient.png` (5000×5000) | trim + fit only |
41
- | `tiktok` | `tiktok.png` | https://www.tiktok.com/about/brand | `https://www.tiktok.com/apple-touch-icon.png` (400×400) | trim + fit only |
42
- | `odoo` | `odoo.png` | https://www.odoo.com/page/brand-assets | `https://odoocdn.com/openerp_website/static/src/img/assets/png/odoo_logo.png` (621×196) | **the leading `o`**, isolated by Odoo's own brand purple `#714B67` — see the note below |
43
- | `google` | `google.png` | https://about.google/brand-resource-center/ | `https://www.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png` (128×128) | trim + fit only |
44
- | `gmail` | `gmail.png` | https://workspace.google.com/ (gstatic product branding) | `https://www.gstatic.com/images/branding/product/2x/gmail_2020q4_48dp.png` (96×96) | trim + fit only |
45
- | `slack` | `slack.png` | https://slack.com/media-kit | `https://a.slack-edge.com/80588/marketing/img/icons/icon_slack_hash_colored.png` (400×400) | trim + fit only |
46
- | `meta` | `meta.png` | https://about.meta.com/brand/resources/meta/company-brand/ | `Meta_Company-Lockup.zip` → `1 Positive Primary/RGB/Meta_lockup_positive primary_RGB.png` (29011×12501) | **first-block crop**: the pack ships the *lockup* (glyph + wordmark); the glyph is the leftmost ink block, 6272 px wide |
47
- | `stripe` | `stripe.png` | https://stripe.com/newsroom/brand-assets | `https://images.ctfassets.net/fzn2n1nzq965/HTTOloNPhisV9P4hlMPNA/…/Stripe_icon_-_square.svg` (400×400, rasterised at 1024) | trim + fit only |
48
- | `shopify` | `shopify.png` | https://www.shopify.com/brand-assets | `shopify-shopping-bag.zip` → `02 - Glyph/png/shopify_glyph.png` (600×683) | trim + fit only |
49
-
50
- ## ⚠ The one judgement call, stated rather than buried — `odoo`
51
-
52
- **Odoo publishes no square glyph.** Its brand-assets page offers the wordmark (`odoo_logo.png`, its
53
- inverted twin, and an SVG) and ~200 *app* icons — and the app icons are not the company mark: the one
54
- served by `odoo.com/web/image/website/1/logo` is a grey camera placeholder and
55
- `icons/base/…/icon.png` is a teal cube, both of which were fetched, looked at, and rejected here. A
56
- 621×196 wordmark fitted into a 128 px square renders as an illegible smear at the 15 px the chips
57
- actually use.
58
-
59
- So the cut is **the leading `o`**, isolated from the official PNG by selecting the pixels in Odoo's
60
- own brand purple `#714B67` — which is exactly the part of that wordmark Odoo draws in the brand colour
61
- while the trailing `doo` is grey `#8f8f8f` (visible in the official SVG as two separate `<path>`
62
- elements). It is a CUT of the vendor's artwork, at the vendor's colour, which is the owner's
63
- instruction; it is not a redraw. **If a square Odoo glyph is ever published, this is the one row in
64
- the table to revisit.**
65
-
66
- ## MISSES — none
67
-
68
- All nine marks in `BRAND_OF_CONNECTOR` that name a real company were obtained. Recorded explicitly
69
- because "no misses" has to be a stated finding rather than an absence a reader has to infer — the
70
- standing rule (wave-30 R6) is that a limit which cannot be removed is *reported* with its cause and a
71
- recommended fix, and its second sentence is the half that gets dropped.
72
-
73
- ## How to add one
74
-
75
- 1. Find the vendor's own brand/press page and take the **glyph** (not the lockup) at the largest size
76
- offered — SVG if there is one, PNG otherwise.
77
- 2. Drop it beside `_cut_brand.py`, add a `JOBS` row (second element `True` if it is a lockup),
78
- run it, and **look at the contact sheet on both grounds** before committing.
79
- 3. Add the row to the table above with the page URL, the asset URL, and what was cut.
80
- 4. Add the key to `BRAND_OF_CONNECTOR` in `connectors/brandMarks.tsx`.
81
-
82
- ⛔ Steps 3 and 4 are not optional and `aios-web/api/verify_meta.py` checks both: a file with no row
83
- here has no provenance, and a file with no map entry is served by a door nothing asks.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/public/brand/gmail.png DELETED
Binary file (6.5 kB)
 
web/public/brand/google.png DELETED
Binary file (8.29 kB)
 
web/public/brand/instagram.png DELETED
Binary file (15.1 kB)
 
web/public/brand/meta.png DELETED
Binary file (9.12 kB)
 
web/public/brand/odoo.png DELETED
Binary file (7.43 kB)
 
web/public/brand/shopify.png DELETED
Binary file (8.85 kB)
 
web/public/brand/slack.png DELETED
Binary file (7.46 kB)
 
web/public/brand/stripe.png DELETED
Binary file (2.89 kB)
 
web/public/brand/tiktok.png DELETED
Binary file (6.84 kB)
 
web/src/ai-agent/AiAgentPage.tsx DELETED
@@ -1,237 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // ai-agent/AiAgentPage.tsx — WAVE 33 · W33-T54/T55 (owner item 7, ruling R3).
3
- //
4
- // Owner: *"collapse the web browser into an AI agent module that builds the flow
5
- // for you"*, and *"lay out the foundation with custom tools we provide"*. The
6
- // tools are the action catalog. This page is the door to them: one box, one
7
- // draft, one Accept.
8
- //
9
- // ⛔ THE DRAFT IS SHOWN BEFORE ANYTHING IS SAVED, and that is T54's `done-when`
10
- // rather than a nicety. The one failure class no validator can catch is a
11
- // well-formed flow that does something OTHER than what was asked for, and the
12
- // only thing that catches it is a person reading the steps. So `draftFlow`
13
- // writes nothing, the steps are painted in full, and `Accept` is a separate
14
- // click through the ORDINARY create door.
15
- //
16
- // ⛔ AND WHAT `clean_actions` CHANGED IS SHOWN TOO. It drops a config key it does
17
- // not recognise and answers 200 (D-75), so a draft accepted without that
18
- // disclosure would open as a flow the person was never shown. `dropped` is
19
- // painted as plainly as the steps are.
20
- //
21
- // ⚠ C4: no `index.css` rule is added or changed here. This module ships its own
22
- // co-located sheet, which is the established practice (`query.css`,
23
- // `SwipeView.css`, `navExtras.css`) and the contract for every lane but B.
24
- // ---------------------------------------------------------------------------
25
-
26
- import { useState } from "react";
27
-
28
- import { acceptDraft, draftFlow, type Draft, type DraftResult } from "./aiAgentApi";
29
- import "./aiAgent.css";
30
-
31
- /** The examples under the box. Deliberately three, deliberately short, deliberately concrete. */
32
- const EXAMPLES = [
33
- "Go to each supplier's website and read the price into the Price column",
34
- "Every Monday, find the new rows in Leads and enrich the Instagram profiles",
35
- "Open each product page, click Accept cookies, then read the stock count",
36
- ];
37
-
38
- export default function AiAgentPage() {
39
- const [prompt, setPrompt] = useState("");
40
- const [busy, setBusy] = useState(false);
41
- const [problem, setProblem] = useState("");
42
- const [result, setResult] = useState<DraftResult | null>(null);
43
- const [saved, setSaved] = useState("");
44
-
45
- const ask = async (text?: string) => {
46
- const q = (text ?? prompt).trim();
47
- if (!q || busy) return;
48
- setBusy(true);
49
- setProblem("");
50
- setResult(null);
51
- setSaved("");
52
- const r = await draftFlow(q);
53
- setBusy(false);
54
- if (!r.ok) {
55
- // ⚠ THE SERVER'S OWN SENTENCE, PRINTED. A refusal here is usually the model saying "this
56
- // needs a step this tool does not have", which is the most useful thing on the screen —
57
- // rewriting it into "something went wrong" would throw away the only answer.
58
- setProblem(r.message);
59
- return;
60
- }
61
- setResult(r.value);
62
- };
63
-
64
- const accept = async (draft: Draft) => {
65
- if (busy) return;
66
- setBusy(true);
67
- setProblem("");
68
- const r = await acceptDraft(draft);
69
- setBusy(false);
70
- if (!r.ok) {
71
- setProblem(r.message);
72
- return;
73
- }
74
- setSaved(r.value.id);
75
- };
76
-
77
- return (
78
- <div className="aiagent">
79
- <h2 className="aiagent-h">Describe what you want, and I will build the steps</h2>
80
- <p className="aiagent-sub">
81
- I can only use the steps this tool already has. If what you ask for needs something that
82
- is not built, I will say so rather than guess.
83
- </p>
84
-
85
- <textarea
86
- id="aiagent-prompt"
87
- className="aiagent-box"
88
- rows={3}
89
- placeholder="Go to this website, do this…"
90
- value={prompt}
91
- disabled={busy}
92
- onChange={(e) => setPrompt(e.target.value)}
93
- />
94
- <div className="aiagent-actions">
95
- <button
96
- type="button"
97
- className="aiagent-go"
98
- disabled={busy || !prompt.trim()}
99
- onClick={() => void ask()}
100
- >
101
- {busy ? "Thinking…" : "Draft the steps"}
102
- </button>
103
- {/* ⚠ SAYS WHAT IT WILL NOT DO. "Draft" is a promise about writing, and a person about to
104
- hand a description to an AI is entitled to know the answer is not going live. */}
105
- <span className="aiagent-note">Nothing is saved until you accept it.</span>
106
- </div>
107
-
108
- {!result && !problem ? (
109
- <div className="aiagent-eg">
110
- <p className="aiagent-eg-h">For example</p>
111
- {EXAMPLES.map((e) => (
112
- <button
113
- key={e}
114
- type="button"
115
- className="aiagent-eg-row"
116
- disabled={busy}
117
- onClick={() => {
118
- setPrompt(e);
119
- void ask(e);
120
- }}
121
- >
122
- {e}
123
- </button>
124
- ))}
125
- </div>
126
- ) : null}
127
-
128
- {problem ? <p className="aiagent-problem">{problem}</p> : null}
129
-
130
- {result ? (
131
- <div className="aiagent-draft">
132
- <h3 className="aiagent-draft-h">{result.draft.name}</h3>
133
- <p className="aiagent-draft-sub">
134
- Starts on: {result.draft.trigger || "manual"}
135
- {result.draft.table ? ` · walks ${result.draft.table}` : ""}
136
- {result.provider ? ` · drafted by ${result.provider}` : ""}
137
- </p>
138
-
139
- <ol className="aiagent-steps">
140
- {result.draft.actions.map((a, i) => (
141
- <li key={a.id} className="aiagent-step">
142
- <span className="aiagent-step-n">{i + 1}</span>
143
- <div className="aiagent-step-body">
144
- <p className="aiagent-step-kind">{a.kind}</p>
145
- {a.why ? <p className="aiagent-step-why">{a.why}</p> : null}
146
- {/* ⛔ THE CONFIG IS PAINTED, NOT SUMMARISED. "Reads a page" tells a person
147
- nothing they can check; the URL and the selector are the whole of what they
148
- are being asked to approve. */}
149
- {Object.entries(a.config)
150
- .filter(([, v]) => v !== "" && v !== false && v !== null && v !== undefined)
151
- .map(([k, v]) => (
152
- <p key={k} className="aiagent-step-cfg">
153
- <span className="aiagent-step-key">{k}</span> {String(v)}
154
- </p>
155
- ))}
156
- {/*
157
- ⛔⛔ THE BLANKS, SHOWN. Skipping empty values is right on its own, and the
158
- system prompt telling the model to leave a setting blank rather than invent it
159
- is right on its own — together they made an UNFINISHED step paint as a finished
160
- one: a `web_read` with no selector and no target column rendered as url + attr
161
- + timeout and nothing else, and the create door then accepted it. A person
162
- approved a step that reads nothing into nowhere, having been shown no blank.
163
- Found by the verifier on this ticket, not by a gate.
164
- ⚠ The words are the SERVER's (`action_needs`), so this line, the builder's
165
- Configured label and the run refusal all say the same thing.
166
- */}
167
- {a.needs.length ? (
168
- <p className="aiagent-step-needs">
169
- Still needs {a.needs.join(", ")} — you can fill it in after you accept.
170
- </p>
171
- ) : null}
172
- {a.unknownField ? (
173
- <p className="aiagent-step-needs">
174
- There is no column called {a.unknownField} on that database, so this step
175
- would write nowhere. Pick the column after you accept.
176
- </p>
177
- ) : null}
178
- </div>
179
- </li>
180
- ))}
181
- </ol>
182
-
183
- {/* ⛔ WHOLE-DRAFT DISCLOSURES — a step list the door truncated, a trigger this
184
- deployment does not have. Standing rule (W30/R6): a limit that cannot be removed
185
- must be REPORTED with its cause and a recommended fix, and a silent truncation IS
186
- the violation. The draft door caps at 12 steps while the engine stores 20, so a
187
- longer answer lost steps that would have been storable. */}
188
- {result.notes.length ? (
189
- <div className="aiagent-dropped">
190
- {result.notes.map((n) => (
191
- <p key={n} className="aiagent-dropped-h">{n}</p>
192
- ))}
193
- </div>
194
- ) : null}
195
-
196
- {result.dropped.length ? (
197
- <div className="aiagent-dropped">
198
- <p className="aiagent-dropped-h">
199
- Some settings were changed to fit what this tool accepts:
200
- </p>
201
- {result.dropped.map((d) => (
202
- <p key={d.kind + d.keys.join()} className="aiagent-dropped-row">
203
- {d.kind}: {d.keys.join(", ")}
204
- </p>
205
- ))}
206
- </div>
207
- ) : null}
208
-
209
- {saved ? (
210
- <p className="aiagent-saved">
211
- Saved. It is an ordinary automation now — open it from Automation to edit any step.
212
- </p>
213
- ) : (
214
- <div className="aiagent-actions">
215
- <button
216
- type="button"
217
- className="aiagent-go"
218
- disabled={busy}
219
- onClick={() => void accept(result.draft)}
220
- >
221
- Accept and create it
222
- </button>
223
- <button
224
- type="button"
225
- className="aiagent-again"
226
- disabled={busy}
227
- onClick={() => void ask()}
228
- >
229
- Try again
230
- </button>
231
- </div>
232
- )}
233
- </div>
234
- ) : null}
235
- </div>
236
- );
237
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/ai-agent/aiAgent.css DELETED
@@ -1,279 +0,0 @@
1
- /* ---------------------------------------------------------------------------
2
- ai-agent/aiAgent.css — the AI agent module's own stylesheet
3
- (WAVE 33, owner item 7, ruling R3).
4
-
5
- Shipped BESIDE its component, following `query/query.css` and the
6
- `FormInterface.css` / `SwipeView.css` precedent, rather than added to
7
- `index.css` — which is B's file this wave (contract C4). Vite carries the
8
- import; the node shim in `verify_ui` already stubs a CSS require for exactly
9
- this shape.
10
-
11
- Deliberately shaped like the Query page it sits beside: same page padding,
12
- same card surfaces, same title scale. The two are the same kind of thing —
13
- describe something in words, read what came back before it is committed — and
14
- a person should not have to learn two layouts to do it.
15
-
16
- ⛔ EVERY FONT SIZE IS A `--lp-fs-*` TOKEN AND EVERY COLOUR A `--lp-*` TOKEN.
17
- Wave-21 R5 is gated over every stylesheet under src, not just index.css, and
18
- one literal here reds `web_ui` for the whole tree.
19
-
20
- ⛔ NO EMOJIS AND NO ALL-CAPS CHROME (DESIGN.md R6).
21
-
22
- ⛔⛔ AND NOTHING IN THIS COMMENT MAY CONTAIN THE TWO CHARACTERS THAT CLOSE IT.
23
- A path glob written out in a sibling stylesheet's header spelled the
24
- terminator, the comment ended mid-sentence, and `lightningcss` then died on
25
- the first backtick after it. `tsc` passed and vite transformed every module;
26
- the failure surfaced in the MINIFIER, nowhere near its cause.
27
- --------------------------------------------------------------------------- */
28
-
29
- .aiagent {
30
- height: 100%;
31
- overflow-y: auto;
32
- padding: 34px 44px 56px;
33
- box-sizing: border-box;
34
- background: var(--lp-wash);
35
- }
36
-
37
- .aiagent-h {
38
- margin: 0 0 6px;
39
- font-size: var(--lp-fs-lg);
40
- font-weight: 650;
41
- color: var(--lp-ink);
42
- }
43
-
44
- .aiagent-sub {
45
- margin: 0 0 18px;
46
- max-width: 62ch;
47
- font-size: var(--lp-fs-sm);
48
- line-height: var(--lp-lh);
49
- color: var(--lp-muted);
50
- }
51
-
52
- .aiagent-box {
53
- display: block;
54
- width: 100%;
55
- max-width: 74ch;
56
- padding: 12px 14px;
57
- box-sizing: border-box;
58
- font: inherit;
59
- font-size: var(--lp-fs-sm);
60
- line-height: var(--lp-lh);
61
- color: var(--lp-ink);
62
- background: var(--lp-surface);
63
- border: 1px solid var(--lp-line);
64
- border-radius: var(--lp-r-md);
65
- resize: vertical;
66
- }
67
-
68
- .aiagent-box:focus {
69
- outline: none;
70
- border-color: var(--lp-blue-solid);
71
- }
72
-
73
- .aiagent-actions {
74
- display: flex;
75
- align-items: center;
76
- gap: 12px;
77
- margin: 12px 0 0;
78
- flex-wrap: wrap;
79
- }
80
-
81
- .aiagent-go {
82
- padding: 8px 16px;
83
- font: inherit;
84
- font-size: var(--lp-fs-sm);
85
- font-weight: 600;
86
- color: var(--lp-surface);
87
- background: var(--lp-blue-solid);
88
- border: 1px solid var(--lp-blue-solid);
89
- border-radius: var(--lp-r-md);
90
- cursor: pointer;
91
- }
92
-
93
- .aiagent-go:disabled {
94
- opacity: 0.5;
95
- cursor: default;
96
- }
97
-
98
- .aiagent-again {
99
- padding: 8px 16px;
100
- font: inherit;
101
- font-size: var(--lp-fs-sm);
102
- color: var(--lp-ink);
103
- background: var(--lp-surface);
104
- border: 1px solid var(--lp-line);
105
- border-radius: var(--lp-r-md);
106
- cursor: pointer;
107
- }
108
-
109
- .aiagent-again:disabled {
110
- opacity: 0.5;
111
- cursor: default;
112
- }
113
-
114
- .aiagent-note {
115
- font-size: var(--lp-fs-2xs);
116
- color: var(--lp-muted);
117
- }
118
-
119
- .aiagent-eg {
120
- margin: 26px 0 0;
121
- max-width: 74ch;
122
- }
123
-
124
- .aiagent-eg-h {
125
- margin: 0 0 8px;
126
- font-size: var(--lp-fs-2xs);
127
- color: var(--lp-muted);
128
- }
129
-
130
- .aiagent-eg-row {
131
- display: block;
132
- width: 100%;
133
- margin: 0 0 8px;
134
- padding: 10px 14px;
135
- text-align: left;
136
- font: inherit;
137
- font-size: var(--lp-fs-sm);
138
- color: var(--lp-ink);
139
- background: var(--lp-surface);
140
- border: 1px solid var(--lp-line);
141
- border-radius: var(--lp-r-md);
142
- cursor: pointer;
143
- }
144
-
145
- .aiagent-eg-row:disabled {
146
- opacity: 0.5;
147
- cursor: default;
148
- }
149
-
150
- .aiagent-problem {
151
- margin: 18px 0 0;
152
- max-width: 74ch;
153
- padding: 10px 14px;
154
- font-size: var(--lp-fs-sm);
155
- line-height: var(--lp-lh);
156
- color: var(--lp-red-deep);
157
- background: var(--lp-surface);
158
- border: 1px solid var(--lp-red-deep);
159
- border-radius: var(--lp-r-md);
160
- }
161
-
162
- .aiagent-draft {
163
- margin: 26px 0 0;
164
- max-width: 74ch;
165
- padding: 18px 20px;
166
- background: var(--lp-surface);
167
- border: 1px solid var(--lp-line);
168
- border-radius: var(--lp-r-md);
169
- }
170
-
171
- .aiagent-draft-h {
172
- margin: 0 0 4px;
173
- font-size: var(--lp-fs-md);
174
- font-weight: 650;
175
- color: var(--lp-ink);
176
- }
177
-
178
- .aiagent-draft-sub {
179
- margin: 0 0 16px;
180
- font-size: var(--lp-fs-2xs);
181
- color: var(--lp-muted);
182
- }
183
-
184
- .aiagent-steps {
185
- margin: 0;
186
- padding: 0;
187
- list-style: none;
188
- }
189
-
190
- .aiagent-step {
191
- display: flex;
192
- gap: 12px;
193
- padding: 12px 0;
194
- border-top: 1px solid var(--lp-line);
195
- }
196
-
197
- .aiagent-step-n {
198
- flex: none;
199
- width: 22px;
200
- height: 22px;
201
- display: inline-flex;
202
- align-items: center;
203
- justify-content: center;
204
- font-size: var(--lp-fs-2xs);
205
- font-weight: 600;
206
- color: var(--lp-muted);
207
- background: var(--lp-surface-2);
208
- border-radius: 999px;
209
- }
210
-
211
- .aiagent-step-body {
212
- min-width: 0;
213
- }
214
-
215
- .aiagent-step-kind {
216
- margin: 0;
217
- font-size: var(--lp-fs-sm);
218
- font-weight: 600;
219
- color: var(--lp-ink);
220
- }
221
-
222
- .aiagent-step-why {
223
- margin: 2px 0 6px;
224
- font-size: var(--lp-fs-2xs);
225
- line-height: var(--lp-lh);
226
- color: var(--lp-muted);
227
- }
228
-
229
- .aiagent-step-cfg {
230
- margin: 0;
231
- font-size: var(--lp-fs-2xs);
232
- line-height: var(--lp-lh);
233
- color: var(--lp-ink);
234
- overflow-wrap: anywhere;
235
- }
236
-
237
- .aiagent-step-key {
238
- display: inline-block;
239
- min-width: 84px;
240
- color: var(--lp-muted);
241
- }
242
-
243
- .aiagent-dropped {
244
- margin: 14px 0 0;
245
- padding: 10px 14px;
246
- background: var(--lp-surface-2);
247
- border-left: 3px solid var(--lp-yellow-deep);
248
- border-radius: var(--lp-r-md);
249
- }
250
-
251
- .aiagent-dropped-h {
252
- margin: 0 0 4px;
253
- font-size: var(--lp-fs-2xs);
254
- font-weight: 600;
255
- color: var(--lp-ink);
256
- }
257
-
258
- .aiagent-dropped-row {
259
- margin: 0;
260
- font-size: var(--lp-fs-2xs);
261
- color: var(--lp-muted);
262
- }
263
-
264
- .aiagent-saved {
265
- margin: 16px 0 0;
266
- font-size: var(--lp-fs-sm);
267
- line-height: var(--lp-lh);
268
- color: var(--lp-ink);
269
- }
270
-
271
- /* The per-step disclosures: a required setting the assistant left blank (it was told to leave one
272
- blank rather than invent it), and a column the target database does not have. Toned like a
273
- warning rather than an error, because neither stops the draft being accepted and fixed. */
274
- .aiagent-step-needs {
275
- margin: 4px 0 0;
276
- font-size: var(--lp-fs-2xs);
277
- line-height: var(--lp-lh);
278
- color: var(--lp-yellow-deep);
279
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/ai-agent/aiAgentApi.ts DELETED
@@ -1,197 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // ai-agent/aiAgentApi.ts — WAVE 33 · W33-T54/T55 (owner item 7, ruling R3):
3
- // two calls, and nothing else.
4
- //
5
- // Shaped like `query/queryApi.ts` — the same `Result<T>`, the same 4xx/5xx
6
- // message split — because the failure that matters is identical: a wrong
7
- // `credentials` word produces no client-side symptom at all, just a 401 from a
8
- // server that never saw a session.
9
- //
10
- // ⛔ DRAFTING AND SAVING ARE TWO DIFFERENT DOORS, AND THAT IS RULING R3, NOT A
11
- // convenience. `draftFlow` writes NOTHING; accepting a draft calls the ORDINARY
12
- // `POST /automations` that the New-automation button has always called. R3 asks
13
- // for a flow "indistinguishable from a hand-built one", and the way to get that
14
- // is for there to be no second write path — not for a second one to be written
15
- // carefully enough to look the same.
16
- //
17
- // ⚠ NO CLIENT UNION OVER `kind`. The action kinds are the server's vocabulary
18
- // and arrive as strings (the wave-9 law): a client
19
- // `type Kind = "web_read" | …` turns "the server added a kind" into "the client
20
- // drops the step".
21
- // ---------------------------------------------------------------------------
22
-
23
- import { API_V1, CREDENTIALS } from "../apiContract";
24
-
25
- export type Result<T> =
26
- | { ok: true; value: T }
27
- | { ok: false; status: number; message: string };
28
-
29
- /** One step of a drafted flow — the CLEANED config, plus the model's own reason for it. */
30
- export interface DraftAction {
31
- id: string;
32
- /** A STRING, never a union — see the header. */
33
- kind: string;
34
- config: Record<string, unknown>;
35
- /** One sentence: why the assistant put this step here. May be "". */
36
- why: string;
37
- /**
38
- * ⛔ WHAT THIS STEP IS STILL MISSING, in the words the runner uses — straight off the server's
39
- * `action_needs`, the same predicate the builder's Configured label and the run refusal read.
40
- * The system prompt tells the model to leave a setting BLANK rather than invent it, and this
41
- * page skips empty values; together those two right decisions made an unfinished step paint as
42
- * a finished one, and the create door then accepted it. Empty is the ordinary case.
43
- */
44
- needs: string[];
45
- /**
46
- * ⛔ A COLUMN THE TARGET DATABASE DOES NOT HAVE, when the assistant named one. Usually the
47
- * column's LABEL where its key was wanted — which is what a person would say, so it is what an
48
- * obedient model echoes, and nothing validated it at draft, accept or store.
49
- */
50
- unknownField?: string;
51
- }
52
-
53
- export interface Draft {
54
- name: string;
55
- trigger: string;
56
- table: string;
57
- actions: DraftAction[];
58
- }
59
-
60
- export interface DraftResult {
61
- draft: Draft;
62
- /** Which rung answered — a wrong draft has to be diagnosable after the fact. */
63
- provider: string;
64
- /**
65
- * ⛔ CONTRACT C7's DISCLOSURE CHANNEL. `clean_actions` drops a config key it does not recognise
66
- * and answers 200 (D-75), so without this the person would accept a flow, open it, and find a
67
- * step configured differently from the one they were shown. Empty is the ordinary case.
68
- */
69
- dropped: { kind: string; keys: string[] }[];
70
- /**
71
- * ⛔ WHOLE-DRAFT DISCLOSURES — a truncated step list, a trigger this deployment does not have.
72
- * Standing rule (owner, W30/R6): a limit that cannot be removed must be REPORTED with its cause
73
- * and a recommended fix. The draft door caps a flow at 12 steps while the engine stores 20, so
74
- * a longer answer loses steps that WOULD have been storable — silently, until now.
75
- */
76
- notes: string[];
77
- /** Always false today, and read rather than assumed: the draft door writes nothing. */
78
- saved: boolean;
79
- }
80
-
81
- export function errorMessage(status: number, message?: string): string {
82
- if (status >= 500 || !message) {
83
- return status >= 500
84
- ? "Something went wrong on our side. Try again in a moment."
85
- : `The server answered ${status}.`;
86
- }
87
- return message;
88
- }
89
-
90
- async function call<T>(
91
- path: string,
92
- init: RequestInit,
93
- read: (body: unknown) => T
94
- ): Promise<Result<T>> {
95
- let res: Response;
96
- try {
97
- res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init });
98
- } catch {
99
- return { ok: false, status: 0, message: "Cannot reach the server." };
100
- }
101
- const body = (await res.json().catch(() => null)) as unknown;
102
- if (!res.ok) {
103
- const detail = (body as { error?: { message?: string } } | null)?.error?.message;
104
- return { ok: false, status: res.status, message: errorMessage(res.status, detail) };
105
- }
106
- return { ok: true, value: read(body) };
107
- }
108
-
109
- const json = (data: unknown): RequestInit => ({
110
- method: "POST",
111
- headers: { "Content-Type": "application/json" },
112
- body: JSON.stringify(data),
113
- });
114
-
115
- const str = (v: unknown): string => (typeof v === "string" ? v : "");
116
-
117
- /** Fails CLOSED: an unreadable step is dropped, never half-parsed into a config nobody wrote. */
118
- export function parseDraft(body: unknown): DraftResult {
119
- const r = (body || {}) as Record<string, unknown>;
120
- const d = (r.draft || {}) as Record<string, unknown>;
121
- const rows = Array.isArray(d.actions) ? (d.actions as unknown[]) : [];
122
- const actions: DraftAction[] = [];
123
- rows.forEach((row, i) => {
124
- const a = (row || {}) as Record<string, unknown>;
125
- if (!str(a.kind)) return;
126
- actions.push({
127
- id: str(a.id) || `act_${i + 1}`,
128
- kind: str(a.kind),
129
- config: (a.config && typeof a.config === "object"
130
- ? (a.config as Record<string, unknown>)
131
- : {}),
132
- why: str(a.why),
133
- // Fails CLOSED the SAFE way: an unreadable `needs` is an empty list, so the page shows no
134
- // false alarm — and the create door still refuses at run time either way.
135
- needs: Array.isArray(a.needs) ? (a.needs as unknown[]).map(str).filter(Boolean) : [],
136
- ...(str(a.unknownField) ? { unknownField: str(a.unknownField) } : {}),
137
- });
138
- });
139
- const dropped: { kind: string; keys: string[] }[] = [];
140
- (Array.isArray(r.dropped) ? (r.dropped as unknown[]) : []).forEach((row) => {
141
- const x = (row || {}) as Record<string, unknown>;
142
- const keys = Array.isArray(x.keys) ? (x.keys as unknown[]).map(str).filter(Boolean) : [];
143
- if (keys.length) dropped.push({ kind: str(x.kind), keys });
144
- });
145
- return {
146
- draft: {
147
- name: str(d.name) || "New automation",
148
- trigger: str(d.trigger) || "manual",
149
- table: str(d.table),
150
- actions,
151
- },
152
- provider: str(r.provider),
153
- dropped,
154
- notes: Array.isArray(r.notes) ? (r.notes as unknown[]).map(str).filter(Boolean) : [],
155
- // ⚠ `=== true`, never truthy. An absent key must read as "nothing was saved", which is the
156
- // safe direction: the wrong one would tell a person their flow exists when it does not.
157
- saved: r.saved === true,
158
- };
159
- }
160
-
161
- /**
162
- * Describe an automation; get a draft back. **This writes nothing.**
163
- *
164
- * The draft is for a person to READ before `acceptDraft` stores it — the only check on the one
165
- * failure class no validator can see: a well-formed flow that does something other than what was
166
- * asked for.
167
- */
168
- export function draftFlow(prompt: string): Promise<Result<DraftResult>> {
169
- return call("/automations/draft", json({ prompt }), parseDraft);
170
- }
171
-
172
- /**
173
- * Store an accepted draft — through the ORDINARY create door, with no marker on it.
174
- *
175
- * ⛔ THIS IS THE WHOLE OF R3's *"indistinguishable from a hand-built one"*. There is no
176
- * `source: "ai"` field and no separate table: what lands is a `plain` automation whose flow
177
- * happens to have been typed by a model, and every editor, gate and runner treats it as one
178
- * because it IS one.
179
- */
180
- export function acceptDraft(draft: Draft): Promise<Result<{ id: string }>> {
181
- return call(
182
- "/automations",
183
- json({
184
- name: draft.name,
185
- kind: "plain",
186
- trigger: { key: draft.trigger || "manual" },
187
- ...(draft.table ? { config: { targetTable: draft.table } } : {}),
188
- flow: {
189
- actions: draft.actions.map((a) => ({ kind: a.kind, config: a.config })),
190
- },
191
- }),
192
- (b) => {
193
- const a = ((b || {}) as { automation?: Record<string, unknown> }).automation || {};
194
- return { id: str(a.id) };
195
- }
196
- );
197
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/manage-agent/ManageAgentPane.tsx DELETED
@@ -1,361 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // manage-agent / ManageAgentPane.tsx — MANAGE AGENT. (wave 33, owner item 10 ·
3
- // W33-T38.)
4
- //
5
- // Owner, verbatim: *"Expand Slack we need to be able to configure an AI bot PER
6
- // channel whose permissions we can toggle based on Fields etc of the databases,
7
- // exactly like how we toggle permissioning per user. We need to be able to
8
- // configure this under a module called "Manage agent" which should be under
9
- // "Manage user"."*
10
- //
11
- // ⭐ "EXACTLY LIKE" IS IMPLEMENTED, NOT IMITATED. The per-database list, its
12
- // collapsed disclosure, its unenforced sentence and its summary line are
13
- // `settings/ModulePermsList` — the SAME component `PermsEditor` renders, not a
14
- // copy of it. The permission payload is the same envelope, parsed by the same
15
- // `parsePermsPayload`, written by the same `toPutBody`. If the account editor's
16
- // layout changes, this changes with it because there is nothing here to forget.
17
- //
18
- // ⛔ AND THE PERMISSION MODEL IS OURS, NOT OPENTAG'S (PRD amendment A1).
19
- // `PENDING.md` D-84 had named OpenTag as the model for per-channel permissioning
20
- // since 2026-08-08 and the premise is FALSE: `app/runtime-host.ts` is
21
- // `identifyUser: () => OPENTAG_SERVICE_USER` — ONE constant identity for every
22
- // request — and its own `sender-context.ts` calls the Slack sender *"informational
23
- // only… not gating access"*. Its granularity ceiling is whole-MCP-server, fixed at
24
- // process boot. `core/perm_scope.py` is already strictly more expressive, so item
25
- // 10 is OUR engine projected onto a CHANNEL principal. What OpenTag contributes is
26
- // the write-approval gate (W33-T67) and nothing else.
27
- //
28
- // ⚠ A CHANNEL IS A PRINCIPAL, NOT A PERSON. The wall is bound to the Slack
29
- // conversation id, so every human in that channel reads through the same wall —
30
- // which is the honest reading of "a bot per channel", and the reason the pane
31
- // says it out loud rather than letting an admin assume per-person scoping.
32
- // ---------------------------------------------------------------------------
33
-
34
- import { useCallback, useEffect, useState } from "react";
35
- import { ModulePermsList } from "../settings/ModulePermsList";
36
- import {
37
- isDirty,
38
- parsePermsPayload,
39
- setAccess,
40
- setFilter,
41
- setHidden,
42
- toPutBody,
43
- toggleHidden,
44
- accessSummary,
45
- } from "../settings/permsModel";
46
- import type { PermsPayload, PermsRecord } from "../settings/permsModel";
47
- import { listUsers } from "../settings/settingsApi";
48
- import {
49
- createAgent,
50
- deleteAgent,
51
- getAgentPerms,
52
- listAgents,
53
- patchAgent,
54
- putAgentPerms,
55
- } from "./agentsApi";
56
- import type { ChannelAgent } from "./agentsApi";
57
- import "./manageAgent.css";
58
-
59
- type Load =
60
- | { phase: "loading" }
61
- | { phase: "error"; message: string }
62
- | { phase: "ready"; agents: ChannelAgent[]; configured: boolean };
63
-
64
- type Edit =
65
- | null
66
- | { phase: "loading"; agent: ChannelAgent }
67
- | { phase: "error"; agent: ChannelAgent; message: string }
68
- | { phase: "ready"; agent: ChannelAgent; payload: PermsPayload };
69
-
70
- export function ManageAgentPane() {
71
- const [load, setLoad] = useState<Load>({ phase: "loading" });
72
- /**
73
- * ⛔ FETCHED HERE, NOT TAKEN AS A PROP, AND THE REASON IS A REAL DIVERGENCE THAT
74
- * WAS ALREADY IN THE FIRST DRAFT. This pane took `userOptions?: string[]` and
75
- * `SettingsModal` mounted it without one, while `PermsEditor` passes it into
76
- * the SAME `ModulePermsList` — so the two callers of one shared component would
77
- * have offered different `user`-condition vocabularies: an admin writing
78
- * "owner is Ana" for a person could, and for a channel could not. Caught by a
79
- * verifier reading the compiled mount site, not by a type error, because the
80
- * prop is optional and its absence is a silent narrowing.
81
- *
82
- * `SettingsModal` cannot supply it: the account list lives inside `UsersPane`,
83
- * a sibling component. So this pane does what it already does for its agents —
84
- * fetches its own data and owns its own states. ⚠ DISPLAY NAMES, matching
85
- * `UsersPane`'s own call: a `user` CELL stores the name, so the builder must
86
- * offer names.
87
- */
88
- const [userOptions, setUserOptions] = useState<string[] | undefined>(undefined);
89
- const [edit, setEdit] = useState<Edit>(null);
90
- const [saved, setSaved] = useState<PermsRecord>({});
91
- const [draft, setDraft] = useState<PermsRecord>({});
92
- const [busy, setBusy] = useState(false);
93
- const [error, setError] = useState("");
94
- const [said, setSaid] = useState("");
95
- const [channel, setChannel] = useState("");
96
- const [label, setLabel] = useState("");
97
-
98
- const reload = useCallback(async () => {
99
- const r = await listAgents();
100
- setLoad(
101
- r.ok
102
- ? { phase: "ready", agents: r.data.agents ?? [], configured: r.data.configured === true }
103
- : { phase: "error", message: r.message }
104
- );
105
- }, []);
106
-
107
- useEffect(() => {
108
- void reload();
109
- // The same list `UsersPane` builds its condition vocabulary from. A failure
110
- // leaves it `undefined` rather than `[]`: the panel documents "absent ⇒ the
111
- // panel says so", and an EMPTY supplied list would WIN as an answer — the
112
- // wave-26 item-24 trap, which is the very defect W33-T35 just closed one
113
- // surface over.
114
- void listUsers().then((r) => {
115
- if (r.ok) setUserOptions((r.data.users ?? []).map((u) => u.name || u.username));
116
- });
117
- }, [reload]);
118
-
119
- const open = useCallback(async (agent: ChannelAgent) => {
120
- setEdit({ phase: "loading", agent });
121
- setError("");
122
- setSaid("");
123
- const r = await getAgentPerms(agent.id);
124
- if (!r.ok) {
125
- setEdit({ phase: "error", agent, message: r.message });
126
- return;
127
- }
128
- const payload = parsePermsPayload(r.data);
129
- if (!payload) {
130
- // ⛔ An unreadable payload is an ERROR, never an empty editor. An empty
131
- // editor here would invite an admin to press Save on a record they were
132
- // never shown — a whole-record replace built out of nothing.
133
- setEdit({ phase: "error", agent, message: "That agent's permissions could not be read." });
134
- return;
135
- }
136
- setSaved(payload.entries);
137
- setDraft(payload.entries);
138
- setEdit({ phase: "ready", agent, payload });
139
- }, []);
140
-
141
- const dirty = edit?.phase === "ready" ? isDirty(edit.payload, saved, draft) : false;
142
-
143
- async function save() {
144
- if (edit?.phase !== "ready") return;
145
- setBusy(true);
146
- setError("");
147
- const r = await putAgentPerms(edit.agent.id, toPutBody(edit.payload, draft) as never);
148
- setBusy(false);
149
- if (!r.ok) {
150
- setError(r.message);
151
- return;
152
- }
153
- setSaved(draft);
154
- setSaid(`Saved. ${accessSummary(edit.payload, draft)}.`);
155
- void reload();
156
- }
157
-
158
- async function add() {
159
- const ch = channel.trim();
160
- if (!ch) return;
161
- setBusy(true);
162
- setError("");
163
- const r = await createAgent({ channel: ch, label: label.trim() || undefined });
164
- setBusy(false);
165
- if (!r.ok) {
166
- setError(r.message);
167
- return;
168
- }
169
- setChannel("");
170
- setLabel("");
171
- await reload();
172
- }
173
-
174
- async function toggleApproval(agent: ChannelAgent) {
175
- setBusy(true);
176
- const r = await patchAgent(agent.id, { writeApproval: !agent.writeApproval });
177
- setBusy(false);
178
- if (!r.ok) {
179
- setError(r.message);
180
- return;
181
- }
182
- await reload();
183
- if (edit?.agent.id === agent.id) setEdit({ ...edit, agent: r.data.agent } as Edit);
184
- }
185
-
186
- async function remove(agent: ChannelAgent) {
187
- setBusy(true);
188
- const r = await deleteAgent(agent.id);
189
- setBusy(false);
190
- if (!r.ok) {
191
- setError(r.message);
192
- return;
193
- }
194
- if (edit?.agent.id === agent.id) setEdit(null);
195
- await reload();
196
- }
197
-
198
- // --- the editor takeover, matching Manage users' own pattern ---------------
199
- if (edit) {
200
- return (
201
- <div className="set-pane">
202
- <button type="button" className="set-secondary set-back" onClick={() => setEdit(null)}>
203
- Back to agents
204
- </button>
205
- <h3 className="set-h">{edit.agent.label || edit.agent.channelName || edit.agent.channel}</h3>
206
- <p className="set-help ma-principal">
207
- This wall applies to the CHANNEL, not to the people in it — everyone who can
208
- talk to this bot reads through the same rules.
209
- </p>
210
-
211
- {edit.phase === "loading" ? (
212
- <span className="lp-spin" role="status" aria-label="Loading" />
213
- ) : null}
214
- {edit.phase === "error" ? <p className="set-error">{edit.message}</p> : null}
215
-
216
- {edit.phase === "ready" ? (
217
- <>
218
- <label className="set-check ma-approval">
219
- <input
220
- type="checkbox"
221
- checked={edit.agent.writeApproval}
222
- disabled={busy}
223
- onChange={() => void toggleApproval(edit.agent)}
224
- />
225
- <span>A person must approve before this bot changes anything</span>
226
- </label>
227
- <p className="set-help">
228
- With this off, the bot commits writes on its own. Reads are always governed
229
- by the rules below.
230
- </p>
231
-
232
- <ModulePermsList
233
- modules={edit.payload.modules}
234
- entries={draft}
235
- onAccess={(key, on) => setDraft((d) => setAccess(d, key, on))}
236
- onFilter={(key, next) => setDraft((d) => setFilter(d, key, next))}
237
- onToggleHidden={(key, fk) => setDraft((d) => toggleHidden(d, key, fk))}
238
- onSetHidden={(key, keys) => setDraft((d) => setHidden(d, key, keys))}
239
- userOptions={userOptions}
240
- emptyNote="This workspace has no databases whose access can be restricted."
241
- />
242
-
243
- <div className="set-actions set-perm-actions">
244
- <button
245
- type="button"
246
- className="set-primary"
247
- disabled={!dirty || busy}
248
- onClick={() => void save()}
249
- >
250
- Save permissions
251
- </button>
252
- {dirty ? <p className="set-help set-perm-dirty">Unsaved changes.</p> : null}
253
- {said ? <p className="set-help">{said}</p> : null}
254
- {error ? <p className="set-error">{error}</p> : null}
255
- </div>
256
- </>
257
- ) : null}
258
- </div>
259
- );
260
- }
261
-
262
- // --- the list -------------------------------------------------------------
263
- return (
264
- <div className="set-pane">
265
- <h3 className="set-h">Manage agent</h3>
266
- <p className="set-perm-intro">
267
- A bot per Slack channel, with the same per-database rules you set for a person.
268
- The rules are enforced by the same engine — a channel is simply another principal.
269
- </p>
270
-
271
- {load.phase === "loading" ? (
272
- <span className="lp-spin" role="status" aria-label="Loading" />
273
- ) : null}
274
- {load.phase === "error" ? <p className="set-error">{load.message}</p> : null}
275
-
276
- {load.phase === "ready" && !load.configured ? (
277
- // ⚠ R6's second sentence: a limit that cannot be removed here is REPORTED
278
- // with its cause, never left to look like an empty list.
279
- <p className="set-help ma-unconfigured">
280
- This workspace has no Slack credentials yet, so an agent configured here could
281
- not connect. Add them under Keychains first — the rules you set will still be
282
- stored and will apply the moment it can.
283
- </p>
284
- ) : null}
285
-
286
- {load.phase === "ready" ? (
287
- <>
288
- {load.agents.length === 0 ? (
289
- <p className="pg-empty">No channel agents yet.</p>
290
- ) : (
291
- <ul className="ma-list">
292
- {load.agents.map((a) => (
293
- <li className="set-card ma-row" key={a.id}>
294
- <button
295
- type="button"
296
- className="ma-open"
297
- onClick={() => void open(a)}
298
- disabled={busy}
299
- >
300
- <span className="ma-name">{a.label || a.channelName || a.channel}</span>
301
- <span className="ma-channel">
302
- {a.channelName ? `${a.channelName} · ` : ""}
303
- {a.channel}
304
- </span>
305
- </button>
306
- <span className="ma-end">
307
- <span className="set-perm-sum">{a.summary ?? ""}</span>
308
- {/* The one setting worth seeing without opening the agent:
309
- everything else is recoverable, an unapproved write is not. */}
310
- <span className="ma-flag">
311
- {a.writeApproval ? "Approval required" : "Writes unattended"}
312
- </span>
313
- <button
314
- type="button"
315
- className="set-secondary"
316
- disabled={busy}
317
- onClick={() => void remove(a)}
318
- >
319
- Remove
320
- </button>
321
- </span>
322
- </li>
323
- ))}
324
- </ul>
325
- )}
326
-
327
- <section className="set-card ma-add">
328
- <h4 className="set-subh">Add a channel</h4>
329
- <label className="set-field">
330
- <span>Slack channel ID</span>
331
- <input
332
- value={channel}
333
- onChange={(e) => setChannel(e.target.value)}
334
- placeholder="C01234ABCDE"
335
- />
336
- </label>
337
- <label className="set-field">
338
- <span>Name (optional)</span>
339
- <input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Sales" />
340
- </label>
341
- {/* ⚠ The ID, not the #name: a channel can be renamed and its id cannot,
342
- and a wall bound to a display name silently re-points on a rename. */}
343
- <p className="set-help">
344
- Use the channel ID rather than its name — a renamed channel keeps its ID, and a
345
- rule bound to a name would quietly follow the name somewhere else.
346
- </p>
347
- <button
348
- type="button"
349
- className="set-primary"
350
- disabled={!channel.trim() || busy}
351
- onClick={() => void add()}
352
- >
353
- Add agent
354
- </button>
355
- </section>
356
- {error ? <p className="set-error">{error}</p> : null}
357
- </>
358
- ) : null}
359
- </div>
360
- );
361
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/manage-agent/agentsApi.ts DELETED
@@ -1,139 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // manage-agent / agentsApi.ts — the client half of the channel-agent doors.
3
- // (wave 33, owner item 10 · W33-T38 / W33-T39.)
4
- //
5
- // ⚠ THE PERMISSION PAYLOAD SHAPE IS THE USER EDITOR'S, ON PURPOSE.
6
- // `GET /agents/{id}` answers with the SAME `{modules, fields_by_module, perms,
7
- // perms_v, is_admin}` envelope as `GET /admin/users/{u}/perms`, so
8
- // `permsModel.parsePermsPayload` parses both and `settings/ModulePermsList`
9
- // renders both. The owner's requirement was *"exactly like how we toggle
10
- // permissioning per user"*; ONE payload shape is what makes that true in code
11
- // rather than in appearance. A second shape here would be a second parser, a
12
- // second renderer and a second set of defaults within a wave.
13
- //
14
- // ⛔ THE CLIENT HIDES; THE SERVER FORBIDS. Every door below is admin-gated
15
- // server-side. Nothing in this file is a permission check.
16
- // ---------------------------------------------------------------------------
17
-
18
- import { API_V1, CREDENTIALS } from "../apiContract";
19
- import type { ApiResult } from "../settings/settingsApi";
20
-
21
- /** One configured channel bot, as the list door reports it. */
22
- export interface ChannelAgent {
23
- id: string;
24
- /** The Slack conversation id (`C…`) — the IDENTITY. A channel can be renamed;
25
- * its id cannot, and binding a permission wall to a display name is how a
26
- * rename silently re-points a grant. */
27
- channel: string;
28
- /** What Slack calls it today. DISPLAY ONLY, and may be empty. */
29
- channelName: string;
30
- label: string;
31
- active: boolean;
32
- /**
33
- * ⛔ W33-T67 — may this bot COMMIT a mutation, or only propose one? Defaults
34
- * TRUE (a human must approve). It is the one setting here whose wrong value
35
- * cannot be undone by revoking the bot afterwards: the write already happened.
36
- */
37
- writeApproval: boolean;
38
- /** One sentence for the list row — "3 of 7 databases, 2 restricted" — computed
39
- * server-side, because the alternative is one round trip per row to fill one
40
- * cell (the same reason `AdminUser.access` exists). */
41
- summary?: string;
42
- }
43
-
44
- export interface AgentListPayload {
45
- agents: ChannelAgent[];
46
- /**
47
- * Does this deployment hold Slack credentials at all? FALSE ⇒ the pane says so
48
- * instead of offering a control that cannot work. ⚠ It is NOT a permission and
49
- * must never be read as one — the routes refuse a non-admin regardless.
50
- */
51
- configured: boolean;
52
- }
53
-
54
- async function call<T>(
55
- path: string,
56
- init?: RequestInit & { body?: string }
57
- ): Promise<ApiResult<T>> {
58
- try {
59
- const res = await fetch(`${API_V1}${path}`, {
60
- credentials: CREDENTIALS,
61
- headers: init?.body ? { "Content-Type": "application/json" } : undefined,
62
- ...init,
63
- });
64
- if (res.status === 204) return { ok: true, data: undefined as T };
65
- let body: unknown = null;
66
- try {
67
- body = await res.json();
68
- } catch {
69
- /* an empty body is normal on 204; a parse failure is not fatal here */
70
- }
71
- if (!res.ok) {
72
- const err = (body as { error?: { message?: string } } | null)?.error;
73
- // A 5xx message is never surfaced verbatim — a server stack trace behind a
74
- // login is still a leak. Same rule as `settingsApi.call`.
75
- const message =
76
- res.status >= 500
77
- ? "Something went wrong on our side. Try again in a moment."
78
- : err?.message ||
79
- (res.status === 403
80
- ? "Administrators only."
81
- : "That change could not be saved.");
82
- return { ok: false, status: res.status, message };
83
- }
84
- return { ok: true, data: body as T };
85
- } catch {
86
- return { ok: false, status: 0, message: "The server could not be reached." };
87
- }
88
- }
89
-
90
- export function listAgents(): Promise<ApiResult<AgentListPayload>> {
91
- return call<AgentListPayload>("/agents");
92
- }
93
-
94
- export function createAgent(body: {
95
- channel: string;
96
- channelName?: string;
97
- label?: string;
98
- }): Promise<ApiResult<{ agent: ChannelAgent }>> {
99
- return call<{ agent: ChannelAgent }>("/agents", {
100
- method: "POST",
101
- body: JSON.stringify(body),
102
- });
103
- }
104
-
105
- /** The agent PLUS the permission envelope — parsed by `parsePermsPayload`. */
106
- export function getAgentPerms(id: string): Promise<ApiResult<unknown>> {
107
- return call<unknown>(`/agents/${encodeURIComponent(id)}`);
108
- }
109
-
110
- /**
111
- * WHOLE-RECORD REPLACE, exactly like `putUserPerms`. Every ENFORCED module the
112
- * server declared is present in `perms`, including untouched ones: a key omitted
113
- * from a replace is a DELETION. `permsModel.toPutBody` is the only sanctioned way
114
- * to build this body — it is also what drops the unenforced `ut_*` keys the
115
- * server would refuse.
116
- */
117
- export function putAgentPerms(
118
- id: string,
119
- body: { perms: Record<string, unknown> }
120
- ): Promise<ApiResult<unknown>> {
121
- return call<unknown>(`/agents/${encodeURIComponent(id)}/perms`, {
122
- method: "PUT",
123
- body: JSON.stringify(body),
124
- });
125
- }
126
-
127
- export function patchAgent(
128
- id: string,
129
- patch: Partial<Pick<ChannelAgent, "label" | "active" | "writeApproval" | "channelName">>
130
- ): Promise<ApiResult<{ agent: ChannelAgent }>> {
131
- return call<{ agent: ChannelAgent }>(`/agents/${encodeURIComponent(id)}`, {
132
- method: "PATCH",
133
- body: JSON.stringify(patch),
134
- });
135
- }
136
-
137
- export function deleteAgent(id: string): Promise<ApiResult<void>> {
138
- return call<void>(`/agents/${encodeURIComponent(id)}`, { method: "DELETE" });
139
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/manage-agent/manageAgent.css DELETED
@@ -1,88 +0,0 @@
1
- /* manage-agent/manageAgent.css — wave 33, owner item 10 (W33-T38).
2
- *
3
- * ⛔ CONTRACT C4: `index.css` is lane B's. Everything NEW to this module lives
4
- * here; everything SHARED with Manage user (`.set-card`, `.set-pane`, `.set-h`,
5
- * `.set-perm-*`) is reused from `index.css` unchanged and is NOT redefined here.
6
- * That is deliberate and it is the owner's requirement — *"the same exact
7
- * layout"*. A stylesheet that re-specified the shared chrome would let the two
8
- * rooms drift by a padding value, which is exactly the drift the shared
9
- * `ModulePermsList` component exists to prevent one level up.
10
- */
11
-
12
- .ma-list {
13
- list-style: none;
14
- margin: 12px 0 20px;
15
- padding: 0;
16
- display: flex;
17
- flex-direction: column;
18
- gap: 8px;
19
- }
20
-
21
- .ma-row {
22
- display: flex;
23
- align-items: center;
24
- justify-content: space-between;
25
- gap: 12px;
26
- }
27
-
28
- /* The whole left half is the door, so the target is a row and not a word. */
29
- .ma-open {
30
- display: flex;
31
- flex-direction: column;
32
- align-items: flex-start;
33
- gap: 2px;
34
- flex: 1 1 auto;
35
- min-width: 0;
36
- /* ⚠ A <button> inherits neither `font` nor `text-align` from its container —
37
- the exact defect owner item 15 reports on Home's automation tiles, one
38
- screen over. Both are stated rather than assumed. */
39
- font: inherit;
40
- text-align: left;
41
- background: none;
42
- border: 0;
43
- padding: 0;
44
- cursor: pointer;
45
- color: inherit;
46
- }
47
- .ma-open:disabled { cursor: default; opacity: 0.6; }
48
- .ma-open:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 2px; }
49
-
50
- .ma-name {
51
- font-size: var(--lp-fs-sm);
52
- font-weight: 620;
53
- overflow: hidden;
54
- text-overflow: ellipsis;
55
- white-space: nowrap;
56
- max-width: 100%;
57
- }
58
-
59
- .ma-channel {
60
- font-size: var(--lp-fs-2xs);
61
- color: var(--lp-muted);
62
- font-variant-numeric: tabular-nums;
63
- }
64
-
65
- .ma-end {
66
- display: flex;
67
- align-items: center;
68
- gap: 10px;
69
- flex: none;
70
- }
71
-
72
- /* The write-approval state, visible without opening the agent. Everything else
73
- about an agent is recoverable by editing it; an unattended write is not. */
74
- .ma-flag {
75
- font-size: var(--lp-fs-2xs);
76
- color: var(--lp-muted);
77
- white-space: nowrap;
78
- }
79
-
80
- .ma-approval { margin: 4px 0 0; }
81
- .ma-principal { max-width: 68ch; }
82
- .ma-unconfigured { max-width: 68ch; }
83
- .ma-add { margin-top: 16px; }
84
-
85
- @media (max-width: 640px) {
86
- .ma-row { flex-wrap: wrap; }
87
- .ma-end { flex-wrap: wrap; justify-content: flex-end; }
88
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/publish/PublishPanel.tsx DELETED
@@ -1,351 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // publish / PublishPanel.tsx — ⭐⭐ wave-33 item 8b (ruling R5, ticket W33-T27).
3
- //
4
- // The publish control, mounted INSIDE the share dialog — "where sharing already
5
- // lives", which is the ticket's own words and the reason this is not a fourth
6
- // dialog.
7
- //
8
- // ⛔⛔ PUBLISHING IS NOT SHARING, AND THIS PANEL MUST NOT LET THE TWO BLUR.
9
- // `routes_shares.py`'s docstring (sharing audit, S-4) already records that TWO
10
- // systems answer "is this shared" — the grant registry drives *Shared with me*,
11
- // while `table_store.is_shared` GATES opening a view. A published link is a
12
- // THIRD thing and is different in kind from both: it creates no grant, appears
13
- // in nobody's *Shared with me*, names no person, and cannot be revoked by
14
- // removing somebody — because there is nobody to remove. Sitting in the same
15
- // dialog is right (it is where a person goes to ask "who can reach this?"), so
16
- // the panel states the distinction rather than relying on the layout to imply
17
- // it.
18
- //
19
- // ⭐ IT ASKS THE SERVER WHETHER THIS VIEW CAN BE PUBLISHED, rather than deciding
20
- // from a `mode` prop. `GET /view-link` refuses a non-interface view with
21
- // `not_an_interface`, refuses a connected-source database with
22
- // `connected_source`, refuses a reader-scoped view with `reader_scoped` and
23
- // refuses a non-owner with `not_yours` — so a client-side mode check would be a
24
- // SECOND evaluator of "is this publishable", agreeing today and drifting the day
25
- // the server learns a new refusal. Any non-200 renders NOTHING, which is exactly
26
- // the ticket's "absent on non-interface views" [[one-evaluator-per-question]].
27
- // ---------------------------------------------------------------------------
28
-
29
- import { useCallback, useEffect, useState } from "react";
30
-
31
- import { API_V1, CREDENTIALS } from "../apiContract";
32
-
33
- import "./publishPanel.css";
34
-
35
- type Access = "public" | "password";
36
-
37
- interface LinkState {
38
- published: boolean;
39
- access: Access;
40
- token: string;
41
- url: string;
42
- hasPassphrase?: boolean;
43
- }
44
-
45
- /**
46
- * The refusals that mean "this view is not publishable, say nothing". Anything else is an error
47
- * worth showing — the difference between a control that does not APPLY and one that is BROKEN.
48
- *
49
- * ⛔ THIS SET WAS SHORT BY TWO, AND ONE OF THEM FIRES ON PRODUCTION DATA. Found by a verifier
50
- * that enumerated every `err(...)` reachable from `GET /view-link` and compared, rather than
51
- * trusting the header of this very file — which claimed both were handled, twenty lines above a
52
- * constant that omitted them.
53
- * · `connected_source` is raised BEFORE the mode check, so it fires on any view of a
54
- * read-through database — and tenant #0 has ten `ut_odoo_*` grids live. The "Share view" menu
55
- * item is not gated on ownership or on view kind, so the "All records" system view of
56
- * `ut_odoo_accounts` opens this dialog. The panel would paint "The publish state could not be
57
- * read." with a disabled button: a BROKEN publish box on a database that simply cannot be
58
- * published.
59
- * · `reader_scoped` fires on a cohort-locked or measure/top-N-filtered INTERFACE view.
60
- *
61
- * ⚠ THE LESSON, because it is the same one twice today: a prose comment describing a behaviour is
62
- * not the behaviour. The header said "any non-200 renders NOTHING"; the code said four codes.
63
- * [[grep-output-is-not-source]] — and a gate would have caught it, which is why one now exists.
64
- */
65
- const SILENT = new Set([
66
- "not_an_interface", "not_a_database", "not_yours", "no_such_view",
67
- "connected_source", "reader_scoped",
68
- // ⛔ ADDED 2026-08-14 FOR THE WAVE-33 DEPLOY, and it is the right rule independent of it.
69
- // `http_404` is what FastAPI answers when the publish ROUTER IS NOT MOUNTED AT ALL — which is
70
- // deliberately the case on this deploy (see `main.py`: three HIGH defects are armed only by
71
- // mounting it, W33-T68/T69/T70). Without this entry every share dialog on the deployment paints
72
- // "The publish state could not be read." beside a dead button, for every view, forever.
73
- // ⭐ The general form is why it belongs here permanently: a door that is ABSENT means the
74
- // capability is not offered, which is precisely what the other six codes mean. An absent feature
75
- // must read as absent, never as broken — the same rule the header states, arriving from the one
76
- // direction nobody had a code for.
77
- "http_404",
78
- ]);
79
-
80
- export default function PublishPanel({ topic, view }: { topic: string; view: string }) {
81
- const [link, setLink] = useState<LinkState | null>(null);
82
- const [hidden, setHidden] = useState(false);
83
- const [ready, setReady] = useState(false);
84
- const [access, setAccess] = useState<Access>("password");
85
- const [passphrase, setPassphrase] = useState("");
86
- const [error, setError] = useState("");
87
- const [busy, setBusy] = useState(false);
88
- const [copied, setCopied] = useState(false);
89
-
90
- const path = `${API_V1}/view-link`;
91
- const query = `?topic=${encodeURIComponent(topic)}&view=${encodeURIComponent(view)}`;
92
-
93
- const take = useCallback((state: LinkState) => {
94
- setLink(state);
95
- setAccess(state.published ? state.access : "password");
96
- setReady(true);
97
- }, []);
98
-
99
- useEffect(() => {
100
- let dead = false;
101
- void (async () => {
102
- try {
103
- const res = await fetch(path + query, { credentials: CREDENTIALS });
104
- if (dead) return;
105
- if (!res.ok) {
106
- const body = (await res.json().catch(() => null)) as
107
- | { error?: { code?: string } }
108
- | null;
109
- // ⛔ A refusal that means "not applicable" hides the control; anything
110
- // else would leave a person staring at a publish box that cannot work.
111
- if (SILENT.has(String(body?.error?.code || ""))) setHidden(true);
112
- else setError("The publish state could not be read.");
113
- setReady(true);
114
- return;
115
- }
116
- take((await res.json()) as LinkState);
117
- } catch {
118
- if (!dead) {
119
- setError("Cannot reach the server.");
120
- setReady(true);
121
- }
122
- }
123
- })();
124
- return () => {
125
- dead = true;
126
- };
127
- }, [path, query, take]);
128
-
129
- const send = useCallback(
130
- async (body: Record<string, unknown>, method: "POST" | "DELETE") => {
131
- setBusy(true);
132
- setError("");
133
- setCopied(false);
134
- try {
135
- const res = await fetch(path, {
136
- method,
137
- credentials: CREDENTIALS,
138
- headers: { "Content-Type": "application/json" },
139
- body: JSON.stringify({ topic, view, ...body }),
140
- });
141
- if (!res.ok) {
142
- const parsed = (await res.json().catch(() => null)) as
143
- | { error?: { message?: string } }
144
- | null;
145
- // The server's own sentence, verbatim. Its refusals NAME their cause
146
- // ("this view is locked to a cohort…", "a database that reads through a
147
- // connected source…"), and a generic "that did not work" would throw
148
- // away the one useful thing the refusal carried — which is R6's second
149
- // sentence arriving at a person.
150
- setError(String(parsed?.error?.message || "That could not be saved."));
151
- return false;
152
- }
153
- take((await res.json()) as LinkState);
154
- setPassphrase("");
155
- return true;
156
- } catch {
157
- setError("Cannot reach the server.");
158
- return false;
159
- } finally {
160
- setBusy(false);
161
- }
162
- },
163
- [path, take, topic, view],
164
- );
165
-
166
- if (!ready || hidden) return null;
167
-
168
- const copy = () => {
169
- if (!link?.url) return;
170
- // ⛔ THE `?.` SHORT-CIRCUITS THE WHOLE CHAIN, WHICH MADE THIS A SILENT NO-OP. Verified by
171
- // execution: with no `navigator.clipboard`, `nav.clipboard?.writeText(x).then(…).catch(…)`
172
- // evaluates to `undefined` and NEITHER handler runs — so the button did nothing, said
173
- // nothing, and left its label reading "Copy". `navigator.clipboard` is absent on http
174
- // (non-localhost) and in older browsers, which is exactly where a person shares links from.
175
- // The `.catch` only ever covered a REJECTED write (permission denied), never an absent API.
176
- const clip = navigator.clipboard;
177
- if (!clip?.writeText) {
178
- setError("Your browser will not copy automatically here — select the link above and copy it.");
179
- return;
180
- }
181
- void clip
182
- .writeText(link.url)
183
- .then(() => setCopied(true))
184
- .catch(() => setError("Could not copy — select the link and copy it by hand."));
185
- };
186
-
187
- return (
188
- <PublishForm
189
- link={link}
190
- access={access}
191
- passphrase={passphrase}
192
- error={error}
193
- busy={busy}
194
- copied={copied}
195
- onAccess={setAccess}
196
- onPassphrase={setPassphrase}
197
- onCopy={copy}
198
- onPublish={(rotate) =>
199
- void send(
200
- { access, ...(rotate ? { rotate: true } : {}), ...(passphrase ? { passphrase } : {}) },
201
- "POST",
202
- )
203
- }
204
- onUnpublish={() => void send({}, "DELETE")}
205
- />
206
- );
207
- }
208
-
209
- /**
210
- * The control itself, as a PURE function of its state.
211
- *
212
- * ⭐ EXPORTED AND SPLIT OUT FOR THE SAME REASON `PublishedBody` is: it makes this surface
213
- * RENDERABLE without a browser or a session. `renderToStaticMarkup` runs no effects, so the
214
- * fetching component above can only ever paint `null` — this control would otherwise reach the
215
- * wave's QA never having been looked at, which for a control the owner explicitly asked for is
216
- * the worst kind of "shipped". [[ui-invisible-to-assertions]]
217
- *
218
- * ⚠ NO TEST-ONLY PROP ANYWHERE. Every prop below is one the real component passes on every
219
- * render; a `preview?: boolean` would be a second code path that the thing a person sees does not
220
- * take, which is worse than not rendering it at all.
221
- */
222
- export function PublishForm({
223
- link,
224
- access,
225
- passphrase,
226
- error,
227
- busy,
228
- copied,
229
- onAccess,
230
- onPassphrase,
231
- onCopy,
232
- onPublish,
233
- onUnpublish,
234
- }: {
235
- link: LinkState | null;
236
- access: Access;
237
- passphrase: string;
238
- error: string;
239
- busy: boolean;
240
- copied: boolean;
241
- onAccess: (a: Access) => void;
242
- onPassphrase: (s: string) => void;
243
- onCopy: () => void;
244
- /** `rotate` = mint a new link and kill the old one in the same write. */
245
- onPublish: (rotate: boolean) => void;
246
- onUnpublish: () => void;
247
- }) {
248
- // A password link needs a passphrase the FIRST time. After that the stored one
249
- // is kept unless a new one is typed, so switching public→password on a link
250
- // that already has one does not demand it again.
251
- const needsPassphrase = access === "password" && !link?.hasPassphrase && !passphrase;
252
-
253
- return (
254
- <section className="pubp" aria-label="Publish a link">
255
- <h3 className="pubp-head">Publish a link</h3>
256
- <p className="pubp-sub">
257
- A link anyone can open without an account. It shows only the columns this view shows, and
258
- it is read-only. {/* ⛔ The distinction, stated rather than implied by the layout. */}
259
- <strong>This is not sharing</strong> — nobody is named, nothing appears in anyone&rsquo;s
260
- Shared&nbsp;with&nbsp;me, and it is revoked by replacing the link rather than by removing
261
- a person.
262
- </p>
263
-
264
- {link?.published ? (
265
- <>
266
- <div className="pubp-linkrow">
267
- <input className="pubp-link" readOnly value={link.url} aria-label="The public link" />
268
- <button type="button" className="pubp-btn" onClick={onCopy} disabled={busy}>
269
- {copied ? "Copied" : "Copy"}
270
- </button>
271
- </div>
272
- <p className="pubp-state">
273
- {link.access === "public"
274
- ? "Anyone with the link can open it."
275
- : "Anyone with the link and the passphrase can open it."}
276
- </p>
277
- </>
278
- ) : null}
279
-
280
- <div className="pubp-access" role="group" aria-label="Who can open the link">
281
- {(["public", "password"] as const).map((a) => (
282
- <label className="pubp-radio" key={a}>
283
- <input
284
- type="radio"
285
- name="pubp-access"
286
- value={a}
287
- checked={access === a}
288
- disabled={busy}
289
- onChange={() => onAccess(a)}
290
- />
291
- <span>{a === "public" ? "Anyone with the link" : "Anyone with the passphrase"}</span>
292
- </label>
293
- ))}
294
- </div>
295
-
296
- {access === "password" ? (
297
- <label className="pubp-pass">
298
- <span className="pubp-label">
299
- {link?.hasPassphrase
300
- ? "New passphrase (leave blank to keep the current one)"
301
- : "Passphrase"}
302
- </span>
303
- <input
304
- className="pubp-input"
305
- type="password"
306
- autoComplete="off"
307
- value={passphrase}
308
- disabled={busy}
309
- onChange={(e) => onPassphrase(e.target.value)}
310
- />
311
- </label>
312
- ) : null}
313
-
314
- {error ? <p className="pubp-err">{error}</p> : null}
315
-
316
- <div className="pubp-actions">
317
- <button
318
- type="button"
319
- className="pubp-btn is-primary"
320
- disabled={busy || needsPassphrase}
321
- onClick={() => onPublish(false)}
322
- >
323
- {link?.published ? "Update link" : "Publish"}
324
- </button>
325
- {link?.published ? (
326
- <>
327
- <button
328
- type="button"
329
- className="pubp-btn"
330
- disabled={busy || needsPassphrase}
331
- onClick={() => onPublish(true)}
332
- // ⚠ "Replace", not "Regenerate": the consequence a person needs to
333
- // predict is that the link they already sent stops working.
334
- title="Mints a new link. The old one stops working immediately."
335
- >
336
- Replace link
337
- </button>
338
- <button
339
- type="button"
340
- className="pubp-btn is-danger"
341
- disabled={busy}
342
- onClick={onUnpublish}
343
- >
344
- Unpublish
345
- </button>
346
- </>
347
- ) : null}
348
- </div>
349
- </section>
350
- );
351
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/publish/PublishedView.tsx DELETED
@@ -1,352 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // publish / PublishedView.tsx — ⭐⭐ wave-33 item 8b (ruling R5, ticket W33-T26).
3
- //
4
- // The page an ANONYMOUS person lands on at `#/v/<token>`. Shell mounts it BEFORE
5
- // the auth wall, exactly where `FormPublic` is mounted; everything below assumes
6
- // there is no session, no workspace, no nav and no viewer.
7
- //
8
- // ⛔ IT IMPORTS NOTHING FROM `customer-grid/**`, AND THAT IS A REQUIREMENT RATHER
9
- // THAN A PREFERENCE — the same one `FormPublic` carries and for a sharper reason
10
- // here. `customer-grid` drags `glide-data-grid` (hundreds of kilobytes of canvas
11
- // spreadsheet) into whatever chunk touches it, and MapView, CatalogView and
12
- // SwipeView all live in that directory. So this page cannot reuse them, and the
13
- // honest answer is not to import them anyway: it renders its own read-only
14
- // presentation per mode. One convenience import — even a type from `types.ts` —
15
- // would put the whole spreadsheet engine on a stranger's first, cold, probably
16
- // mobile page load.
17
- //
18
- // ⛔ AND IT RENDERS NO EDIT AFFORDANCE OF ANY KIND. There is no cell to click, no
19
- // menu, no "open in app". A published link is a READ of a projection, and a
20
- // control that looks actionable on a page with no session is a promise the
21
- // server would refuse.
22
- //
23
- // ⚠ Styling is co-located (`publish.css`, contract C4) because `index.css` is
24
- // B's file this wave. COLOUR is local to that sheet, TYPE uses the product's
25
- // `--lp-fs-*` tokens — the sheet's own header carries the argument, and the
26
- // first draft got it wrong in the direction `verify_ui` caught.
27
- // ---------------------------------------------------------------------------
28
-
29
- import { useEffect, useState } from "react";
30
-
31
- import "./publish.css";
32
-
33
- /** One column, exactly as `routes_publish._public_view` builds it. */
34
- export interface PubColumn {
35
- key: string;
36
- label: string;
37
- /** The server's own word. Deliberately `string`, not a union — an unknown type
38
- * renders as text, which is the safe direction; a union would render nothing
39
- * at all for a type this page has not heard of. */
40
- type: string;
41
- options?: string[];
42
- }
43
-
44
- export interface PubRow {
45
- pid: number;
46
- /** ⚠ Present ONLY on a map — the server ships coordinates for that mode alone,
47
- * because they are an address in another form. */
48
- lat?: number | null;
49
- lon?: number | null;
50
- [key: string]: unknown;
51
- }
52
-
53
- export interface PubLimit {
54
- subject: string;
55
- effect: string;
56
- detail: string;
57
- recommendation?: string;
58
- }
59
-
60
- export interface PubPage {
61
- title: string;
62
- mode: string;
63
- display: Record<string, string>;
64
- columns: PubColumn[];
65
- rows: PubRow[];
66
- total: number;
67
- limits?: PubLimit[];
68
- }
69
-
70
- type Phase = "loading" | "locked" | "ready" | "gone";
71
-
72
- const NUMERIC = new Set(["int", "number", "money", "pct", "rating"]);
73
-
74
- function cellText(value: unknown): string {
75
- if (value === null || value === undefined) return "";
76
- if (typeof value === "boolean") return value ? "Yes" : "No";
77
- return String(value);
78
- }
79
-
80
- /**
81
- * A plot of positions — equirectangular, fitted to the points, and that is the
82
- * whole design note.
83
- *
84
- * ⛔ NO TILE LAYER, NO MAP LIBRARY, NO EXTERNAL HOST. A published page is loaded
85
- * by somebody with no account, so every byte it fetches from a third party is a
86
- * request WE caused a stranger's browser to make, carrying their IP to a vendor
87
- * they never chose. Plotting the points the server already sent into an inline
88
- * SVG costs nothing and asks nobody.
89
- *
90
- * ⚠ IT DOES NOT PRETEND TO BE A MAP OF A TERRITORY — no coastlines, no
91
- * graticule, no scale bar. Drawing chrome that implies a basemap we do not have
92
- * would be a picture making a claim the data does not support.
93
- */
94
- function MapPlot({ rows, title }: { rows: PubRow[]; title: (r: PubRow) => string }) {
95
- // ⛔ `coord` REJECTS null BEFORE `Number()` SEES IT, and that is not defensive noise — the
96
- // first version of this function did `Number(r.lat)` straight, and `Number(null)` is **0**,
97
- // which is finite and inside ±90. Every row with no location plotted at the equator, off the
98
- // west coast of Africa, and the "nothing to plot" message could never render. Caught by this
99
- // component's own render test on its first run; a source grep could not have seen it, and
100
- // neither could a screenshot of a table that HAS coordinates.
101
- const coord = (v: unknown, max: number): number | null => {
102
- if (v === null || v === undefined || v === "") return null;
103
- const n = Number(v);
104
- return Number.isFinite(n) && Math.abs(n) <= max ? n : null;
105
- };
106
- const pts = rows
107
- .map((r) => ({ r, lat: coord(r.lat, 90), lon: coord(r.lon, 180) }))
108
- .filter((p): p is { r: PubRow; lat: number; lon: number } =>
109
- p.lat !== null && p.lon !== null);
110
- if (!pts.length) {
111
- // ⚠ R6's second sentence, on a page: a map with nothing on it must SAY why,
112
- // never render an empty rectangle that reads as a broken link.
113
- return (
114
- <p className="pubv-note">
115
- None of these rows carry a location yet, so there is nothing to plot.
116
- </p>
117
- );
118
- }
119
- // Fit the points, then pad, so a cluster in one city does not render as one dot.
120
- const lats = pts.map((p) => p.lat);
121
- const lons = pts.map((p) => p.lon);
122
- const pad = 0.12;
123
- const minLat = Math.min(...lats);
124
- const maxLat = Math.max(...lats);
125
- const minLon = Math.min(...lons);
126
- const maxLon = Math.max(...lons);
127
- const spanLat = Math.max(maxLat - minLat, 0.05);
128
- const spanLon = Math.max(maxLon - minLon, 0.05);
129
- const box = { w: 1000, h: 560 };
130
- const at = (lat: number, lon: number) => ({
131
- x: (((lon - minLon + spanLon * pad) / (spanLon * (1 + 2 * pad))) * box.w),
132
- y: ((1 - (lat - minLat + spanLat * pad) / (spanLat * (1 + 2 * pad))) * box.h),
133
- });
134
- return (
135
- <div className="pubv-map">
136
- <svg viewBox={`0 0 ${box.w} ${box.h}`} role="img" aria-label="Map of the published rows">
137
- <rect x="0" y="0" width={box.w} height={box.h} className="pubv-map-bg" />
138
- {pts.map(({ r, lat, lon }) => {
139
- const p = at(lat, lon);
140
- return (
141
- <g key={r.pid}>
142
- <circle cx={p.x} cy={p.y} r="7" className="pubv-pin" />
143
- <title>{title(r)}</title>
144
- </g>
145
- );
146
- })}
147
- </svg>
148
- </div>
149
- );
150
- }
151
-
152
- export default function PublishedView({ token }: { token: string }) {
153
- const [page, setPage] = useState<PubPage | null>(null);
154
- const [phase, setPhase] = useState<Phase>("loading");
155
- const [passphrase, setPassphrase] = useState("");
156
- const [error, setError] = useState("");
157
- const [busy, setBusy] = useState(false);
158
-
159
- useEffect(() => {
160
- let live = true;
161
- setPhase("loading");
162
- fetch(`/api/v1/published/${encodeURIComponent(token)}`)
163
- .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
164
- .then((data) => {
165
- if (!live) return;
166
- // The server's two shapes: `{locked:true}` and nothing else, or the page.
167
- if (data && data.locked) {
168
- setPhase("locked");
169
- return;
170
- }
171
- setPage(data as PubPage);
172
- setPhase("ready");
173
- })
174
- // ⚠ ONE dead end for every failure, mirroring the server's uniform 403. Telling a visitor
175
- // "that link was revoked" versus "no such link" would hand back exactly the distinction the
176
- // server-side refusal exists to withhold.
177
- .catch(() => live && setPhase("gone"));
178
- return () => {
179
- live = false;
180
- };
181
- }, [token]);
182
-
183
- const unlock = (event: React.FormEvent) => {
184
- event.preventDefault();
185
- if (busy) return;
186
- setBusy(true);
187
- setError("");
188
- fetch(`/api/v1/published/${encodeURIComponent(token)}`, {
189
- method: "POST",
190
- headers: { "Content-Type": "application/json" },
191
- body: JSON.stringify({ passphrase }),
192
- })
193
- .then(async (r) => {
194
- if (r.ok) {
195
- setPage((await r.json()) as PubPage);
196
- setPhase("ready");
197
- // ⛔ The typed secret does not outlive the request that used it.
198
- setPassphrase("");
199
- return;
200
- }
201
- setError("That passphrase did not open this link.");
202
- })
203
- .catch(() => setError("That could not be checked — try again in a moment."))
204
- .finally(() => setBusy(false));
205
- };
206
-
207
- if (phase === "loading") {
208
- return <div className="pubv-root pubv-boot" aria-busy="true" />;
209
- }
210
-
211
- if (phase === "gone") {
212
- return (
213
- <div className="pubv-root">
214
- <div className="pubv-card">
215
- <h1 className="pubv-title">This link is not available</h1>
216
- <p className="pubv-note">
217
- It may have been revoked, or the view it pointed at may have changed. Ask whoever
218
- shared it for a new link.
219
- </p>
220
- </div>
221
- </div>
222
- );
223
- }
224
-
225
- if (phase === "locked") {
226
- return (
227
- <div className="pubv-root">
228
- <form className="pubv-card" onSubmit={unlock}>
229
- <h1 className="pubv-title">This link needs a passphrase</h1>
230
- <label className="pubv-label" htmlFor="pubv-pass">
231
- Passphrase
232
- </label>
233
- <input
234
- id="pubv-pass"
235
- className="pubv-input"
236
- type="password"
237
- autoFocus
238
- autoComplete="off"
239
- value={passphrase}
240
- onChange={(e) => setPassphrase(e.target.value)}
241
- />
242
- {error ? <p className="pubv-error">{error}</p> : null}
243
- <button className="pubv-btn" type="submit" disabled={busy || !passphrase}>
244
- {busy ? "Checking…" : "Open"}
245
- </button>
246
- </form>
247
- </div>
248
- );
249
- }
250
-
251
- if (!page) return null;
252
- return <PublishedBody page={page} />;
253
- }
254
-
255
- /**
256
- * The page itself, as a PURE function of the server's payload.
257
- *
258
- * ⭐ EXPORTED, AND SPLIT OUT FOR ONE REASON: it makes this surface RENDERABLE without a browser,
259
- * a server or a session. `renderToStaticMarkup` runs no effects, so a component that fetches in
260
- * `useEffect` can only ever paint its loading state under this repo's render harness — which
261
- * would have left the published page in the same "gated by things assertions cannot see" bucket
262
- * as everything else in [[ui-invisible-to-assertions]]. With the fetch above and the markup here,
263
- * `verify_wiring` can render the REAL component over a fixture payload and assert what a reader
264
- * would actually see — including the things that matter most and are least visible to a source
265
- * grep: that a hidden column's VALUE is nowhere in the emitted HTML, and that the page offers no
266
- * control a session-less visitor could press.
267
- *
268
- * ⚠ It takes the payload and nothing else. A prop for "is this a preview?" or a callback would
269
- * reintroduce exactly the state the split exists to remove.
270
- */
271
- export function PublishedBody({ page }: { page: PubPage }) {
272
- // The first text column is what a pin, a card or a row leads with. Derived from the
273
- // projection the server sent, never named here — this page has no idea what the table is.
274
- const lead = page.columns.find((c) => !NUMERIC.has(c.type)) || page.columns[0];
275
- const titleOf = (r: PubRow) => (lead ? cellText(r[lead.key]) : `#${r.pid}`);
276
-
277
- const body =
278
- page.mode === "map" ? (
279
- <MapPlot rows={page.rows} title={titleOf} />
280
- ) : page.mode === "catalog" || page.mode === "swipe" ? (
281
- <ul className="pubv-cards">
282
- {page.rows.map((r) => (
283
- <li className="pubv-card-item" key={r.pid}>
284
- <h2 className="pubv-card-title">{titleOf(r)}</h2>
285
- <dl className="pubv-pairs">
286
- {page.columns
287
- .filter((c) => !lead || c.key !== lead.key)
288
- .map((c) => (
289
- <div className="pubv-pair" key={c.key}>
290
- <dt>{c.label}</dt>
291
- <dd className={NUMERIC.has(c.type) ? "is-num" : undefined}>
292
- {cellText(r[c.key])}
293
- </dd>
294
- </div>
295
- ))}
296
- </dl>
297
- </li>
298
- ))}
299
- </ul>
300
- ) : (
301
- // timeseries / form / anything the server offers next. A read-only table is the
302
- // presentation that cannot be wrong about a mode this page has not learned yet.
303
- <div className="pubv-tablewrap">
304
- <table className="pubv-table">
305
- <thead>
306
- <tr>
307
- {page.columns.map((c) => (
308
- <th key={c.key} className={NUMERIC.has(c.type) ? "is-num" : undefined}>
309
- {c.label}
310
- </th>
311
- ))}
312
- </tr>
313
- </thead>
314
- <tbody>
315
- {page.rows.map((r) => (
316
- <tr key={r.pid}>
317
- {page.columns.map((c) => (
318
- <td key={c.key} className={NUMERIC.has(c.type) ? "is-num" : undefined}>
319
- {cellText(r[c.key])}
320
- </td>
321
- ))}
322
- </tr>
323
- ))}
324
- </tbody>
325
- </table>
326
- </div>
327
- );
328
-
329
- return (
330
- <div className="pubv-root pubv-page">
331
- <header className="pubv-head">
332
- <h1 className="pubv-title">{page.title || "Shared view"}</h1>
333
- <p className="pubv-count">
334
- {page.total} {page.total === 1 ? "record" : "records"}
335
- </p>
336
- </header>
337
- {body}
338
- {/* ⚠ R6's second sentence, rendered. A page that serves fewer rows than the view holds
339
- says so, with the cause — a short page that stays quiet about being short is the
340
- silent truncation the rule is actually about. */}
341
- {(page.limits || []).map((l) => (
342
- <p className="pubv-note" key={l.subject}>
343
- {l.detail}
344
- {l.recommendation ? ` — ${l.recommendation}` : ""}
345
- </p>
346
- ))}
347
- {page.rows.length === 0 ? (
348
- <p className="pubv-note">This view has no records right now.</p>
349
- ) : null}
350
- </div>
351
- );
352
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/publish/publish.css DELETED
@@ -1,174 +0,0 @@
1
- /* ---------------------------------------------------------------------------
2
- publish / publish.css — the published-view page (wave 33, item 8b, R5).
3
-
4
- ⚠ CO-LOCATED, per contract C4: `index.css` is B's file this wave, and the
5
- established practice for a new surface is a stylesheet beside its component
6
- (`query.css`, `SwipeView.css`, `navExtras.css`).
7
-
8
- ⚠ COLOUR is local (`--pubv-*`), TYPE is the product's (`--lp-fs-*`), and the
9
- split is not arbitrary — the first draft of this file declared literal sizes
10
- too and `verify_ui` reded on three of them, correctly.
11
-
12
- The FONT-TOKEN LAW is app-wide (DESIGN.md R5, gated by `verify_ui::font_literals`
13
- over every stylesheet under `web/src`), and it binds here for a reason this
14
- page makes sharper rather than weaker: `--lp-fs-*` are RATIOS of the
15
- `html { font-size }` root, so a literal `13px` here would be the one surface
16
- in the product that ignores a reader's browser text size. The draft's argument
17
- for going local — "a stranger's first load must look finished on its own" —
18
- was answered by checking rather than by asserting: `index.css` is imported by
19
- the app entry and is therefore in the single emitted stylesheet on every
20
- route, `#/v/<token>` included. There is no cascade in which these tokens are
21
- absent.
22
-
23
- ⚠ COLOUR stays local because there IS a real difference there: this page has
24
- no shell chrome around it, so it owns its whole surface rather than sitting
25
- inside one. The values are the product's (navy `#1F4E78`, DESIGN.md's
26
- neutrals), so nothing drifts visually.
27
-
28
- ⛔ NO EMOJI, no ALL-CAPS chrome — DESIGN.md R6 applies to a public page too.
29
- --------------------------------------------------------------------------- */
30
-
31
- .pubv-root {
32
- --pubv-ink: #1e2233;
33
- --pubv-muted: #5d6478;
34
- --pubv-line: #e3e6ee;
35
- --pubv-surface: #ffffff;
36
- --pubv-ground: #f6f7fb;
37
- --pubv-brand: #1f4e78;
38
-
39
- box-sizing: border-box;
40
- min-height: 100vh;
41
- padding: 40px 24px 64px;
42
- background: var(--pubv-ground);
43
- color: var(--pubv-ink);
44
- font-family: Inter, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
45
- font-size: var(--lp-fs-sm);
46
- line-height: 1.5;
47
- }
48
- .pubv-root *,
49
- .pubv-root *::before,
50
- .pubv-root *::after { box-sizing: inherit; }
51
-
52
- /* Deliberately wordless, exactly like the shell's boot card: a "Loading…" line
53
- would flash for one round trip on every open. */
54
- .pubv-boot { background: var(--pubv-ground); }
55
-
56
- .pubv-page { max-width: 1120px; margin: 0 auto; }
57
-
58
- .pubv-head {
59
- display: flex;
60
- align-items: baseline;
61
- gap: 12px;
62
- flex-wrap: wrap;
63
- margin-bottom: 20px;
64
- }
65
- .pubv-title {
66
- margin: 0;
67
- font-size: var(--lp-fs-lg);
68
- font-weight: 600;
69
- letter-spacing: -0.01em;
70
- color: var(--pubv-brand);
71
- }
72
- .pubv-count { margin: 0; color: var(--pubv-muted); font-size: var(--lp-fs-xs); }
73
- .pubv-note {
74
- margin: 14px 0 0;
75
- color: var(--pubv-muted);
76
- font-size: var(--lp-fs-xs);
77
- max-width: 68ch;
78
- }
79
-
80
- /* ── the passphrase card, and the not-available card ─────────────────────── */
81
- .pubv-card {
82
- max-width: 380px;
83
- margin: 12vh auto 0;
84
- padding: 26px 24px;
85
- background: var(--pubv-surface);
86
- border: 1px solid var(--pubv-line);
87
- border-radius: 12px;
88
- display: flex;
89
- flex-direction: column;
90
- gap: 10px;
91
- }
92
- .pubv-label { font-size: var(--lp-fs-2xs); font-weight: 500; color: var(--pubv-muted); }
93
- .pubv-input {
94
- font: inherit;
95
- padding: 9px 11px;
96
- border: 1px solid var(--pubv-line);
97
- border-radius: 8px;
98
- background: var(--pubv-surface);
99
- color: var(--pubv-ink);
100
- }
101
- .pubv-input:focus-visible { outline: 2px solid var(--pubv-brand); outline-offset: 1px; }
102
- .pubv-error { margin: 0; color: #a3453c; font-size: var(--lp-fs-xs); }
103
- .pubv-btn {
104
- font: inherit;
105
- font-weight: 500;
106
- margin-top: 4px;
107
- padding: 9px 14px;
108
- border: 0;
109
- border-radius: 8px;
110
- background: var(--pubv-brand);
111
- color: #fff;
112
- cursor: pointer;
113
- }
114
- .pubv-btn:disabled { opacity: 0.5; cursor: default; }
115
-
116
- /* ── the map plot ────────────────────────────────────────────────────────── */
117
- .pubv-map {
118
- background: var(--pubv-surface);
119
- border: 1px solid var(--pubv-line);
120
- border-radius: 12px;
121
- padding: 8px;
122
- overflow: hidden;
123
- }
124
- .pubv-map svg { display: block; width: 100%; height: auto; }
125
- .pubv-map-bg { fill: #eef2f7; }
126
- .pubv-pin { fill: var(--pubv-brand); fill-opacity: 0.78; stroke: #fff; stroke-width: 1.5; }
127
-
128
- /* ── catalog / swipe cards ───────────────────────────────────────────────── */
129
- .pubv-cards {
130
- list-style: none;
131
- margin: 0;
132
- padding: 0;
133
- display: grid;
134
- grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
135
- gap: 14px;
136
- }
137
- .pubv-card-item {
138
- background: var(--pubv-surface);
139
- border: 1px solid var(--pubv-line);
140
- border-radius: 12px;
141
- padding: 16px 16px 12px;
142
- }
143
- .pubv-card-title { margin: 0 0 8px; font-size: var(--lp-fs-sm); font-weight: 600; }
144
- .pubv-pairs { margin: 0; display: grid; gap: 4px; }
145
- .pubv-pair { display: flex; gap: 10px; justify-content: space-between; align-items: baseline; }
146
- .pubv-pair dt { color: var(--pubv-muted); font-size: var(--lp-fs-2xs); }
147
- .pubv-pair dd { margin: 0; font-size: var(--lp-fs-xs); text-align: right; }
148
- .pubv-pair dd.is-num { font-variant-numeric: tabular-nums; }
149
-
150
- /* ── the fallback table ──────────────────────────────────────────────────── */
151
- /* ⚠ The wrapper scrolls, not the page: a wide table must never make the whole
152
- document scroll sideways on a phone. */
153
- .pubv-tablewrap {
154
- overflow-x: auto;
155
- background: var(--pubv-surface);
156
- border: 1px solid var(--pubv-line);
157
- border-radius: 12px;
158
- }
159
- .pubv-table { border-collapse: collapse; width: 100%; font-size: var(--lp-fs-xs); }
160
- .pubv-table th,
161
- .pubv-table td {
162
- text-align: left;
163
- padding: 9px 14px;
164
- border-bottom: 1px solid var(--pubv-line);
165
- white-space: nowrap;
166
- }
167
- .pubv-table th { font-weight: 500; color: var(--pubv-muted); }
168
- .pubv-table tr:last-child td { border-bottom: 0; }
169
- .pubv-table .is-num { text-align: right; font-variant-numeric: tabular-nums; }
170
-
171
- @media (max-width: 600px) {
172
- .pubv-root { padding: 24px 14px 48px; }
173
- .pubv-card { margin-top: 8vh; }
174
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/publish/publishPanel.css DELETED
@@ -1,102 +0,0 @@
1
- /* ---------------------------------------------------------------------------
2
- publish / publishPanel.css — the publish control inside the share dialog
3
- (wave 33, item 8b, R5, W33-T27).
4
-
5
- ⚠ CO-LOCATED per contract C4 (`index.css` is B's file this wave), and SEPARATE
6
- from `publish.css` on purpose: that sheet styles the PUBLIC page, which has no
7
- shell around it and owns its whole surface. This one lives INSIDE a dialog the
8
- shell already styles, so it inherits that dialog's ink, surface and radius
9
- rather than declaring its own — a second palette one modal deep is how two
10
- greys end up next to each other.
11
-
12
- ⛔ TYPE IS THE PRODUCT'S (`--lp-fs-*`), never a literal. DESIGN.md R5, gated
13
- app-wide by `verify_ui::font_literals`; `publish.css` learned this the
14
- expensive way in the same hour.
15
- --------------------------------------------------------------------------- */
16
-
17
- .pubp {
18
- margin-top: 14px;
19
- padding-top: 14px;
20
- border-top: 1px solid var(--lp-line, #e3e6ee);
21
- display: flex;
22
- flex-direction: column;
23
- gap: 8px;
24
- }
25
-
26
- .pubp-head {
27
- margin: 0;
28
- font-size: var(--lp-fs-sm);
29
- font-weight: 600;
30
- color: var(--lp-ink);
31
- }
32
-
33
- .pubp-sub,
34
- .pubp-state,
35
- .pubp-label {
36
- margin: 0;
37
- font-size: var(--lp-fs-2xs);
38
- color: var(--lp-muted);
39
- }
40
- .pubp-sub { max-width: 62ch; }
41
-
42
- .pubp-linkrow { display: flex; gap: 8px; align-items: center; }
43
- .pubp-link {
44
- font: inherit;
45
- font-size: var(--lp-fs-2xs);
46
- flex: 1 1 auto;
47
- min-width: 0;
48
- padding: 7px 9px;
49
- border: 1px solid var(--lp-line, #e3e6ee);
50
- border-radius: var(--lp-r-sm, 6px);
51
- background: var(--lp-surface-2, #f6f7fb);
52
- color: var(--lp-ink);
53
- }
54
-
55
- .pubp-access { display: flex; flex-wrap: wrap; gap: 14px; }
56
- .pubp-radio {
57
- display: flex;
58
- align-items: center;
59
- gap: 6px;
60
- font-size: var(--lp-fs-2xs);
61
- color: var(--lp-ink);
62
- cursor: pointer;
63
- }
64
-
65
- .pubp-pass { display: flex; flex-direction: column; gap: 4px; }
66
- .pubp-input {
67
- font: inherit;
68
- font-size: var(--lp-fs-2xs);
69
- padding: 7px 9px;
70
- border: 1px solid var(--lp-line, #e3e6ee);
71
- border-radius: var(--lp-r-sm, 6px);
72
- background: var(--lp-surface, #fff);
73
- color: var(--lp-ink);
74
- }
75
-
76
- .pubp-err { margin: 0; font-size: var(--lp-fs-2xs); color: var(--lp-red-deep, #a3453c); }
77
-
78
- .pubp-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 2px; }
79
- .pubp-btn {
80
- font: inherit;
81
- font-size: var(--lp-fs-2xs);
82
- font-weight: 500;
83
- padding: 7px 12px;
84
- border: 1px solid var(--lp-line, #e3e6ee);
85
- border-radius: var(--lp-r-sm, 6px);
86
- background: var(--lp-surface, #fff);
87
- color: var(--lp-ink);
88
- cursor: pointer;
89
- }
90
- .pubp-btn:hover:not(:disabled) { background: var(--lp-surface-2, #f6f7fb); }
91
- .pubp-btn:disabled { opacity: 0.5; cursor: default; }
92
- /* The CTA colour is reserved for the CTA (DESIGN.md:58) and Publish is one. */
93
- .pubp-btn.is-primary {
94
- background: var(--lp-primary, #1f4e78);
95
- border-color: var(--lp-primary, #1f4e78);
96
- color: #fff;
97
- }
98
- .pubp-btn.is-primary:hover:not(:disabled) { filter: brightness(1.06); }
99
- /* ⚠ Unpublish is DESTRUCTIVE-ish but not destructive: it revokes a link, it
100
- deletes no data. So it is tinted, never filled — a red button here would rank
101
- it beside "delete this database", which it is not. */
102
- .pubp-btn.is-danger { color: var(--lp-red-deep, #a3453c); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/settings/ModulePermsList.tsx DELETED
@@ -1,193 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // settings / ModulePermsList.tsx — THE per-database permission list. (wave 33,
3
- // owner items 10 + 11 · W33-T34 / W33-T38.)
4
- //
5
- // ⭐ WHY THIS FILE EXISTS, IN THE OWNER'S OWN WORDS: *"under manage user (and
6
- // manage agent too since its the same exact layout)"*. "The same exact layout"
7
- // has exactly one honest implementation, and it is not two components kept in
8
- // step by intention. `PermsEditor` and `ManageAgentPane` both render THIS, so a
9
- // change to the disclosure, the unenforced sentence or the summary line reaches
10
- // both or neither.
11
- //
12
- // ⛔ THE ALTERNATIVE, NAMED SO NOBODY RE-DERIVES IT. Copying the JSX into the
13
- // agent pane would have been faster today and is the exact shape of every defect
14
- // this repo keeps re-finding: `may_open` vs the automation table picker (wave
15
- // 20), `clean_fields` vs `_clean_field` (wave 28), `FILTER_OPS`' three mirrors.
16
- // Two renderings of one rule disagree in front of a user, and each looks correct
17
- // read on its own.
18
- //
19
- // PURELY PRESENTATIONAL. It owns exactly one piece of state — WHICH row is
20
- // expanded — because that is a property of this list and of nothing else. Every
21
- // value it shows and every write it makes belongs to the caller: the account
22
- // editor PUTs to `/admin/users/{u}/perms`, the agent editor to its own door, and
23
- // this component knows about neither.
24
- // ---------------------------------------------------------------------------
25
-
26
- import { useState } from "react";
27
- import type { ReactNode } from "react";
28
- import { FilterBuilderPanel, FieldsHidePanel } from "../filter-kit";
29
- import type { FilterTree } from "../customer-grid/types";
30
- import type { PermsModule, PermsRecord } from "./permsModel";
31
- import { filterOf, hiddenSet, hideableKeys, identityKey, moduleSummary } from "./permsModel";
32
- import "./perms.css";
33
-
34
- export interface ModulePermsListProps {
35
- /** In server order — the order the sections render in. */
36
- modules: PermsModule[];
37
- /** The DRAFT being edited, keyed by module. */
38
- entries: PermsRecord;
39
- onAccess: (key: string, on: boolean) => void;
40
- onFilter: (key: string, next: FilterTree | null) => void;
41
- onToggleHidden: (key: string, fieldKey: string) => void;
42
- onSetHidden: (key: string, keys: string[]) => void;
43
- /** People this tenant can name in a `user` condition. Absent ⇒ the panel says so. */
44
- userOptions?: string[];
45
- /** Anything the CALLER wants in a row's head — the account editor's "Copy to…"
46
- * door. Returning null is the normal case and costs the row nothing. */
47
- headExtra?: (m: PermsModule) => ReactNode;
48
- /** Shown when the tenant governs nothing at all. */
49
- emptyNote?: string;
50
- }
51
-
52
- export function ModulePermsList({
53
- modules,
54
- entries,
55
- onAccess,
56
- onFilter,
57
- onToggleHidden,
58
- onSetHidden,
59
- userOptions,
60
- headExtra,
61
- emptyNote,
62
- }: ModulePermsListProps) {
63
- // ⭐ Owner item 11: *"the database should not show all immediately the detail
64
- // (for filter or hide fields)"*. Single-valued rather than a Set, deliberately
65
- // — the complaint was a wall of panels, and an accordion cannot become one by
66
- // accumulation.
67
- const [openDetail, setOpenDetail] = useState<string | null>(null);
68
-
69
- if (modules.length === 0) {
70
- return (
71
- <p className="pg-empty">
72
- {emptyNote ?? "This workspace has no databases whose access can be restricted."}
73
- </p>
74
- );
75
- }
76
-
77
- return (
78
- <>
79
- {modules.map((m) => {
80
- const entry = entries[m.key];
81
- const on = entry?.access === true;
82
- const schemaless = m.fields.length === 0;
83
- const shown = openDetail === m.key;
84
- // ⛔⛔ `!== false`, NOT truthiness. `verify_ui`'s NC
85
- // `perms-editor-renders-controls-before-the-record-arrives` injects a raw
86
- // module literal with no `enforced` key; read as truthiness that module
87
- // renders as UNENFORCED — no checkbox — and the NC stops biting for a
88
- // reason unrelated to what it guards [[gate-negative-control]]. It caught
89
- // exactly that within an hour of the flag existing. Stated the same way
90
- // `permsModel.parsePermsPayload` states it: only an explicit `false`
91
- // disarms a row, because every module a payload could carry before this
92
- // flag existed WAS enforced [[default-must-pass-its-own-guard]].
93
- const enforced = m.enforced !== false;
94
- const canDetail = on && !schemaless && enforced;
95
-
96
- // ⛔ A database this editor does not decide gets NO access toggle — not a
97
- // disabled one, not an unchecked one. An unchecked box beside a name
98
- // reads as "denied", and nothing here denies it.
99
- if (!enforced) {
100
- return (
101
- <section className="set-card set-perm-mod" key={m.key}>
102
- <div className="set-perm-modhead">
103
- <span className="set-perm-modname">{m.label}</span>
104
- <span className="set-perm-headend">
105
- <span className="set-perm-sum">Not set here</span>
106
- </span>
107
- </div>
108
- <p className="set-help">
109
- Access to this database is decided by who created it and who it has been
110
- shared with, not by this editor. A rule saved here would not be applied,
111
- so none is offered.
112
- </p>
113
- </section>
114
- );
115
- }
116
-
117
- return (
118
- <section className="set-card set-perm-mod" key={m.key}>
119
- <div className="set-perm-modhead">
120
- <label className="set-check set-perm-toggle">
121
- <input
122
- type="checkbox"
123
- checked={on}
124
- onChange={(e) => onAccess(m.key, e.target.checked)}
125
- />
126
- <span className="set-perm-modname">{m.label}</span>
127
- </label>
128
- {/* ⚠ Wrapped rather than left as siblings of the toggle:
129
- `.set-perm-modhead` is `space-between` and lives in `index.css`,
130
- which is lane B's under contract C4. Grouping the trailing
131
- controls keeps every new one off that rule — one flex child in,
132
- one flex child out. */}
133
- <span className="set-perm-headend">
134
- <span className="set-perm-sum">{moduleSummary(entry, schemaless)}</span>
135
- {canDetail ? (
136
- <button
137
- type="button"
138
- className="set-secondary set-perm-disclose"
139
- aria-expanded={shown}
140
- onClick={() => setOpenDetail((k) => (k === m.key ? null : m.key))}
141
- >
142
- {shown ? "Hide detail" : "Conditions and fields"}
143
- </button>
144
- ) : null}
145
- {headExtra?.(m) ?? null}
146
- </span>
147
- </div>
148
-
149
- {/* R9's fail-closed rendering: no readable schema means the access
150
- toggle and nothing else. The record it saves says the same thing —
151
- no filter, no hidden fields — so the editor and the payload cannot
152
- disagree (`permsModel.toPutBody`). */}
153
- {on && schemaless ? (
154
- <p className="set-help">
155
- No field list is available for this database, so access is all this editor
156
- can set for it. Conditions and hidden fields need a schema.
157
- </p>
158
- ) : null}
159
-
160
- {canDetail && shown ? (
161
- <div className="set-perm-panels">
162
- <div className="cg-pop set-perm-pop">
163
- <FilterBuilderPanel
164
- fields={m.fields}
165
- filters={filterOf(entries, m.key)}
166
- onChange={(next) => onFilter(m.key, next)}
167
- userOptions={userOptions}
168
- />
169
- </div>
170
- <div className="cg-pop set-perm-pop">
171
- <FieldsHidePanel
172
- fields={m.fields}
173
- hidden={hiddenSet(entries, m.key)}
174
- onToggle={(key) => onToggleHidden(m.key, key)}
175
- // ⚠ `lockedKey` IS NOT OPTIONAL HERE, whatever the prop says.
176
- // Absent, the panel locks nothing and one click on "Hide all"
177
- // hides the row's own name too — a record whose faithful
178
- // enforcement is a table of blank rows, which the server's PUT
179
- // validation would accept because the identity column is a
180
- // perfectly KNOWN field key.
181
- lockedKey={identityKey(m.fields)}
182
- onHideAll={() => onSetHidden(m.key, hideableKeys(m.fields))}
183
- onShowAll={() => onSetHidden(m.key, [])}
184
- />
185
- </div>
186
- </div>
187
- ) : null}
188
- </section>
189
- );
190
- })}
191
- </>
192
- );
193
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web/src/settings/perms.css DELETED
@@ -1,47 +0,0 @@
1
- /* settings/perms.css — wave 33 (owner item 11, W33-T34/T38).
2
- *
3
- * ⛔ CONTRACT C4: `index.css` is lane B's. Everything the permission editor's
4
- * per-database DISCLOSURE needs is new, so it lives here and is imported by
5
- * `PermsEditor.tsx` — the established practice (`query.css`, `navExtras.css`,
6
- * `SwipeView.css`). Nothing in this file redefines an `index.css` rule; it only
7
- * styles classes that did not exist before this wave.
8
- *
9
- * WHY A DISCLOSURE AT ALL. Owner, 2026-08-14: *"the database should not show all
10
- * immediately the detail (for filter or hide fields), the user should have the
11
- * ability to see ALL databases"*. Those two clauses pull against each other —
12
- * more databases, less detail per database — and an accordion is what satisfies
13
- * both. Before wave 33 the list was a fixed TWO and every panel rendered inline;
14
- * it is now every database the tenant has.
15
- */
16
-
17
- /* The trailing controls of a module head, grouped as ONE flex child so the
18
- `space-between` rule in `index.css` still sees exactly two children. */
19
- .set-perm-headend {
20
- display: flex;
21
- align-items: center;
22
- gap: 10px;
23
- flex: none;
24
- }
25
-
26
- /* Smaller than a primary action and quieter than `Copy to…`: this button reveals
27
- detail, it does not commit anything. It borrows `.set-secondary`'s border,
28
- surface and focus ring rather than restating them — a second definition of the
29
- button chrome is a second place for the focus ring to go missing. */
30
- .set-perm-disclose {
31
- font-size: var(--lp-fs-2xs);
32
- padding: 3px 9px;
33
- white-space: nowrap;
34
- }
35
-
36
- /* The open state reads as pressed, so a scrolled-away head still says which
37
- database owns the panels below it. */
38
- .set-perm-disclose[aria-expanded="true"] {
39
- border-color: var(--lp-blue-deep);
40
- color: var(--lp-blue-deep);
41
- }
42
-
43
- @media (max-width: 640px) {
44
- /* The head wraps before the label truncates: a database name is the one thing
45
- in this row that cannot be guessed from context. */
46
- .set-perm-headend { flex-wrap: wrap; justify-content: flex-end; }
47
- }