fsanyoto commited on
Commit
3db79d6
Β·
verified Β·
1 Parent(s): 84a1769

Deploy Loopable

Browse files
aios_grid.py CHANGED
@@ -101,9 +101,17 @@ def _round(v):
101
  #: `phone` / `email` / `url` (text-family with per-type rendering) Β· `rating` (top-level
102
  #: `max`, SVG stars client-side β€” never emoji) Β· `created_time` (READ-ONLY, renders the row's
103
  #: `_created`) Β· `formula` (READ-ONLY, client-computed from the row's other cells).
 
 
 
 
 
 
 
 
104
  CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
105
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
106
- "automation"}
107
  #: User-created types whose CELLS are read-only: their values are computed (formula β€” client
108
  #: side, any error degrades to BLANK) or system-owned (created_time = the row's `_created`).
109
  #: Emitted with the cohort column's read-only mechanism β€” `source: 'odoo'` + `derived` β€” so
@@ -615,7 +623,13 @@ def fields_from_workspace(workspace=None, cohorts=False, scope_key=None, fields_
615
  if ftype == "automation" and _clean_automation(field.get("automation")) else {}),
616
  **_field_extras(field, ftype),
617
  })
618
- if cohorts:
 
 
 
 
 
 
619
  out.append(cohort_field())
620
  return out
621
 
@@ -1647,15 +1661,21 @@ def workspace_wire(ws, uname, pool_pids, defs=None, scope_key='customer', storag
1647
  `cohortMode`/`scopeChoice` (the API stamps its own from `?scope=`).
1648
 
1649
  Wave 16 C-TOPIC: `fields_base` selects the canonical contract (absent = customer,
1650
- byte-identical); `with_cohorts=False` is the PRODUCT surface β€” cohorts are customer
1651
- machinery (`modules/cohort` stores partner pids), and resolving them against product pids
1652
- would intersect two unrelated id spaces and render a plausible, meaningless member count.
 
 
 
 
 
 
1653
  """
1654
  import modules.cohort as cohort_mod
1655
 
1656
  cohort_lists = []
1657
  if with_cohorts:
1658
- for cid, c in sorted(cohort_mod.visible(uname, pool_pids).items(),
1659
  key=lambda kv: (kv[1].get('name') or '').lower()):
1660
  members = [p for p in (c.get('members') or []) if p in pool_pids]
1661
  entry = {'id': cid, 'name': c.get('name') or cid, 'pids': members}
 
101
  #: `phone` / `email` / `url` (text-family with per-type rendering) Β· `rating` (top-level
102
  #: `max`, SVG stars client-side β€” never emoji) Β· `created_time` (READ-ONLY, renders the row's
103
  #: `_created`) Β· `formula` (READ-ONLY, client-computed from the row's other cells).
104
+ #: ⭐ Wave-19 R7 / contract C5: `image` β€” a PICTURE on a record. The cell holds a string
105
+ #: REFERENCE, never bytes: a product `code`, an `ed:<slug>` editorial asset, or `rec:<id>` for
106
+ #: something uploaded through the field (`POST /api/v1/assets/records`). Storing a reference is
107
+ #: what lets Royal's 1,142 existing SKU masters appear with nothing re-uploaded, and it keeps the
108
+ #: overlay stratum the size it is β€” base64 bytes in a JSON blob read on every render would be a
109
+ #: megabyte-per-row tax on the whole store. Editable by NATURE (deliberately NOT in
110
+ #: `READONLY_CUSTOM_TYPES`): the ref is what the upload endpoint hands back, and the client PATCHes
111
+ #: it through the ordinary overlay wall rather than the asset route writing cells behind it.
112
  CUSTOM_FIELD_TYPES = {"text", "select", "multiselect", "user", "int", "currency", "pct", "date",
113
  "checkbox", "phone", "email", "url", "rating", "created_time", "formula",
114
+ "automation", "image"}
115
  #: User-created types whose CELLS are read-only: their values are computed (formula β€” client
116
  #: side, any error degrades to BLANK) or system-owned (created_time = the row's `_created`).
117
  #: Emitted with the cohort column's read-only mechanism β€” `source: 'odoo'` + `derived` β€” so
 
623
  if ftype == "automation" and _clean_automation(field.get("automation")) else {}),
624
  **_field_extras(field, ftype),
625
  })
626
+ if cohorts and not any(f.get('key') == COHORT_COLUMN for f in out):
627
+ # ⚠ The emptiness check is WAVE 19's, and it is about the topics R9 opened this column to.
628
+ # A user table's field keys are slugged from whatever its creator typed, so a column
629
+ # literally called "Cohorts" produces the key `cohorts` β€” and appending here unguarded
630
+ # would put TWO fields with one key on the wire. The client indexes fields by key, so the
631
+ # duplicate does not error: it silently paints one column's values under the other's
632
+ # header. The user's own column wins; the derived one steps aside rather than shadowing it.
633
  out.append(cohort_field())
634
  return out
635
 
 
1661
  `cohortMode`/`scopeChoice` (the API stamps its own from `?scope=`).
1662
 
1663
  Wave 16 C-TOPIC: `fields_base` selects the canonical contract (absent = customer,
1664
+ byte-identical).
1665
+
1666
+ ⭐ WAVE 19 / R9 β€” `with_cohorts` NO LONGER MEANS "customer only". Wave 16 set it False on the
1667
+ product surface because cohorts were a single customer-keyed bucket, so resolving them against
1668
+ product pids would have intersected two unrelated id spaces and printed a plausible,
1669
+ meaningless member count. `modules.cohort` is scope-parameterized now: the lists come from
1670
+ THIS topic's bucket (`cohort_mod.scoped(scope_key)`), so their ids are this topic's ids and
1671
+ the intersection with `pool_pids` is the ordinary one. The flag survives as an honest OFF
1672
+ switch for a surface that wants no membership channel at all β€” it is not a topic wall.
1673
  """
1674
  import modules.cohort as cohort_mod
1675
 
1676
  cohort_lists = []
1677
  if with_cohorts:
1678
+ for cid, c in sorted(cohort_mod.scoped(scope_key).visible(uname, pool_pids).items(),
1679
  key=lambda kv: (kv[1].get('name') or '').lower()):
1680
  members = [p for p in (c.get('members') or []) if p in pool_pids]
1681
  entry = {'id': cid, 'name': c.get('name') or cid, 'pids': members}
aios_grid_component/index.html CHANGED
The diff for this file is too large to render. See raw diff
 
aios_grid_embed.html CHANGED
The diff for this file is too large to render. See raw diff
 
core/assets.py CHANGED
@@ -27,7 +27,11 @@ _MANIFEST_TTL = 300
27
  #: (fetched_at, {"CODE": {...}}, {"slug": {...}}) β€” one manifest read per process per TTL.
28
  #: DEBT-5 (2026-08-04): the same manifest.json now carries a second, NON-SKU half under
29
  #: "editorial" β€” full-bleed lifestyle imagery for catalog gallery pages, keyed by slug.
30
- _MANIFEST = {'at': 0.0, 'codes': None, 'editorial': None}
 
 
 
 
31
 
32
 
33
  def repo_id():
@@ -50,9 +54,10 @@ def _load():
50
  man = json.loads(Path(p).read_text(encoding='utf-8')) or {}
51
  codes = man.get('codes') or {}
52
  editorial_ = man.get('editorial') or {}
 
53
  except Exception:
54
- codes, editorial_ = {}, {}
55
- _MANIFEST.update(at=now, codes=codes, editorial=editorial_)
56
 
57
 
58
  def manifest():
@@ -128,6 +133,86 @@ def put_editorial(slug, orig_bytes, ext, web_png):
128
  return True
129
 
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  def reset_cache():
132
  """Drop the memoized manifest β€” for gates and for a post-ingest refresh."""
133
- _MANIFEST.update(at=0.0, codes=None, editorial=None)
 
27
  #: (fetched_at, {"CODE": {...}}, {"slug": {...}}) β€” one manifest read per process per TTL.
28
  #: DEBT-5 (2026-08-04): the same manifest.json now carries a second, NON-SKU half under
29
  #: "editorial" β€” full-bleed lifestyle imagery for catalog gallery pages, keyed by slug.
30
+ #: ⭐ WAVE 19 R7 / C5: and a THIRD, under "records" β€” pictures uploaded through an `image` FIELD,
31
+ #: namespaced BY TENANT (`<tenant>/<id>`). The other two namespaces are Royal's catalogue assets
32
+ #: and are tenant-#0 material by nature; this one is written by any signed-in user of any tenant,
33
+ #: so the tenant is part of the address and comes from the SESSION on both write and read.
34
+ _MANIFEST = {'at': 0.0, 'codes': None, 'editorial': None, 'records': None}
35
 
36
 
37
  def repo_id():
 
54
  man = json.loads(Path(p).read_text(encoding='utf-8')) or {}
55
  codes = man.get('codes') or {}
56
  editorial_ = man.get('editorial') or {}
57
+ records_ = man.get('records') or {}
58
  except Exception:
59
+ codes, editorial_, records_ = {}, {}, {}
60
+ _MANIFEST.update(at=now, codes=codes, editorial=editorial_, records=records_)
61
 
62
 
63
  def manifest():
 
133
  return True
134
 
135
 
136
+ # ───────────────────────────────────────── record images (wave 19, R7 / contract C5)
137
+ #
138
+ # A picture attached to ONE ROW through an `image` field, by any signed-in user. Two things make
139
+ # this namespace different from the two above, and both are about who may write it:
140
+ #
141
+ # * it is TENANT-ADDRESSED (`<tenant>/<id>`), because a nurilab user uploading a photo must not
142
+ # land anywhere a royal-imports read can reach. The tenant comes from the SESSION at both
143
+ # ends β€” never from the reference string, which is why a `rec:` ref copied between tenants
144
+ # resolves to a 404 rather than to somebody else's photograph.
145
+ # * the id is SERVER-MINTED hex, so the client never names a path component.
146
+
147
+
148
+ def records():
149
+ """{'<tenant>/<id>': {'ext': ...}} β€” the record-image half of the manifest; {} if unreachable."""
150
+ _load()
151
+ return _MANIFEST['records'] or {}
152
+
153
+
154
+ def record_ref(tenant, asset_id):
155
+ """The manifest key for one tenant's asset. ONE composition point, so read and write cannot
156
+ disagree about where a picture lives."""
157
+ return f"{str(tenant or '').strip().lower()}/{str(asset_id or '').strip().lower()}"
158
+
159
+
160
+ def fetch_record(tenant, asset_id, quality='web'):
161
+ """A local Path to one RECORD image, or None β€” same shape as fetch()/fetch_editorial().
162
+
163
+ β›” Returns None for an id this tenant does not own, and that is the cross-tenant wall: the
164
+ lookup key is composed from the caller's own tenant, so an id belonging to another tenant is
165
+ simply absent from the manifest under this address. Indistinguishable from "no such picture",
166
+ which is exactly what the caller is entitled to know.
167
+ """
168
+ ref = record_ref(tenant, asset_id)
169
+ meta = records().get(ref)
170
+ if not meta:
171
+ return None
172
+ rel = (f'assets/records/{ref}/web.png' if quality == 'web'
173
+ else f"assets/records/{ref}/orig{meta.get('ext', '.png')}")
174
+ try:
175
+ from huggingface_hub import hf_hub_download
176
+ return Path(hf_hub_download(repo_id(), rel, repo_type='dataset', token=_token()))
177
+ except Exception:
178
+ return None
179
+
180
+
181
+ def put_record(tenant, asset_id, orig_bytes, ext, web_png):
182
+ """Store one record image: original, web derivative and the updated manifest in ONE commit
183
+ (a partial upload can never leave a listed-but-unfetchable reference). Raises on failure β€”
184
+ the route turns that into an honest 503, never a silent success.
185
+
186
+ ⚠ Shares `put_editorial`'s read-modify-write caveat on manifest.json: two uploads landing in
187
+ the same second could drop one entry. Uploads through a field are rarer than a scroll but far
188
+ from admin-rare, so this is the first namespace where that will actually bite β€” booked in the
189
+ wave doc rather than quietly inherited.
190
+ """
191
+ import json
192
+
193
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
194
+ ref = record_ref(tenant, asset_id)
195
+ api = HfApi(token=_token())
196
+ try:
197
+ p = hf_hub_download(repo_id(), 'manifest.json', repo_type='dataset', token=_token(),
198
+ force_download=True)
199
+ man = json.loads(Path(p).read_text(encoding='utf-8')) or {}
200
+ except Exception:
201
+ man = {}
202
+ man.setdefault('records', {})[ref] = {'ext': ext}
203
+ api.create_commit(
204
+ repo_id(), repo_type='dataset',
205
+ operations=[
206
+ CommitOperationAdd(f'assets/records/{ref}/orig{ext}', orig_bytes),
207
+ CommitOperationAdd(f'assets/records/{ref}/web.png', web_png),
208
+ CommitOperationAdd('manifest.json',
209
+ json.dumps(man, indent=1, sort_keys=True).encode('utf-8')),
210
+ ],
211
+ commit_message=f'record image: {ref}')
212
+ reset_cache()
213
+ return True
214
+
215
+
216
  def reset_cache():
217
  """Drop the memoized manifest β€” for gates and for a post-ingest refresh."""
218
+ _MANIFEST.update(at=0.0, codes=None, editorial=None, records=None)
core/grid_events.py CHANGED
@@ -145,6 +145,35 @@ def _tops(ctx):
145
  return ctx.table if ctx.table is not None else cl_mod.TABLE_OPS
146
 
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  # ------------------------------------------------------------------ the workspace family (X1 amd.)
149
  def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
150
  """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
@@ -636,10 +665,11 @@ def handle_one(event, ctx):
636
  # the SET it is, in the store that owns it; the view record must not grow a second title
637
  # that the read side would then have to arbitrate. Routed rather than duplicated.
638
  if _is_locked_view and store.available():
639
- _cur = (cohort_mod.all_for(uname).get(view_id) or {}).get('name')
 
640
  if name and name != _cur:
641
  try:
642
- cohort_mod.rename(uname, view_id, name)
643
  except ValueError as _e:
644
  _tel.error('cohort:rename-via-view', _e)
645
  view = {'id': view_id, 'name': name,
@@ -711,8 +741,8 @@ def handle_one(event, ctx):
711
  # on the very next render: the row would come back, minus the user's sort and columns,
712
  # which reads as a corruption rather than as a refusal. Own sets only (`all_for`), the
713
  # same wall `cohort_delete` rides.
714
- if store.available() and view_id in cohort_mod.all_for(uname):
715
- cohort_mod.delete(uname, view_id)
716
  _tops(ctx).delete_view(uname, view_id)
717
  # True, unlike an ordinary view_delete: the lists payload IS server truth and the
718
  # client cannot know the membership channel changed.
@@ -905,17 +935,18 @@ def handle_one(event, ctx):
905
  # caller's permitted pool β€” the same guard add_to_list rides.
906
  if not store.available():
907
  return False
 
908
  cohort_id = str(event.get('cohortId') or '').strip()[:120]
909
- if not cohort_id or cohort_id not in cohort_mod.all_for(uname):
910
  return False
911
  try:
912
  if kind == 'cohort_rename':
913
  name = str(event.get('name') or '').strip()[:120]
914
  if not name:
915
  return False
916
- cohort_mod.rename(uname, cohort_id, name)
917
  elif kind == 'cohort_delete':
918
- cohort_mod.delete(uname, cohort_id)
919
  else:
920
  raw_pids = event.get('pids')
921
  if not isinstance(raw_pids, list):
@@ -924,9 +955,9 @@ def handle_one(event, ctx):
924
  if not pids:
925
  return False
926
  if kind == 'cohort_add':
927
- cohort_mod.add_members(uname, cohort_id, pids)
928
  else:
929
- cohort_mod.remove_members(uname, cohort_id, pids)
930
  except ValueError as e:
931
  _tel.error('cohort:panel-edit', e)
932
  return False
@@ -935,21 +966,31 @@ def handle_one(event, ctx):
935
  return True
936
 
937
  if kind in ('doc_add', 'doc_delete', 'doc_fetch'):
938
- # DOCUMENTS on a customer row (owner item 12, contract C5). Metadata in the store key
939
  # `customer_docs`; the BYTES live at their own path in the tenant dataset, never in a
940
  # JSON blob β€” see core.store.upload_bytes for why that distinction is load-bearing.
 
 
 
 
 
 
 
 
941
  import base64 as _b64c
942
  import re as _re_mod
943
  if not store.available():
944
  return False
 
 
945
  pid = event.get('pid')
946
  doc_id = str(event.get('docId') or '').strip()[:80]
947
  # The pid wall is the SAME one every other row-scoped event rides: a caller may only
948
- # touch customers inside their own permitted pool. Without it, documents would be the
949
  # one surface where a scoped agent could read another book's rows.
950
  if not isinstance(pid, int) or pid not in allowed_pids or not doc_id:
951
  return False
952
- meta_all = store.get(_DOCS_KEY) or {}
953
  row = list((meta_all.get(str(pid)) or []))
954
 
955
  if kind == 'doc_add':
@@ -969,9 +1010,9 @@ def handle_one(event, ctx):
969
  if len(row) >= _DOC_MAX_PER_ROW or any(d.get('id') == doc_id for d in row):
970
  return False
971
  safe = _re_mod.sub(r'[^A-Za-z0-9._-]', '_', name)[:80] or 'file'
972
- path = f'docs/{pid}/{doc_id}_{safe}'
973
  try:
974
- store.upload_bytes(path, blob, message=f'doc {doc_id} for customer {pid}')
975
  except Exception as _ue:
976
  _tel.error('docs:upload', _ue)
977
  return False
@@ -1008,7 +1049,13 @@ def handle_one(event, ctx):
1008
  def _write(cur):
1009
  cur[str(pid)] = row
1010
  return cur
1011
- store.update(_DOCS_KEY, _write, flush='async')
 
 
 
 
 
 
1012
  return True
1013
 
1014
  if kind in ('folder_create', 'folder_rename', 'folder_delete', 'folder_duplicate',
@@ -1028,7 +1075,7 @@ def handle_one(event, ctx):
1028
  def _own_ids(sfc, cur_ws):
1029
  if sfc == 'views':
1030
  return set((cur_ws.get('views') or {}))
1031
- return set(cohort_mod.all_for(uname))
1032
 
1033
  def _mutate(cur_ws):
1034
  folders = _agf.clean_folders(cur_ws.get('folders'))
@@ -1230,22 +1277,33 @@ def handle_one(event, ctx):
1230
  name = str(event.get('name') or '').strip()[:120]
1231
  if not store.available():
1232
  return False
 
 
 
 
 
 
1233
  try:
1234
  if not cohort_id:
1235
  if not name:
1236
  return False
1237
- cohort_id = cohort_mod.create(uname, name, pids)
1238
  else:
1239
- if cohort_id not in cohort_mod.all_for(uname):
1240
  return False # not this user's cohort β€” fail closed, do not create
1241
- cohort_mod.add_members(uname, cohort_id, pids)
1242
  except ValueError as e:
1243
  _tel.error('cohort:add_to_list', e)
1244
  return False
1245
  # True: the Cohort page's list and counts must reflect this, and the toast below only
1246
  # renders on a fresh run.
 
 
 
 
 
1247
  ctx.out.toast = (
1248
- f"Added {len(pids):,} customer{'' if len(pids) == 1 else 's'} to "
1249
  f"{name or 'the list'}.")
1250
  return True
1251
 
 
145
  return ctx.table if ctx.table is not None else cl_mod.TABLE_OPS
146
 
147
 
148
+ def _cohorts(ctx):
149
+ """The COHORT store this ctx operates on β€” `_tops`'s sibling, and here for the same reason.
150
+
151
+ ⭐ WAVE 19 / R9: a cohort belongs to its database. Every cohort verb below used to name
152
+ `cohort_mod` directly, so a list built on the Product surface landed in `customer_cohorts`
153
+ beside somebody's real customer lists β€” with PRODUCT pids in it (CRC32 hashes of SKU codes),
154
+ which the customer page would then try to resolve against partner ids. Wave 16 answered that
155
+ by REFUSING cohorts on other topics (`with_cohorts=False`); R9 says scope-parameterize
156
+ instead. `modules.cohort.scoped` returns the module itself for the customer topic, so the
157
+ customer path is byte-unchanged.
158
+ """
159
+ return cohort_mod.scoped(ctx.scope_key)
160
+
161
+
162
+ def _docs_key(ctx):
163
+ """The DOCUMENTS bucket this ctx operates on β€” `_cohorts`'s sibling (wave 19, item 12's
164
+ silent third case).
165
+
166
+ β›” `_DOCS_KEY` STAYS the module constant with its shipped value: app.py re-imports it for the
167
+ Streamlit docs payload and `verify_seam.py` asserts the two resolve to the same string. This
168
+ resolves the CUSTOMER topic to exactly that constant and gives every other database its own
169
+ bucket, so the pid keys inside one bucket all come from one id space.
170
+ """
171
+ scope = str(getattr(ctx, 'scope_key', '') or 'customer').strip().lower()
172
+ if scope in cohort_mod.LEGACY_SCOPES:
173
+ return _DOCS_KEY
174
+ return f'{scope}_docs'
175
+
176
+
177
  # ------------------------------------------------------------------ the workspace family (X1 amd.)
178
  def table_workspace(ctx, allowed_pids=None, consume_corrections=True):
179
  """Durable Airtable-style view/schema/overlay state, with an honest session fallback.
 
665
  # the SET it is, in the store that owns it; the view record must not grow a second title
666
  # that the read side would then have to arbitrate. Routed rather than duplicated.
667
  if _is_locked_view and store.available():
668
+ _sets = _cohorts(ctx) # R9: the SET lives in this topic's bucket
669
+ _cur = (_sets.all_for(uname).get(view_id) or {}).get('name')
670
  if name and name != _cur:
671
  try:
672
+ _sets.rename(uname, view_id, name)
673
  except ValueError as _e:
674
  _tel.error('cohort:rename-via-view', _e)
675
  view = {'id': view_id, 'name': name,
 
741
  # on the very next render: the row would come back, minus the user's sort and columns,
742
  # which reads as a corruption rather than as a refusal. Own sets only (`all_for`), the
743
  # same wall `cohort_delete` rides.
744
+ if store.available() and view_id in _cohorts(ctx).all_for(uname):
745
+ _cohorts(ctx).delete(uname, view_id)
746
  _tops(ctx).delete_view(uname, view_id)
747
  # True, unlike an ordinary view_delete: the lists payload IS server truth and the
748
  # client cannot know the membership channel changed.
 
935
  # caller's permitted pool β€” the same guard add_to_list rides.
936
  if not store.available():
937
  return False
938
+ sets = _cohorts(ctx) # R9: this DATABASE's lists, never another's
939
  cohort_id = str(event.get('cohortId') or '').strip()[:120]
940
+ if not cohort_id or cohort_id not in sets.all_for(uname):
941
  return False
942
  try:
943
  if kind == 'cohort_rename':
944
  name = str(event.get('name') or '').strip()[:120]
945
  if not name:
946
  return False
947
+ sets.rename(uname, cohort_id, name)
948
  elif kind == 'cohort_delete':
949
+ sets.delete(uname, cohort_id)
950
  else:
951
  raw_pids = event.get('pids')
952
  if not isinstance(raw_pids, list):
 
955
  if not pids:
956
  return False
957
  if kind == 'cohort_add':
958
+ sets.add_members(uname, cohort_id, pids)
959
  else:
960
+ sets.remove_members(uname, cohort_id, pids)
961
  except ValueError as e:
962
  _tel.error('cohort:panel-edit', e)
963
  return False
 
966
  return True
967
 
968
  if kind in ('doc_add', 'doc_delete', 'doc_fetch'):
969
+ # DOCUMENTS on a row (owner item 12, contract C5). Metadata in the store key
970
  # `customer_docs`; the BYTES live at their own path in the tenant dataset, never in a
971
  # JSON blob β€” see core.store.upload_bytes for why that distinction is load-bearing.
972
+ #
973
+ # ⭐ WAVE 19 / R9 β€” item 1's SILENT THIRD CASE, and the one nobody reported because the
974
+ # React shell cannot reach it yet (`payload.docs` is set only by app.py). Both homes are
975
+ # keyed by pid and both were topic-blind: the metadata bucket AND the byte path
976
+ # `docs/<pid>/…`. Two topics' pid spaces overlap by construction (a CRC32 hash lands
977
+ # anywhere an Odoo partner id can), so a product's file could occupy the path of a
978
+ # customer's β€” one upload silently shadowing another tenant-visible document. Per-topic
979
+ # bucket AND per-topic prefix; the customer topic keeps both of its shipped names.
980
  import base64 as _b64c
981
  import re as _re_mod
982
  if not store.available():
983
  return False
984
+ docs_key = _docs_key(ctx)
985
+ docs_dir = 'docs' if docs_key == _DOCS_KEY else f'docs/{docs_key[:-5]}'
986
  pid = event.get('pid')
987
  doc_id = str(event.get('docId') or '').strip()[:80]
988
  # The pid wall is the SAME one every other row-scoped event rides: a caller may only
989
+ # touch rows inside their own permitted pool. Without it, documents would be the
990
  # one surface where a scoped agent could read another book's rows.
991
  if not isinstance(pid, int) or pid not in allowed_pids or not doc_id:
992
  return False
993
+ meta_all = store.get(docs_key) or {}
994
  row = list((meta_all.get(str(pid)) or []))
995
 
996
  if kind == 'doc_add':
 
1010
  if len(row) >= _DOC_MAX_PER_ROW or any(d.get('id') == doc_id for d in row):
1011
  return False
1012
  safe = _re_mod.sub(r'[^A-Za-z0-9._-]', '_', name)[:80] or 'file'
1013
+ path = f'{docs_dir}/{pid}/{doc_id}_{safe}'
1014
  try:
1015
+ store.upload_bytes(path, blob, message=f'doc {doc_id} for {scope_key} {pid}')
1016
  except Exception as _ue:
1017
  _tel.error('docs:upload', _ue)
1018
  return False
 
1049
  def _write(cur):
1050
  cur[str(pid)] = row
1051
  return cur
1052
+ # ⚠ `docs_key`, NOT `_DOCS_KEY`. The read above and the byte path were both made
1053
+ # per-topic and this line was not β€” so a product document's BYTES landed correctly under
1054
+ # `docs/product/…` while its METADATA went into `customer_docs` beside the customer rows,
1055
+ # keyed by a CRC32 hash. Found by `verify_scopes.py`'s own leg on its first run, which is
1056
+ # the argument for asserting the ABSENCE from the legacy bucket and not just the presence
1057
+ # in the new one: every "it saved" check here was green.
1058
+ store.update(docs_key, _write, flush='async')
1059
  return True
1060
 
1061
  if kind in ('folder_create', 'folder_rename', 'folder_delete', 'folder_duplicate',
 
1075
  def _own_ids(sfc, cur_ws):
1076
  if sfc == 'views':
1077
  return set((cur_ws.get('views') or {}))
1078
+ return set(_cohorts(ctx).all_for(uname))
1079
 
1080
  def _mutate(cur_ws):
1081
  folders = _agf.clean_folders(cur_ws.get('folders'))
 
1277
  name = str(event.get('name') or '').strip()[:120]
1278
  if not store.available():
1279
  return False
1280
+ # ⭐ WAVE 19 / R9 β€” THE BUG THIS RULING NAMES. This branch is where a list is BORN, and it
1281
+ # named `cohort_mod` directly: a list created from the Product surface was written into
1282
+ # `customer_cohorts` with CRC32 product pids in it, then rendered on the Customer page as
1283
+ # a list of customers nobody recognised. The set now belongs to the database it was
1284
+ # created on, and `ctx.scope_key` is the only thing that decides which.
1285
+ sets = _cohorts(ctx)
1286
  try:
1287
  if not cohort_id:
1288
  if not name:
1289
  return False
1290
+ cohort_id = sets.create(uname, name, pids)
1291
  else:
1292
+ if cohort_id not in sets.all_for(uname):
1293
  return False # not this user's cohort β€” fail closed, do not create
1294
+ sets.add_members(uname, cohort_id, pids)
1295
  except ValueError as e:
1296
  _tel.error('cohort:add_to_list', e)
1297
  return False
1298
  # True: the Cohort page's list and counts must reflect this, and the toast below only
1299
  # renders on a fresh run.
1300
+ #
1301
+ # ⚠ The NOUN is the TOPIC's, not the literal "customer" this line carried since wave 2.
1302
+ # "Added 12 customers" over a set of SKUs is the surface stating, in words, that the list
1303
+ # went somewhere it did not β€” the user-visible half of the same leak.
1304
+ _noun = sets.noun
1305
  ctx.out.toast = (
1306
+ f"Added {len(pids):,} {_noun}{'' if len(pids) == 1 else 's'} to "
1307
  f"{name or 'the list'}.")
1308
  return True
1309
 
core/platform_admin.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """core/platform_admin.py β€” THE PLATFORM-OPERATOR PREDICATE (wave 19, owner item 13 / ruling R3).
2
+
3
+ There are now TWO kinds of administrator in this product and they must never be confused:
4
+
5
+ * a **tenant admin** (`role: 'admin'`) runs ONE company's workspace β€” its accounts, its
6
+ keychains, its databases. Nurilab's admin is one; Royal's is one. `core.perms.is_admin`
7
+ is that wall and it is scoped to the caller's own tenant everywhere it is used.
8
+ * a **platform admin** operates LOOPABLE ITSELF β€” the cross-tenant view of who our customers
9
+ are, what they are running, and what it costs. That is a different question and it needs a
10
+ different key, because every tenant already has an admin and none of them may see the others.
11
+
12
+ β›” THE DOUBLE LOCK, and why it is two conditions and not one (R3, verbatim: "NEW fail-closed
13
+ `platform_admin` server predicate (tenant-scoped `is_admin` does NOT qualify)"):
14
+
15
+ record flag `platform_admin is True` AND `tenant == 'loopable'`
16
+
17
+ Either half alone is a promotion path we do not want to exist. The flag alone would mean a
18
+ tenant admin who can write user records (Y4's `POST /admin/users` is reachable by every tenant
19
+ admin) could mint themselves a cross-tenant reader inside their OWN company. The tenant alone
20
+ would mean every future account in the `loopable` workspace β€” a designer, a contractor β€” reads
21
+ every customer's operational data by virtue of their email domain. Requiring both means the
22
+ promotion needs a write to a record AND membership of a tenant that no customer's admin can
23
+ create accounts in.
24
+
25
+ FAIL-CLOSED IN THE STRICT SENSE: `is True`, not truthiness. A record carrying the string
26
+ "false", a 0, a "yes", or a partially-read dict is NOT a platform admin. The flag is absent on
27
+ every pre-wave record, which is the correct answer for all of them.
28
+
29
+ ⚠ THE FLAG MUST RIDE `users._public()` OR THIS PREDICATE IS BLIND. `deps._user_for` builds every
30
+ API session from that projection, so a field that lives only on the stored record is invisible
31
+ to every route that asks this question β€” the same rule `core.users` states for `perms`/`perms_v`
32
+ ("the wall travels on this projection or it does not travel"), recurring on a new field. Both
33
+ sides land in the same change, and `verify_api.py`'s W19-ADMIN section drives the predicate
34
+ through a real SESSION rather than through a hand-built dict, so a dropped projection is red.
35
+
36
+ This module deliberately holds NO routes, NO store reads and NO imports of the permission layer:
37
+ it is one question, answerable from the session's own user dict, callable from either host.
38
+ """
39
+
40
+ #: The ONE tenant slug a platform administrator may belong to. A constant rather than an env var
41
+ #: on purpose β€” "which company operates this platform" is not a per-deployment setting, and an
42
+ #: env-var reader here would be one misconfigured container away from admitting another slug.
43
+ PLATFORM_TENANT = 'loopable'
44
+
45
+
46
+ def is_platform_admin(user):
47
+ """True iff `user` is a Loopable platform operator. Fail-closed on anything else.
48
+
49
+ `user` is the PUBLIC session projection (`core.users._public`) or a raw record β€” both carry
50
+ the same two keys, so the predicate answers identically wherever it is asked. None, {}, a
51
+ non-dict, a missing flag or a mismatched tenant are all False, and none of them are an error:
52
+ "not a platform admin" is the answer for almost every session the product will ever serve.
53
+ """
54
+ if not isinstance(user, dict):
55
+ return False
56
+ if user.get('platform_admin') is not True:
57
+ return False
58
+ return str(user.get('tenant') or 'royal-imports').strip().lower() == PLATFORM_TENANT
core/users.py CHANGED
@@ -27,7 +27,7 @@ def _hash(pw, salt):
27
 
28
 
29
  def _record(pw, name, role, bus, active=True, modules='all', agent=None, email=None,
30
- perms=None, tenant='royal-imports'):
31
  salt = secrets.token_hex(16)
32
  rec = {'salt': salt, 'hash': _hash(pw, salt), 'name': name, 'role': role,
33
  'bus': bus, 'active': active, 'modules': modules,
@@ -36,6 +36,12 @@ def _record(pw, name, role, bus, active=True, modules='all', agent=None, email=N
36
  # pre-wave record β€” no migration. Login binds the session to THIS value; the posted
37
  # tenant field can hint but never override it.
38
  'tenant': str(tenant or 'royal-imports').strip().lower()}
 
 
 
 
 
 
39
  if perms is not None:
40
  # Wave 15 C-PERM. A record written WITH perms is migrated by construction β€” the marker
41
  # and the block are set together, here, so no writer can create one without the other.
@@ -100,6 +106,15 @@ def _public(username, u):
100
  # present in three files and is absent in the one that runs.
101
  **({'perms': u['perms']} if isinstance(u.get('perms'), dict) else {}),
102
  **({'perms_v': int(u['perms_v'] or 0)} if u.get('perms_v') else {}),
 
 
 
 
 
 
 
 
 
103
  'epoch': int(u.get('epoch') or 0)}
104
 
105
 
@@ -180,7 +195,7 @@ def verify(username, pw):
180
 
181
 
182
  def create_user(username, pw, name, role='user', bus='all', modules='all',
183
- agent=None, email=None, tenant=None):
184
  """Create β€” or, from app.py's dialog, OVERWRITE β€” an account.
185
 
186
  β›” X3: OVERWRITING AN ACCOUNT MUST NOT RESURRECT ITS OLD SESSIONS. `_record()` builds a fresh
@@ -203,7 +218,14 @@ def create_user(username, pw, name, role='user', bus='all', modules='all',
203
  agent=agent, email=email,
204
  # An overwrite that names no tenant KEEPS the account's company β€” a
205
  # rename must never quietly move a user between tenants.
206
- tenant=(tenant or prior.get('tenant') or 'royal-imports'))
 
 
 
 
 
 
 
207
  if prior:
208
  rec['epoch'] = int(prior.get('epoch') or 0) + 1
209
  reg[username] = rec
@@ -242,6 +264,128 @@ def set_active(username, active):
242
  store.update('users', _set)
243
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  def set_access(username, role=None, bus=None, modules=None, agent=None, email=None,
246
  name=None, perms=None):
247
  """Update access fields. agent/email: pass '' to clear, None to leave unchanged β€”
 
27
 
28
 
29
  def _record(pw, name, role, bus, active=True, modules='all', agent=None, email=None,
30
+ perms=None, tenant='royal-imports', platform_admin=False):
31
  salt = secrets.token_hex(16)
32
  rec = {'salt': salt, 'hash': _hash(pw, salt), 'name': name, 'role': role,
33
  'bus': bus, 'active': active, 'modules': modules,
 
36
  # pre-wave record β€” no migration. Login binds the session to THIS value; the posted
37
  # tenant field can hint but never override it.
38
  'tenant': str(tenant or 'royal-imports').strip().lower()}
39
+ if platform_admin is True:
40
+ # Wave 19 (R3): the PLATFORM-operator flag β€” half of `core.platform_admin`'s double lock
41
+ # (the other half is `tenant == 'loopable'`). Written ONLY for True, so every record that
42
+ # is not deliberately promoted keeps its pre-wave shape and answers False by absence.
43
+ # There is no UI writer and there never should be: it is set by provisioning, on purpose.
44
+ rec['platform_admin'] = True
45
  if perms is not None:
46
  # Wave 15 C-PERM. A record written WITH perms is migrated by construction β€” the marker
47
  # and the block are set together, here, so no writer can create one without the other.
 
106
  # present in three files and is absent in the one that runs.
107
  **({'perms': u['perms']} if isinstance(u.get('perms'), dict) else {}),
108
  **({'perms_v': int(u['perms_v'] or 0)} if u.get('perms_v') else {}),
109
+ # β›” WAVE 19 R3 β€” THE SAME RULE, ON A NEW FIELD. `deps._user_for` builds every API
110
+ # session from this projection, so the platform-admin flag travels here or
111
+ # `core.platform_admin.is_platform_admin(session.user)` is blind and the Loopable
112
+ # admin plane 403s its own operator. Carried ONLY when the record says True, so a
113
+ # session dict for any other account is byte-identical to its pre-wave shape.
114
+ # Not a client leak: `routes_auth._public_user` is a whitelist projection and does
115
+ # not name this key, so it reaches no browser via /login or /me β€” the client's copy
116
+ # is the separate `platformAdmin` bool on GET /settings, which is derived from this.
117
+ **({'platform_admin': True} if u.get('platform_admin') is True else {}),
118
  'epoch': int(u.get('epoch') or 0)}
119
 
120
 
 
195
 
196
 
197
  def create_user(username, pw, name, role='user', bus='all', modules='all',
198
+ agent=None, email=None, tenant=None, platform_admin=None):
199
  """Create β€” or, from app.py's dialog, OVERWRITE β€” an account.
200
 
201
  β›” X3: OVERWRITING AN ACCOUNT MUST NOT RESURRECT ITS OLD SESSIONS. `_record()` builds a fresh
 
218
  agent=agent, email=email,
219
  # An overwrite that names no tenant KEEPS the account's company β€” a
220
  # rename must never quietly move a user between tenants.
221
+ tenant=(tenant or prior.get('tenant') or 'royal-imports'),
222
+ # Wave 19 (R3): CARRIED, for the same reason `epoch` is carried below β€”
223
+ # `_record` builds a FRESH record, so re-running the provisioner (it is
224
+ # documented as idempotent) or saving an account through this function
225
+ # would silently DEMOTE a platform admin and lock the operator out of
226
+ # their own plane. None = leave as it was; True/False = set it deliberately.
227
+ platform_admin=(prior.get('platform_admin') is True
228
+ if platform_admin is None else platform_admin is True))
229
  if prior:
230
  rec['epoch'] = int(prior.get('epoch') or 0) + 1
231
  reg[username] = rec
 
264
  store.update('users', _set)
265
 
266
 
267
+ def set_platform_admin(username, on):
268
+ """Promote/demote a PLATFORM administrator (wave 19, R3) without touching the password.
269
+
270
+ The narrow write, deliberately: `create_user` is the destructive path (fresh salt, fresh
271
+ hash, bumped epoch) and promoting somebody should not sign them out or rotate a credential.
272
+ Cleared by REMOVING the key, so a demoted record goes back to its pre-wave shape rather than
273
+ carrying a `False` that reads as "somebody considered this".
274
+
275
+ ⚠ This is the flag only. It grants nothing on its own β€” `core.platform_admin` also demands
276
+ the `loopable` tenant, and there is no code path anywhere that moves an account between
277
+ tenants, which is what makes the second lock hold.
278
+ """
279
+ username = (username or '').strip().lower()
280
+
281
+ def _set(reg):
282
+ u = reg.get(username)
283
+ if u:
284
+ if on is True:
285
+ u['platform_admin'] = True
286
+ else:
287
+ u.pop('platform_admin', None)
288
+ return reg
289
+ store.update('users', _set)
290
+
291
+
292
+ # ------------------------------------------------------------------ activity stamps (wave 19 R4)
293
+ # "When did this account last sign in, and is anyone actually using it?" β€” the two questions the
294
+ # Loopable admin plane exists to answer and that NOTHING in the product could answer before this
295
+ # wave (there is no login history, no audit log, no request log anywhere).
296
+ #
297
+ # β›” THIS IS THE FIRST HIGH-FREQUENCY WRITER `users.json` HAS EVER HAD, and that bucket also holds
298
+ # every password hash, `active`, `epoch` and the permission blocks. Three rules follow, and the
299
+ # second one is a correctness rule, not a performance one:
300
+ #
301
+ # 1. **In-place mutation of ONE key.** Never `_record()`, never a whole-record replace: a stamp
302
+ # that rebuilt the record would reset the salt/hash (locking the user out) or the epoch
303
+ # (silently un-revoking every cookie ever minted for them). `set_password`'s docstring
304
+ # explains why that class of bug is worth naming out loud.
305
+ #
306
+ # 2. **SYNCHRONOUS FLUSH β€” deliberately NOT the async path, and this reverses my first draft.**
307
+ # `store.update(flush='async')` rebases on the PROCESS CACHE once a key is `_owned`
308
+ # (`core/store.py:284`) and its worker uploads that whole cached blob. For a
309
+ # table-workspace key, written by one process, that is exactly right. For `users` it is a
310
+ # silent-revert machine: tenant #0's Streamlit host writes the SAME file, so an API process
311
+ # holding a cache from an hour ago would, on its next stamp, upload a blob in which a
312
+ # password rotation or a deactivation performed in the other host simply never happened.
313
+ # A telemetry stamp must not be able to resurrect a disabled account. `flush='sync'` does a
314
+ # FRESH strict read inside the store's lock and then uploads, which is the same discipline
315
+ # every other `users` writer already uses.
316
+ #
317
+ # 3. **OFF THE REQUEST THREAD, so rule 2 costs nothing.** A sync commit is a hub round-trip, and
318
+ # neither a sign-in nor a random request an hour later should wait for it. Each stamp runs on
319
+ # a short-lived daemon thread; `flush_stamps()` is how a test or a shutdown waits for them.
320
+ # Everything is fail-silent: a stamp is telemetry and may never turn a good login into a
321
+ # failed one β€” the plane shows an honest "never" instead.
322
+ def _now_iso():
323
+ import datetime as _dt
324
+ return _dt.datetime.now(_dt.timezone.utc).isoformat(timespec='seconds')
325
+
326
+
327
+ #: Live stamp threads, so `flush_stamps()` can join them. Bounded by construction β€” one thread per
328
+ #: stamp, and a stamp is at most one per login plus one per account per hour per process.
329
+ _STAMPS = []
330
+ _STAMPS_LOCK = __import__('threading').Lock()
331
+
332
+
333
+ def _stamp(username, fields):
334
+ """Merge `fields` into ONE account record, on a background thread, with a fresh read."""
335
+ username = (username or '').strip().lower()
336
+ if not username or not fields:
337
+ return None
338
+
339
+ def _set(reg):
340
+ u = reg.get(username)
341
+ if isinstance(u, dict):
342
+ u.update(fields)
343
+ return reg
344
+
345
+ def _work():
346
+ try:
347
+ store.update('users', _set) # sync: fresh strict read + blocking upload
348
+ except Exception:
349
+ pass # a lost stamp is a lost stamp, never an error
350
+ import threading
351
+ t = threading.Thread(target=_work, daemon=True, name=f'user-stamp:{username}')
352
+ with _STAMPS_LOCK:
353
+ _STAMPS[:] = [x for x in _STAMPS if x.is_alive()]
354
+ _STAMPS.append(t)
355
+ t.start()
356
+ return t
357
+
358
+
359
+ def flush_stamps(timeout=10.0):
360
+ """Block until outstanding stamp writes have been applied. For gates and shutdown hooks β€”
361
+ the app never needs it, exactly like `core.store.flush`."""
362
+ with _STAMPS_LOCK:
363
+ pending = list(_STAMPS)
364
+ for t in pending:
365
+ t.join(timeout=timeout)
366
+ return all(not t.is_alive() for t in pending)
367
+
368
+
369
+ def touch_login(username, when=None):
370
+ """Stamp `last_login` (ISO-8601, UTC, OFFSET-BEARING) on a SUCCESSFUL login.
371
+
372
+ `username` must be the RESOLVED account key, not what the person typed: `verify()` accepts an
373
+ email address and resolves it to the registry key, so stamping the typed identifier would
374
+ write a stamp onto a key that does not exist and create a phantom account in the registry.
375
+
376
+ `last_active` rides along β€” signing in IS activity, and setting both here means the plane's
377
+ two columns agree the moment somebody logs in rather than an hour later.
378
+ """
379
+ stamp = when or _now_iso()
380
+ return _stamp(username, {'last_login': stamp, 'last_active': stamp})
381
+
382
+
383
+ def touch_active(username, when=None):
384
+ """Stamp `last_active` β€” "this session did something". Throttled BY THE CALLER (`deps.py`
385
+ holds a process-local last-seen map), so this is not a store round-trip per request."""
386
+ return _stamp(username, {'last_active': when or _now_iso()})
387
+
388
+
389
  def set_access(username, role=None, bus=None, modules=None, agent=None, email=None,
390
  name=None, perms=None):
391
  """Update access fields. agent/email: pass '' to clear, None to leave unchanged β€”
harness/analyst.py CHANGED
@@ -291,7 +291,14 @@ def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX
291
  answer = ("(the model returned an empty answer β€” nothing was computed; "
292
  "please rephrase or ask again)")
293
  import harness.telemetry as _tel
 
 
 
 
 
294
  _tel.log(telemetry_kind, question=question[:200],
 
 
295
  model=model or (available_providers() or [{}])[0].get("name", "auto"),
296
  iterations=i + 1,
297
  tools=[t["tool"] for t in trace],
 
291
  answer = ("(the model returned an empty answer β€” nothing was computed; "
292
  "please rephrase or ask again)")
293
  import harness.telemetry as _tel
294
+ # Wave 19 (R4): ATTRIBUTED. The token count was previously logged against nobody, so
295
+ # "which customer is spending model budget, and who inside it?" had no answer even in
296
+ # principle. Read defensively off `user` because this function is deliberately
297
+ # callable WITHOUT one β€” `harness/evals.py` and `harness/routines.py` run as the
298
+ # system, and telemetry omits both keys for them rather than inventing a subject.
299
  _tel.log(telemetry_kind, question=question[:200],
300
+ user=(user or {}).get("username") if isinstance(user, dict) else None,
301
+ tenant=(user or {}).get("tenant") if isinstance(user, dict) else None,
302
  model=model or (available_providers() or [{}])[0].get("name", "auto"),
303
  iterations=i + 1,
304
  tools=[t["tool"] for t in trace],
harness/telemetry.py CHANGED
@@ -16,12 +16,35 @@ PATH = Path(__file__).resolve().parents[1] / "data" / "store" / "usage.jsonl"
16
  ERR_PATH = PATH.parent / "errors.jsonl"
17
 
18
 
19
- def log(kind, **fields):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  try:
21
  PATH.parent.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
22
  with PATH.open("a", encoding="utf-8") as f:
23
- f.write(json.dumps({"ts": time.strftime("%Y-%m-%d %H:%M:%S"),
24
- "kind": kind, **fields}, default=str) + "\n")
25
  except Exception:
26
  pass
27
 
 
16
  ERR_PATH = PATH.parent / "errors.jsonl"
17
 
18
 
19
+ def log(kind, user=None, tenant=None, **fields):
20
+ """Append one usage event. Never raises.
21
+
22
+ β­’ WAVE 19 (R4): `user` and `tenant` are FIRST-CLASS PARAMETERS, not just two more `**fields`.
23
+ They already worked as free-form fields β€” the point of naming them is that attribution stops
24
+ being a convention each call site remembers or forgets. The Analyst's token line is the first
25
+ caller to pass them (`harness/analyst.py`), which is what makes "who spent these tokens, for
26
+ which customer?" answerable AT ALL: before this wave the log recorded a token count attached
27
+ to nobody.
28
+
29
+ Both are OPTIONAL and omitted from the line when absent, so a system-initiated run (the eval
30
+ ladder, `harness/routines.py` β€” neither runs on behalf of a person) writes exactly the record
31
+ it wrote before. A missing key is honest; `"user": null` would invite a reader to count it.
32
+
33
+ ⚠ HONEST LIMIT β€” this file is CONTAINER-LOCAL JSONL (`data/store/usage.jsonl`, git-ignored,
34
+ lost on a Space restart). Attribution starts accruing now; it is not yet a durable, queryable
35
+ usage ledger, which is why the per-user token PANEL stays deferred (DEBT D-8) rather than
36
+ being built against a log that a redeploy erases.
37
+ """
38
  try:
39
  PATH.parent.mkdir(parents=True, exist_ok=True)
40
+ rec = {"ts": time.strftime("%Y-%m-%d %H:%M:%S"), "kind": kind}
41
+ if user:
42
+ rec["user"] = str(user)
43
+ if tenant:
44
+ rec["tenant"] = str(tenant)
45
+ rec.update(fields)
46
  with PATH.open("a", encoding="utf-8") as f:
47
+ f.write(json.dumps(rec, default=str) + "\n")
 
48
  except Exception:
49
  pass
50
 
modules/cohort.py CHANGED
@@ -20,16 +20,50 @@ Persistence: HF store key `customer_cohorts`, shaped {username: {cohort_id: {...
20
  like the saved views it sits beside, and written through `store.update` (strict
21
  read-modify-write β€” never get+put around a mutation; that is the restart-wipe bug).
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  No validate(): there is no Odoo aggregate to reconcile a hand-picked list against. Its counts
24
  derive from the rows it renders (rule 8b), and the metrics themselves are already validated by
25
  the customers module they come from.
26
  """
27
  import datetime as _dt
 
28
 
29
  import core.store as store
30
 
31
  KEY = 'customer_cohorts'
32
 
 
 
 
 
 
33
  #: A cohort is a list of ids, not a query β€” but ids are cheap and a runaway list would bloat the
34
  #: per-user store blob, which is read on every page render. Generous enough to never bind in
35
  #: practice (the whole book is ~1,550) and small enough to bound the payload.
@@ -37,22 +71,56 @@ MAX_MEMBERS = 5000
37
  MAX_COHORTS = 100
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def _now():
41
  return _dt.datetime.now().strftime('%Y-%m-%d %H:%M')
42
 
43
 
44
- def all_for(username):
45
- """{cohort_id: {name, members, note, created, updated}} for one user.
46
 
47
  Returns {} when the store is unavailable rather than raising: a cohort list that cannot load
48
  should degrade to "no cohorts", never to a broken page.
49
  """
50
  try:
51
- return dict((store.get(KEY) or {}).get(username, {}) or {})
52
  except Exception:
53
  return {}
54
 
55
 
 
 
 
 
 
56
  def _clean_members(raw, allowed_pids=None):
57
  """Ints only, de-duplicated, ORDER PRESERVED, and intersected with what this user may see.
58
 
@@ -76,25 +144,40 @@ def _clean_members(raw, allowed_pids=None):
76
  return out[:MAX_MEMBERS]
77
 
78
 
79
- def visible(username, allowed_pids=None):
80
- """Every cohort, with membership already scoped to what this user may open."""
81
  return {cid: {**c, 'members': _clean_members(c.get('members'), allowed_pids)}
82
- for cid, c in all_for(username).items()}
 
 
 
 
 
83
 
84
 
85
  def new_id(name):
86
- """A stable id from the name plus a suffix, so two cohorts called "Q3 calls" can coexist."""
 
 
 
 
 
 
87
  slug = ''.join(ch if ch.isalnum() else '_' for ch in str(name).lower()).strip('_')[:40]
88
  return f"cohort_{slug or 'list'}_{_dt.datetime.now().strftime('%H%M%S')}"
89
 
90
 
91
- def create(username, name, members=(), note=''):
92
- """Create a cohort and return its id. Raises ValueError on a blank name or when the per-user
93
- cap is reached β€” refusing loudly beats silently dropping somebody's list."""
 
 
 
 
94
  name = str(name or '').strip()[:120]
95
  if not name:
96
  raise ValueError('a cohort needs a name')
97
- existing = all_for(username)
98
  if len(existing) >= MAX_COHORTS:
99
  raise ValueError(f'you already have {MAX_COHORTS} cohorts β€” delete one first')
100
  cid = new_id(name)
@@ -104,11 +187,16 @@ def create(username, name, members=(), note=''):
104
  def _up(data):
105
  data.setdefault(username, {})[cid] = record
106
  return data
107
- store.update(KEY, _up)
108
  return cid
109
 
110
 
111
- def _mutate(username, cohort_id, change):
 
 
 
 
 
112
  def _up(data):
113
  book = data.setdefault(username, {})
114
  c = book.get(cohort_id)
@@ -117,10 +205,10 @@ def _mutate(username, cohort_id, change):
117
  change(c)
118
  c['updated'] = _now()
119
  return data
120
- store.update(KEY, _up)
121
 
122
 
123
- def add_members(username, cohort_id, pids):
124
  """Union new ids into a cohort, PRESERVING the existing order and appending the new ones.
125
 
126
  Additive on purpose: "add to list" from a view can be clicked twice, and the second click
@@ -128,33 +216,54 @@ def add_members(username, cohort_id, pids):
128
  """
129
  def _change(c):
130
  c['members'] = _clean_members(list(c.get('members') or []) + list(pids or []))
131
- _mutate(username, cohort_id, _change)
132
 
133
 
134
- def remove_members(username, cohort_id, pids):
 
 
 
 
 
135
  drop = {int(p) for p in (pids or []) if str(p).lstrip('-').isdigit()}
136
 
137
  def _change(c):
138
  c['members'] = [p for p in _clean_members(c.get('members')) if p not in drop]
139
- _mutate(username, cohort_id, _change)
140
 
141
 
142
- def rename(username, cohort_id, name):
 
 
 
 
143
  name = str(name or '').strip()[:120]
144
  if not name:
145
  raise ValueError('a cohort needs a name')
146
- _mutate(username, cohort_id, lambda c: c.__setitem__('name', name))
 
 
 
 
 
 
 
 
147
 
148
 
149
  def set_note(username, cohort_id, note):
150
- _mutate(username, cohort_id, lambda c: c.__setitem__('note', str(note or '')[:2000]))
151
 
152
 
153
- def delete(username, cohort_id):
154
  def _up(data):
155
  (data.get(username) or {}).pop(cohort_id, None)
156
  return data
157
- store.update(KEY, _up)
 
 
 
 
158
 
159
 
160
  def rows_for(cohort, pool_rows):
@@ -169,3 +278,69 @@ def rows_for(cohort, pool_rows):
169
  members = _clean_members(cohort.get('members'))
170
  rows = [by_pid[p] for p in members if p in by_pid]
171
  return rows, len(members) - len(rows)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  like the saved views it sits beside, and written through `store.update` (strict
21
  read-modify-write β€” never get+put around a mutation; that is the restart-wipe bug).
22
 
23
+ ⭐ WAVE 19 / OWNER RULING R9 β€” A COHORT BELONGS TO ITS DATABASE. "It should stay in Product
24
+ database … for ANY database new/old": until relational features land, database functionalities
25
+ are purely independent. So this module is now SCOPE-PARAMETERIZED rather than restricted β€” one
26
+ bucket per topic (`<scope>_cohorts`), reached through `scoped(scope)`.
27
+
28
+ β›” THE ID SPACES ARE WHY, not tidiness. A cohort stores the TOPIC's row ids: customer pids are
29
+ Odoo partner ids, product pids are CRC32 hashes of the SKU code, a user table's are its own
30
+ row numbers. One shared bucket and a hash collision silently puts a product in somebody's
31
+ customer list β€” the same argument `routes_products` makes about the overlay bucket, and the
32
+ reason wave 16 answered it with `with_cohorts=False` (a refusal) instead of a bucket.
33
+
34
+ β›” THE CUSTOMER TOPIC KEEPS THE LEGACY KEY β€” zero migration. `customer` and `cohort` are ONE
35
+ topic (the Cohort surface is the customer table over hand-curated sets), so both resolve to
36
+ `customer_cohorts` and every shipped list is found exactly where it already lives.
37
+
38
+ β›” `scoped('customer')` RETURNS THIS MODULE, deliberately, so the module-level functions stay
39
+ the customer implementation rather than becoming a second copy of it. Callers that patch
40
+ `modules.cohort.visible` (the gates do) keep working through the facade, and every existing
41
+ positional call site is byte-unaffected.
42
+
43
+ TENANCY, STATED NOT HIDDEN (booked as DEBT, wave 19): this module writes through the MODULE-LEVEL
44
+ `core.store`, i.e. tenant #0's dataset repo β€” the same place `customer_docs` and the customer /
45
+ product table workspaces already live. It is safe rather than correct: the outer key is the
46
+ USERNAME, and `core/users.py`'s registry is ONE global bucket, so a username belongs to exactly
47
+ one tenant and no cross-tenant READ is reachable. What is wrong is RESIDENCY (tenant B's lists
48
+ sit in tenant #0's repo). Fixing it means threading the runtime handle through `EventCtx`, which
49
+ needs `routes_grid._ctx` β€” another session's file this wave.
50
+
51
  No validate(): there is no Odoo aggregate to reconcile a hand-picked list against. Its counts
52
  derive from the rows it renders (rule 8b), and the metrics themselves are already validated by
53
  the customers module they come from.
54
  """
55
  import datetime as _dt
56
+ import sys as _sys
57
 
58
  import core.store as store
59
 
60
  KEY = 'customer_cohorts'
61
 
62
+ #: The scope names that mean THE CUSTOMER BOOK. `cohort` is the customer table over curated sets
63
+ #: β€” the same rows, the same pids, the same lists β€” so it must resolve to the same bucket, and ''
64
+ #: is what an unset `scope_key` looks like. Anything else is another database.
65
+ LEGACY_SCOPES = frozenset({'', 'customer', 'cohort'})
66
+
67
  #: A cohort is a list of ids, not a query β€” but ids are cheap and a runaway list would bloat the
68
  #: per-user store blob, which is read on every page render. Generous enough to never bind in
69
  #: practice (the whole book is ~1,550) and small enough to bound the payload.
 
71
  MAX_COHORTS = 100
72
 
73
 
74
+ def key_for(scope):
75
+ """The store bucket ONE topic's cohorts live in (R9).
76
+
77
+ Customer (and its `cohort` surface) keep `customer_cohorts` β€” the legacy key, so no shipped
78
+ list moves. Every other database gets `<scope>_cohorts`, which for a user table is
79
+ `ut_<slug>_cohorts`: the same naming the table's own workspace bucket already uses
80
+ (`<scope>_table_workspace`), so one database's durable state reads as one family.
81
+ """
82
+ s = str(scope or 'customer').strip().lower()
83
+ return KEY if s in LEGACY_SCOPES else f'{s}_cohorts'
84
+
85
+
86
+ def noun_for(scope):
87
+ """What ONE row of this topic is called β€” the "Added 12 customers to …" toast's noun.
88
+
89
+ A hardcoded "customer" was the visible half of the leak this ruling closes: adding twelve
90
+ SKUs to a product list said "Added 12 customers", which is the surface telling the user the
91
+ wrong thing about where their list went. Unknown topics say "record" rather than guessing a
92
+ label from a slug β€” a user table is called whatever its creator named it, and inventing a
93
+ singular from `ut_supplier_quotes` would be worse than the honest generic.
94
+ """
95
+ s = str(scope or 'customer').strip().lower()
96
+ if s in LEGACY_SCOPES:
97
+ return 'customer'
98
+ if s == 'product':
99
+ return 'product'
100
+ return 'record'
101
+
102
+
103
  def _now():
104
  return _dt.datetime.now().strftime('%Y-%m-%d %H:%M')
105
 
106
 
107
+ def _all_for(key, username):
108
+ """{cohort_id: {name, members, note, created, updated}} for one user, from ONE bucket.
109
 
110
  Returns {} when the store is unavailable rather than raising: a cohort list that cannot load
111
  should degrade to "no cohorts", never to a broken page.
112
  """
113
  try:
114
+ return dict((store.get(key) or {}).get(username, {}) or {})
115
  except Exception:
116
  return {}
117
 
118
 
119
+ def all_for(username):
120
+ """{cohort_id: {...}} for one user on the CUSTOMER book β€” see `_all_for`."""
121
+ return _all_for(KEY, username)
122
+
123
+
124
  def _clean_members(raw, allowed_pids=None):
125
  """Ints only, de-duplicated, ORDER PRESERVED, and intersected with what this user may see.
126
 
 
144
  return out[:MAX_MEMBERS]
145
 
146
 
147
+ def _visible(key, username, allowed_pids=None):
148
+ """Every cohort in ONE bucket, with membership already scoped to what this user may open."""
149
  return {cid: {**c, 'members': _clean_members(c.get('members'), allowed_pids)}
150
+ for cid, c in _all_for(key, username).items()}
151
+
152
+
153
+ def visible(username, allowed_pids=None):
154
+ """Every CUSTOMER cohort, membership scoped to what this user may open."""
155
+ return _visible(KEY, username, allowed_pids)
156
 
157
 
158
  def new_id(name):
159
+ """A stable id from the name plus a suffix, so two cohorts called "Q3 calls" can coexist.
160
+
161
+ ⚠ Topic-FREE on purpose. The id is a handle stored inside the topic's own bucket, and a saved
162
+ view's `cohortLock` names it β€” so encoding the topic in the string would only add a second
163
+ place for the two to disagree. Two databases may each hold a `cohort_q3_calls_101112`; they
164
+ are different objects in different buckets and neither read can reach the other.
165
+ """
166
  slug = ''.join(ch if ch.isalnum() else '_' for ch in str(name).lower()).strip('_')[:40]
167
  return f"cohort_{slug or 'list'}_{_dt.datetime.now().strftime('%H%M%S')}"
168
 
169
 
170
+ def _create(key, username, name, members=(), note=''):
171
+ """Create a cohort in ONE bucket and return its id. Raises ValueError on a blank name or when
172
+ the per-user cap is reached β€” refusing loudly beats silently dropping somebody's list.
173
+
174
+ The cap is PER BUCKET, i.e. per database, which is the honest reading of R9: a hundred
175
+ product lists must not be spent by a hundred customer lists somebody else's page created.
176
+ """
177
  name = str(name or '').strip()[:120]
178
  if not name:
179
  raise ValueError('a cohort needs a name')
180
+ existing = _all_for(key, username)
181
  if len(existing) >= MAX_COHORTS:
182
  raise ValueError(f'you already have {MAX_COHORTS} cohorts β€” delete one first')
183
  cid = new_id(name)
 
187
  def _up(data):
188
  data.setdefault(username, {})[cid] = record
189
  return data
190
+ store.update(key, _up)
191
  return cid
192
 
193
 
194
+ def create(username, name, members=(), note=''):
195
+ """Create a CUSTOMER cohort and return its id β€” see `_create`."""
196
+ return _create(KEY, username, name, members=members, note=note)
197
+
198
+
199
+ def _mutate(key, username, cohort_id, change):
200
  def _up(data):
201
  book = data.setdefault(username, {})
202
  c = book.get(cohort_id)
 
205
  change(c)
206
  c['updated'] = _now()
207
  return data
208
+ store.update(key, _up)
209
 
210
 
211
+ def _add_members(key, username, cohort_id, pids):
212
  """Union new ids into a cohort, PRESERVING the existing order and appending the new ones.
213
 
214
  Additive on purpose: "add to list" from a view can be clicked twice, and the second click
 
216
  """
217
  def _change(c):
218
  c['members'] = _clean_members(list(c.get('members') or []) + list(pids or []))
219
+ _mutate(key, username, cohort_id, _change)
220
 
221
 
222
+ def add_members(username, cohort_id, pids):
223
+ """Union new ids into a CUSTOMER cohort β€” see `_add_members`."""
224
+ _add_members(KEY, username, cohort_id, pids)
225
+
226
+
227
+ def _remove_members(key, username, cohort_id, pids):
228
  drop = {int(p) for p in (pids or []) if str(p).lstrip('-').isdigit()}
229
 
230
  def _change(c):
231
  c['members'] = [p for p in _clean_members(c.get('members')) if p not in drop]
232
+ _mutate(key, username, cohort_id, _change)
233
 
234
 
235
+ def remove_members(username, cohort_id, pids):
236
+ _remove_members(KEY, username, cohort_id, pids)
237
+
238
+
239
+ def _rename(key, username, cohort_id, name):
240
  name = str(name or '').strip()[:120]
241
  if not name:
242
  raise ValueError('a cohort needs a name')
243
+ _mutate(key, username, cohort_id, lambda c: c.__setitem__('name', name))
244
+
245
+
246
+ def rename(username, cohort_id, name):
247
+ _rename(KEY, username, cohort_id, name)
248
+
249
+
250
+ def _set_note(key, username, cohort_id, note):
251
+ _mutate(key, username, cohort_id, lambda c: c.__setitem__('note', str(note or '')[:2000]))
252
 
253
 
254
  def set_note(username, cohort_id, note):
255
+ _set_note(KEY, username, cohort_id, note)
256
 
257
 
258
+ def _delete(key, username, cohort_id):
259
  def _up(data):
260
  (data.get(username) or {}).pop(cohort_id, None)
261
  return data
262
+ store.update(key, _up)
263
+
264
+
265
+ def delete(username, cohort_id):
266
+ _delete(KEY, username, cohort_id)
267
 
268
 
269
  def rows_for(cohort, pool_rows):
 
278
  members = _clean_members(cohort.get('members'))
279
  rows = [by_pid[p] for p in members if p in by_pid]
280
  return rows, len(members) - len(rows)
281
+
282
+
283
+ # ─────────────────────────────────────────────── R9: ONE topic's cohorts, as an object
284
+ class CohortStore:
285
+ """The cohort verbs for ONE non-customer database, closed over its bucket key.
286
+
287
+ Same method names and same argument order as the module functions above, so a caller written
288
+ against `modules.cohort` reads identically whichever it holds β€” which is the point: the write
289
+ handler resolves the store once (`scoped(ctx.scope_key)`) and every branch below it stays the
290
+ code it already was.
291
+ """
292
+
293
+ __slots__ = ('scope', 'key', 'noun')
294
+
295
+ def __init__(self, scope):
296
+ self.scope = str(scope or 'customer').strip().lower()
297
+ self.key = key_for(self.scope)
298
+ self.noun = noun_for(self.scope)
299
+
300
+ def __repr__(self):
301
+ return f'CohortStore({self.scope!r} -> {self.key!r})'
302
+
303
+ def all_for(self, username):
304
+ return _all_for(self.key, username)
305
+
306
+ def visible(self, username, allowed_pids=None):
307
+ return _visible(self.key, username, allowed_pids)
308
+
309
+ def create(self, username, name, members=(), note=''):
310
+ return _create(self.key, username, name, members=members, note=note)
311
+
312
+ def add_members(self, username, cohort_id, pids):
313
+ _add_members(self.key, username, cohort_id, pids)
314
+
315
+ def remove_members(self, username, cohort_id, pids):
316
+ _remove_members(self.key, username, cohort_id, pids)
317
+
318
+ def rename(self, username, cohort_id, name):
319
+ _rename(self.key, username, cohort_id, name)
320
+
321
+ def set_note(self, username, cohort_id, note):
322
+ _set_note(self.key, username, cohort_id, note)
323
+
324
+ def delete(self, username, cohort_id):
325
+ _delete(self.key, username, cohort_id)
326
+
327
+
328
+ def scoped(scope=None):
329
+ """The cohort store for ONE topic β€” THE resolution point (R9).
330
+
331
+ β›” Returns THIS MODULE for the customer topic, not a `CohortStore(KEY)`. Two reasons, and both
332
+ are about not creating a second implementation of the shipped behaviour:
333
+ 1. the module-level functions ARE the customer store, so the legacy path keeps executing
334
+ exactly the code the gates measure β€” no wrapper to drift from;
335
+ 2. tests patch `modules.cohort.visible` (verify_grid_events' folder legs do), and a facade
336
+ that returned a bound object would silently ignore the patch, leaving a gate green over
337
+ code it is no longer exercising.
338
+ """
339
+ if str(scope or 'customer').strip().lower() in LEGACY_SCOPES:
340
+ return _sys.modules[__name__]
341
+ return CohortStore(scope)
342
+
343
+
344
+ #: What ONE row of the customer topic is called β€” the module facade's answer to `CohortStore.noun`,
345
+ #: so `scoped(x).noun` reads the same whichever object `x` resolved to.
346
+ noun = 'customer'