fsanyoto commited on
Commit
043da5c
·
verified ·
1 Parent(s): 98c8696

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "502ea41c1",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "0586be259",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 502ea41c1
 
1
+ 0586be259
api/agent_card.py CHANGED
@@ -4,8 +4,8 @@ import re
4
  from urllib.parse import urlsplit
5
 
6
 
7
- _HOSTS = {"runloopable.com", "www.runloopable.com", "fsanyoto-loopable.hf.space",
8
- "fsanyoto-runloopable.hf.space"}
9
  _LOCAL = {"localhost", "127.0.0.1", "::1"}
10
 
11
 
@@ -33,8 +33,7 @@ def _trusted_origin(base_url: str) -> str:
33
  origin = _origin(base_url)
34
  parsed = urlsplit(origin)
35
  trusted = {f"https://{host}" for host in _HOSTS}
36
- for key in ("APP_BASE_URL", "AIOS_PUBLIC_BASE"):
37
- configured = os.environ.get(key)
38
  if configured:
39
  try:
40
  trusted.add(_origin(configured))
 
4
  from urllib.parse import urlsplit
5
 
6
 
7
+ # A Space's own address arrives through APP_BASE_URL / AIOS_PUBLIC_BASE, which every deploy sets.
8
+ _HOSTS = {"runloopable.com", "www.runloopable.com"}
9
  _LOCAL = {"localhost", "127.0.0.1", "::1"}
10
 
11
 
 
33
  origin = _origin(base_url)
34
  parsed = urlsplit(origin)
35
  trusted = {f"https://{host}" for host in _HOSTS}
36
+ for configured in (os.environ.get("APP_BASE_URL"), os.environ.get("AIOS_PUBLIC_BASE")):
 
37
  if configured:
38
  try:
39
  trusted.add(_origin(configured))
api/assistant_open_items.py CHANGED
@@ -75,8 +75,11 @@ def open_items(session, args):
75
  candidates = [row for row in rows if not row.get("request_id") and ticket_tools._status(row) == "Open"]
76
  # Tickets stores comma-joined audience names; the common wall expects a detached list.
77
  normalized = [{**row, "audience": sorted(tickets._stored_audience(row))} for row in candidates]
 
 
78
  allowed = perm_scope.apply_row_scope(
79
- normalized, session.user, database, table["fields"], st=session.runtime)
 
80
  assigned = [row for row in allowed if username in tickets._names(row.get("assigned_to"))]
81
  assigned_ids = {row["id"] for row in assigned}
82
  for row in allowed:
 
75
  candidates = [row for row in rows if not row.get("request_id") and ticket_tools._status(row) == "Open"]
76
  # Tickets stores comma-joined audience names; the common wall expects a detached list.
77
  normalized = [{**row, "audience": sorted(tickets._stored_audience(row))} for row in candidates]
78
+ # The request reader keeps attribution and masks source text (_read_item), so it asks for
79
+ # the audience and row walls without the generic door's source recheck (S73-T49).
80
  allowed = perm_scope.apply_row_scope(
81
+ normalized, session.user, database, table["fields"], st=session.runtime,
82
+ recheck_sources=False)
83
  assigned = [row for row in allowed if username in tickets._names(row.get("assigned_to"))]
84
  assigned_ids = {row["id"] for row in assigned}
85
  for row in allowed:
api/assistant_write_preview.py CHANGED
@@ -151,10 +151,11 @@ def lines(preview, name, args, session):
151
  if name in {"sheet_create_workbook", "sheet_add_tab", "sheet_delete_tab", "view_delete", "query_view_delete", "app_delete"}:
152
  continue
153
  label = path[-1].replace("_", " ").capitalize()
154
- if "cells" in path:
 
155
  index = path.index("cells")
156
  label = "Cell " + path[index + 1] + (" " + path[-1] if len(path) > index + 2 else "")
157
- elif "rows" in path:
158
  index = path.index("rows")
159
  label = "Record " + path[index + 1] + (" " + label.lower() if len(path) > index + 2 else "")
160
  elif "rules" in path:
 
151
  if name in {"sheet_create_workbook", "sheet_add_tab", "sheet_delete_tab", "view_delete", "query_view_delete", "app_delete"}:
152
  continue
153
  label = path[-1].replace("_", " ").capitalize()
154
+ # A container name is a record or cell address only when an id follows it.
155
+ if "cells" in path[:-1]:
156
  index = path.index("cells")
157
  label = "Cell " + path[index + 1] + (" " + path[-1] if len(path) > index + 2 else "")
158
+ elif "rows" in path[:-1]:
159
  index = path.index("rows")
160
  label = "Record " + path[index + 1] + (" " + label.lower() if len(path) > index + 2 else "")
161
  elif "rules" in path:
api/intelligence_store.py CHANGED
@@ -8,10 +8,16 @@ import importlib
8
  import difflib
9
  import json
10
  import re
11
- import secrets
12
 
13
  import yaml
14
 
 
 
 
 
 
 
 
15
 
16
  STORE_KEY = "intelligence_files"
17
  TEMPLATE_USAGE_KEY = "intelligence_template_usage"
@@ -673,8 +679,11 @@ def propose_file(ctx, path, body, *, expected_version=None):
673
  return write_file(ctx, path, body, expected_version=expected_version, require_approval=True)
674
 
675
 
676
- def read_file(session, path, *, version=0):
677
- """Read an authorized current or historical file and persist usage outside its versions."""
 
 
 
678
  _authorize(session)
679
  path = normalize_path(path)
680
  if type(version) is not int or version < 0:
@@ -693,6 +702,8 @@ def read_file(session, path, *, version=0):
693
  return record, entry
694
 
695
  record, entry = readable(_files(session))
 
 
696
  if path in _template_catalog() and path not in _document(session.runtime.get(STORE_KEY)):
697
  saved = {}
698
 
@@ -879,7 +890,7 @@ def _new_proposal(session, record, text, metadata, identity, proposal_id):
879
  proposal = {"id": proposal_id, "path": path, "title": metadata["title"], "body": text,
880
  "metadata": metadata, "baseVersion": current, "baseCreated": head["created"] if head else None,
881
  "baseMetadata": deepcopy(head["metadata"]) if head else None,
882
- "status": "pending", "created": datetime.now(timezone.utc).isoformat(timespec="microseconds"),
883
  **identity, "policy": policy, "approvedBy": [],
884
  "diff": "\n".join(difflib.unified_diff(before.splitlines(), text.splitlines(), lineterm="",
885
  fromfile=f"{path} (version {current})", tofile=f"{path} (proposed)")) + "\n"}
@@ -926,7 +937,7 @@ def _notify_proposal(session, proposal):
926
 
927
  def _entry(text, metadata, version, identity, **extra):
928
  return {"version": version, "body": text, "metadata": deepcopy(metadata), **identity,
929
- "created": datetime.now(timezone.utc).isoformat(timespec="microseconds"),
930
  "bytes": len(text.encode("utf-8")), **extra}
931
 
932
 
@@ -1114,7 +1125,7 @@ def write_file(caller, path, body, *, author_kind="user", expected_version=None,
1114
  raise IntelligenceError("bad_version", "expectedVersion must be a whole number of zero or more.")
1115
  text, metadata = prepare_markdown(body, session.uname)
1116
  saved = {}
1117
- proposal_id = "ip_" + secrets.token_hex(12)
1118
 
1119
  def append(raw):
1120
  saved.clear()
@@ -1144,7 +1155,7 @@ def write_file(caller, path, body, *, author_kind="user", expected_version=None,
1144
  _check_file_capacity(session, files, path)
1145
  if len(prior) >= MAX_VERSIONS:
1146
  raise IntelligenceError("too_many_versions", "This file already has 100 versions. Save further work in a new file.", 409)
1147
- now = datetime.now(timezone.utc).isoformat(timespec="microseconds")
1148
  record = dict(old) if old else {"path": path, "created": now,
1149
  "createdBy": session.uname, "createdKind": identity["authorKind"], "versions": []}
1150
  if "personal_scope" in metadata:
 
8
  import difflib
9
  import json
10
  import re
 
11
 
12
  import yaml
13
 
14
+ from core import write_execution
15
+
16
+
17
+ def _now():
18
+ """A confirmed write replays its preview's instant; every other write reads this module's clock."""
19
+ return write_execution.utcnow() if write_execution.active() else datetime.now(timezone.utc)
20
+
21
 
22
  STORE_KEY = "intelligence_files"
23
  TEMPLATE_USAGE_KEY = "intelligence_template_usage"
 
679
  return write_file(ctx, path, body, expected_version=expected_version, require_approval=True)
680
 
681
 
682
+ def read_file(session, path, *, version=0, record_use=True):
683
+ """Read an authorized current or historical file and persist usage outside its versions.
684
+
685
+ `record_use=False` only rechecks admission and returns the file: a confirmed write's receipt
686
+ check runs on a read-only runtime and must write nothing (PRD A4)."""
687
  _authorize(session)
688
  path = normalize_path(path)
689
  if type(version) is not int or version < 0:
 
702
  return record, entry
703
 
704
  record, entry = readable(_files(session))
705
+ if not record_use:
706
+ return _file(record, entry, session=session)
707
  if path in _template_catalog() and path not in _document(session.runtime.get(STORE_KEY)):
708
  saved = {}
709
 
 
890
  proposal = {"id": proposal_id, "path": path, "title": metadata["title"], "body": text,
891
  "metadata": metadata, "baseVersion": current, "baseCreated": head["created"] if head else None,
892
  "baseMetadata": deepcopy(head["metadata"]) if head else None,
893
+ "status": "pending", "created": _now().isoformat(timespec="microseconds"),
894
  **identity, "policy": policy, "approvedBy": [],
895
  "diff": "\n".join(difflib.unified_diff(before.splitlines(), text.splitlines(), lineterm="",
896
  fromfile=f"{path} (version {current})", tofile=f"{path} (proposed)")) + "\n"}
 
937
 
938
  def _entry(text, metadata, version, identity, **extra):
939
  return {"version": version, "body": text, "metadata": deepcopy(metadata), **identity,
940
+ "created": _now().isoformat(timespec="microseconds"),
941
  "bytes": len(text.encode("utf-8")), **extra}
942
 
943
 
 
1125
  raise IntelligenceError("bad_version", "expectedVersion must be a whole number of zero or more.")
1126
  text, metadata = prepare_markdown(body, session.uname)
1127
  saved = {}
1128
+ proposal_id = "ip_" + write_execution.new_id()[:24]
1129
 
1130
  def append(raw):
1131
  saved.clear()
 
1155
  _check_file_capacity(session, files, path)
1156
  if len(prior) >= MAX_VERSIONS:
1157
  raise IntelligenceError("too_many_versions", "This file already has 100 versions. Save further work in a new file.", 409)
1158
+ now = _now().isoformat(timespec="microseconds")
1159
  record = dict(old) if old else {"path": path, "created": now,
1160
  "createdBy": session.uname, "createdKind": identity["authorKind"], "versions": []}
1161
  if "personal_scope" in metadata:
api/routes_agent_harness.py CHANGED
@@ -53,6 +53,28 @@ def _intelligence_error(exc):
53
  return refusal
54
 
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  @router.get("/intelligence/files", dependencies=[Depends(_intelligence_no_cache)])
57
  def get_intelligence_files(path: str = "", section: str = "", version: int = 0,
58
  q: str = "", folder: str = "", offset: int = 0, limit: int = 100,
 
53
  return refusal
54
 
55
 
56
+ def activity_read_policy(session: Session, object):
57
+ """Admit file activity through the current Intelligence record without recording file usage."""
58
+ import intelligence_store as intelligence
59
+
60
+ if not isinstance(session, Session) or not isinstance(object, dict):
61
+ return False
62
+ if set(object) != {"file", "id"}:
63
+ return False
64
+ try:
65
+ if not session.tenant or getattr(session.runtime, "key", None) != session.tenant:
66
+ return False
67
+ path = intelligence.normalize_path(object["file"])
68
+ if path != object["file"] or object["id"] != path:
69
+ return False
70
+ intelligence._authorize(session)
71
+ record = intelligence._readable_record(session, intelligence._files(session), path)
72
+ return intelligence._personal_record_readable(session, record) is True
73
+ except Exception:
74
+ # Missing, malformed or unavailable current records never authorize retained activity.
75
+ return False
76
+
77
+
78
  @router.get("/intelligence/files", dependencies=[Depends(_intelligence_no_cache)])
79
  def get_intelligence_files(path: str = "", section: str = "", version: int = 0,
80
  q: str = "", folder: str = "", offset: int = 0, limit: int = 100,
api/routes_external.py CHANGED
@@ -336,6 +336,28 @@ def _database_preview_documents(session, before, after):
336
  return documents
337
 
338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  def _public_preview_documents(session, documents):
340
  """Show readable workbook values without copying private caches or write history."""
341
  from core import user_tables
@@ -1002,14 +1024,20 @@ def _resolve_external_scope(
1002
  status = ({database: {"permitted": True, "answerable": True}
1003
  for database in databases} if strict_schema and databases is not None else
1004
  deps.assistant_source_status(session, databases=databases))
1005
- if databases is None or "ut_activity" in databases:
 
 
1006
  try:
1007
  _native_activity_scope(session, mode="schema")
1008
- status["ut_activity"] = {"permitted": True, "answerable": True, "visible": True}
1009
  except HTTPException as exc:
1010
  info = exc.detail.get("error", {}) if isinstance(exc.detail, dict) else {}
1011
- status["ut_activity"] = {"permitted": False, "answerable": False,
1012
- "visible": False, "reason": info.get("message", "")}
 
 
 
 
 
1013
  definitions = None
1014
 
1015
  def fallback_label(database: str) -> str:
@@ -3572,7 +3600,11 @@ def _preview_external_write(session, name, arguments, *, issue_token=True, execu
3572
  current_revision = copy.deepcopy(plan.get("revision") or {})
3573
  else:
3574
  documents = preview_runtime.changed()
3575
- diff, truncated = _diff_documents(_public_preview_documents(session, documents))
 
 
 
 
3576
  warnings = (["The preview diff reached its display cap; split this change."]
3577
  if truncated else [])
3578
  affected = _affected_for(name, normalised, diff, result)
 
336
  return documents
337
 
338
 
339
+ def _request_preview_documents(session, request_id, documents):
340
+ """Project a request change through current participation, credential and source access."""
341
+ import tickets
342
+ from tool_groups import requests
343
+
344
+ pair = {}
345
+ for side in ("before", "after"):
346
+ snapshot = _PreviewRuntime(session.runtime)
347
+ for key, changed in documents.items():
348
+ snapshot.put(key, changed[side])
349
+ reader = Session(session.tenant, session.user, session.claims, _ReceiptRuntime(snapshot))
350
+ ctx = _tool_context(reader, preview=True)
351
+ name, _label, _connection, databases = requests._identity(ctx)
352
+ task = tickets.get_request_attribution(
353
+ reader.runtime, request_id, name,
354
+ source_check=lambda source: requests._source_scope(ctx, source, databases))
355
+ if not task["sourceVisible"]:
356
+ raise PermissionError("You cannot see the source data this request needs.")
357
+ pair[side] = {task["id"]: task}
358
+ return {"requests": pair}
359
+
360
+
361
  def _public_preview_documents(session, documents):
362
  """Show readable workbook values without copying private caches or write history."""
363
  from core import user_tables
 
1024
  status = ({database: {"permitted": True, "answerable": True}
1025
  for database in databases} if strict_schema and databases is not None else
1026
  deps.assistant_source_status(session, databases=databases))
1027
+ if "ut_activity" in status and not strict_schema:
1028
+ # The Assistant's row decides permission. The native door only narrows it: an access
1029
+ # refusal drops the source, and an unavailable backend leaves it listed but unanswerable.
1030
  try:
1031
  _native_activity_scope(session, mode="schema")
 
1032
  except HTTPException as exc:
1033
  info = exc.detail.get("error", {}) if isinstance(exc.detail, dict) else {}
1034
+ row = dict(status["ut_activity"])
1035
+ if exc.status_code in (401, 403, 404):
1036
+ row.update(permitted=False, answerable=False, visible=False)
1037
+ else:
1038
+ row["answerable"] = False
1039
+ row["reason"] = info.get("message") or row.get("reason") or ""
1040
+ status["ut_activity"] = row
1041
  definitions = None
1042
 
1043
  def fallback_label(database: str) -> str:
 
3600
  current_revision = copy.deepcopy(plan.get("revision") or {})
3601
  else:
3602
  documents = preview_runtime.changed()
3603
+ if name == "requests" and normalised.get("action") in {"answer", "complete"}:
3604
+ projected = _request_preview_documents(session, normalised["arguments"]["id"], documents)
3605
+ else:
3606
+ projected = _public_preview_documents(session, documents)
3607
+ diff, truncated = _diff_documents(projected)
3608
  warnings = (["The preview diff reached its display cap; split this change."]
3609
  if truncated else [])
3610
  affected = _affected_for(name, normalised, diff, result)
api/routes_nav.py CHANGED
@@ -724,6 +724,11 @@ def nav(session: Session = Depends(require_session)):
724
  # marked as such. `degraded` is that mark; the shell renders it in the affected slot.
725
  _degraded.append("databases")
726
  pass
 
 
 
 
 
727
  if not pages:
728
  if tmods != "all":
729
  # A provisioned tenant with no modules and no databases YET is a legitimate empty
@@ -803,7 +808,8 @@ def nav(session: Session = Depends(require_session)):
803
  _creator = str((_ut_defs.get(key) or {}).get("createdBy") or "")
804
  _mine = bool(session.admin or (_creator and _creator == session.uname))
805
  p["manage"] = _mine
806
- p["canDelete"] = _mine
 
807
  # ⭐ WAVE 27 item 3 (contract C9) — A LOCKED DATABASE SAYS SO IN THE RAIL.
808
  #
809
  # "Locked" is the owner's item-4 vocabulary and it means exactly ONE thing (DESIGN.md
 
724
  # marked as such. `degraded` is that mark; the shell renders it in the affected slot.
725
  _degraded.append("databases")
726
  pass
727
+ # S73-T64: every viewer is admitted to the activity log, which then gates each event. Alone it
728
+ # would turn "no access" and "no databases yet" into a rail holding one always-empty database,
729
+ # so it rides only beside another page this session may open.
730
+ if pages and all(str(p.get("key", "")) == "ut_activity" for p in pages):
731
+ pages = []
732
  if not pages:
733
  if tmods != "all":
734
  # A provisioned tenant with no modules and no databases YET is a legitimate empty
 
808
  _creator = str((_ut_defs.get(key) or {}).get("createdBy") or "")
809
  _mine = bool(session.admin or (_creator and _creator == session.uname))
810
  p["manage"] = _mine
811
+ # S73-T64: user_tables refuses to delete the activity log, so the rail offers no Delete.
812
+ p["canDelete"] = _mine and key != "ut_activity"
813
  # ⭐ WAVE 27 item 3 (contract C9) — A LOCKED DATABASE SAYS SO IN THE RAIL.
814
  #
815
  # "Locked" is the owner's item-4 vocabulary and it means exactly ONE thing (DESIGN.md
api/routes_query.py CHANGED
@@ -2206,6 +2206,15 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
2206
  refused = _refusal("/query/chat", cause, cause_detail, session)
2207
  result.update({"status": "refused", "code": refused["code"], "cause": cause,
2208
  "error": {"code": refused["code"], "message": refused["message"]}})
 
 
 
 
 
 
 
 
 
2209
  return result
2210
 
2211
 
 
2206
  refused = _refusal("/query/chat", cause, cause_detail, session)
2207
  result.update({"status": "refused", "code": refused["code"], "cause": cause,
2208
  "error": {"code": refused["code"], "message": refused["message"]}})
2209
+ result["producingSources"] = None
2210
+ if (not cause and not draft_card and not turn["pendingDelete"]
2211
+ and not agent_runtime._HELD.get() and not getattr(session.runtime, "preview_only", False)):
2212
+ # The producing context has reset; the admitted turn still owns its source proof.
2213
+ agent_runtime._seed_sources(session, turn)
2214
+ # An empty source selection or tool audit does not prove a source-free answer.
2215
+ if sources:
2216
+ agent_runtime._merge_sources(session, turn, sources)
2217
+ result["producingSources"] = agent_runtime._turn_sources(turn)
2218
  return result
2219
 
2220
 
api/routes_tables.py CHANGED
@@ -514,16 +514,21 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
514
  from core import activity_log, perm_scope
515
 
516
  key = activity_log.DATABASE_KEY
517
- own = _defn_or_refuse(session, key, defs_only=True, scope_applied=True)
518
- own_grid = _compute_ut_assembly(session, key, with_rows=False, fields_only=True)
 
 
 
519
  own_keys = {f['key'] for f in own_grid['fields']}
520
  query = [object, by, since, until]
521
  position = _activity_cursor(session, query, token=cursor) if cursor else None
522
  if type(limit) is not int or not 1 <= limit <= activity_log.MAX_PAGE:
523
- raise err(400, 'bad_activity_limit', 'Choose between 1 and 1000 events.')
524
  if type(scan_limit) is not int or not limit <= scan_limit <= activity_log.MAX_SCAN:
525
  raise err(400, 'bad_activity_limit', 'The activity scan limit is invalid.')
526
  contexts = {}
 
 
527
  partners = {}
528
  connected = set()
529
 
@@ -534,9 +539,12 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
534
  g = own_grid
535
  elif database.startswith('ut_'):
536
  # The complete assembly supplies the hidden-field closure after workspace merge.
537
- definition = _defn_or_refuse(session, database, defs_only=True, scope_applied=True)
 
538
  windowed = not _ut().materialises(database, st=session.runtime, defn=definition)
539
- g = _compute_ut_assembly(session, database, with_rows=False, fields_only=windowed)
 
 
540
  if windowed:
541
  connected.add(database)
542
  elif database in ('customer_data', 'product_data'):
@@ -546,6 +554,9 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
546
  else:
547
  g = None
548
  contexts[database] = g
 
 
 
549
  except HTTPException as exc:
550
  if exc.status_code not in (403, 404, 409):
551
  raise
@@ -581,11 +592,12 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
581
  return source(str(obj['database'])) is not None if 'database' in obj else partner(obj)
582
 
583
  records = []
 
584
  # One raw page counts every event against the scan budget, including refused sources.
585
  try:
586
  raw = activity_log.read(session.runtime, can_read_object=can_read_object,
587
  object=object, by=by, since=since, until=until,
588
- cursor=position, limit=min(1000, scan_limit), scan_limit=scan_limit)
589
  position = raw['next_cursor']
590
  # Resolve only this page's source ids through the connected grid's existing SQL wall.
591
  # Whole-pool admission would hide all record events once a source exceeds its window.
@@ -602,17 +614,17 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
602
  if exc.status_code not in (403, 404, 409):
603
  raise
604
  contexts[database]['pids'] = frozenset()
605
- for index, event in enumerate(raw['records']):
606
- if not perm_scope.apply_row_scope([event], session.user, key, own['fields'],
607
- st=session.runtime, defn=own):
608
- continue
609
  obj = event['object']
610
  clean = None
611
  if can_read_object(obj):
612
  if 'database' in obj:
613
  database = str(obj['database'])
614
  g = source(database)
615
- visible = {f['key'] for f in g['fields']}
616
  changes = event.get('changes') or {}
617
  if event['kind'] == 'field':
618
  field_key = str(obj['id'])
@@ -624,10 +636,10 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
624
  corpus = list(g['fields']) + [previous]
625
  hidden = _ut_hidden(session, database, corpus, st=session.runtime)
626
  if field_key not in hidden and field_key not in g.get('hidden', ()):
627
- visible.add(field_key)
628
  admitted = field_key in visible
629
  else:
630
- admitted = str(obj['id']) in {str(pid) for pid in g['pids']}
631
  # Unscoped readers may see deletions. A scoped missing row fails closed.
632
  if (not admitted and database.startswith('ut_') and database != key
633
  and database not in connected
@@ -636,7 +648,8 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
636
  session.user, database, st=session.runtime, defn=g['defn'])):
637
  admitted = True
638
  if admitted:
639
- clean = {name: pair for name, pair in changes.items() if name in visible}
 
640
  if changes and not clean:
641
  clean = None
642
  elif 'app' in obj:
@@ -645,14 +658,18 @@ def query_activity(session: Session, *, object=None, by=None, since=None, until=
645
  else:
646
  clean = event['changes']
647
  if clean is not None:
648
- safe = dict(event, changes=clean)
 
 
 
649
  # Byte counts describe the permitted payload, never a hidden value's length.
650
- safe['changes_original_bytes'] = len(json.dumps(clean, ensure_ascii=False).encode())
651
- safe['changes_truncated'] = bool(event['changes_truncated'] and clean)
652
- records.append({name: value for name, value in safe.items()
653
- if name in own_keys or name in ('id', 'pid')})
 
654
  if len(records) >= limit:
655
- if index < len(raw['records']) - 1:
656
  position = [event['occurred_at'], event['id']]
657
  break
658
  except ValueError as exc:
@@ -1586,7 +1603,8 @@ def ut_assembly(session: Session, table_key: str, storage_key: str = "",
1586
 
1587
  def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = "",
1588
  consume_corrections: bool = False, with_rows: bool = True, st=None,
1589
- *, fields_only: bool = False, needed=None):
 
1590
  """The user-table mirror of `grid_assembly` / `product_assembly` — SAME g-dict keys, so
1591
  `/workspace` and the events route consume any of the three interchangeably.
1592
 
@@ -1710,8 +1728,9 @@ def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = ""
1710
  _usage_source = getattr(ctx, "workspace_document", None)
1711
  if not isinstance(_usage_source, dict):
1712
  _usage_source = ops.st
1713
- _usage = _field_usage(session, table_key, fields, defn,
1714
- _usage_source, ops.table_key, st=st)
 
1715
  except Exception: # noqa: BLE001
1716
  _usage = {}
1717
  if _usage:
@@ -1775,7 +1794,7 @@ def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = ""
1775
  # lookback catalogue AND the cells to go with it; every other user table still serves `[]`,
1776
  # which is the honest answer for a hand-typed one rather than a descope.
1777
  today = _recurrence_today
1778
- measures = ut_measures(table_key, session)
1779
  derived = aios_grid.cohort_cells(lists) if not fields_only else {}
1780
  materialized_fields = fields if needed is None else [f for f in fields if f.get("key") in needed]
1781
  for _pid, _cells in (_ut_measure_cells(table_key, materialized_fields, pids, today, measures,
@@ -1833,7 +1852,7 @@ def _ut_measure_err(tag, e):
1833
  pass
1834
 
1835
 
1836
- def ut_measures(table_key, session):
1837
  """The lookback-measure OFFER for a user database FOR THIS SESSION, or `[]` — W37-T12 /
1838
  owner item 4 (R1), narrowed by the metrics capability in W38-T19.
1839
 
@@ -1859,6 +1878,9 @@ def ut_measures(table_key, session):
1859
  import core.perm_scope as perm_scope
1860
  if not perm_scope.may_metrics(session.user, table_key):
1861
  return []
 
 
 
1862
  try:
1863
  from harness import semantic as sem
1864
  topic = sem.topic_for_grid(table_key)
 
514
  from core import activity_log, perm_scope
515
 
516
  key = activity_log.DATABASE_KEY
517
+ # Borrow definitions and grants for this call only; each cursor request rebuilds them.
518
+ context_store = _table_lend(session.runtime, key, defs_only=True)
519
+ own = _defn_or_refuse(session, key, st=context_store, defs_only=True, scope_applied=True)
520
+ own_grid = _compute_ut_assembly(session, key, st=context_store, with_rows=False, fields_only=True,
521
+ include_usage=False, include_measures=False)
522
  own_keys = {f['key'] for f in own_grid['fields']}
523
  query = [object, by, since, until]
524
  position = _activity_cursor(session, query, token=cursor) if cursor else None
525
  if type(limit) is not int or not 1 <= limit <= activity_log.MAX_PAGE:
526
+ raise err(400, 'bad_activity_limit', f'Choose between 1 and {activity_log.MAX_PAGE} events.')
527
  if type(scan_limit) is not int or not limit <= scan_limit <= activity_log.MAX_SCAN:
528
  raise err(400, 'bad_activity_limit', 'The activity scan limit is invalid.')
529
  contexts = {}
530
+ source_keys = {}
531
+ source_pids = {}
532
  partners = {}
533
  connected = set()
534
 
 
539
  g = own_grid
540
  elif database.startswith('ut_'):
541
  # The complete assembly supplies the hidden-field closure after workspace merge.
542
+ definition = _defn_or_refuse(session, database, st=context_store,
543
+ defs_only=True, scope_applied=True)
544
  windowed = not _ut().materialises(database, st=session.runtime, defn=definition)
545
+ g = _compute_ut_assembly(session, database, st=context_store,
546
+ with_rows=False, fields_only=windowed,
547
+ include_usage=False, include_measures=False)
548
  if windowed:
549
  connected.add(database)
550
  elif database in ('customer_data', 'product_data'):
 
554
  else:
555
  g = None
556
  contexts[database] = g
557
+ if g is not None:
558
+ source_keys[database] = frozenset(f['key'] for f in g['fields'])
559
+ source_pids[database] = frozenset(str(pid) for pid in g['pids'])
560
  except HTTPException as exc:
561
  if exc.status_code not in (403, 404, 409):
562
  raise
 
592
  return source(str(obj['database'])) is not None if 'database' in obj else partner(obj)
593
 
594
  records = []
595
+ encode_changes = json.JSONEncoder(ensure_ascii=False).encode
596
  # One raw page counts every event against the scan budget, including refused sources.
597
  try:
598
  raw = activity_log.read(session.runtime, can_read_object=can_read_object,
599
  object=object, by=by, since=since, until=until,
600
+ cursor=position, limit=min(max(1000, limit), scan_limit), scan_limit=scan_limit)
601
  position = raw['next_cursor']
602
  # Resolve only this page's source ids through the connected grid's existing SQL wall.
603
  # Whole-pool admission would hide all record events once a source exceeds its window.
 
614
  if exc.status_code not in (403, 404, 409):
615
  raise
616
  contexts[database]['pids'] = frozenset()
617
+ source_pids[database] = frozenset(str(pid) for pid in contexts[database]['pids'])
618
+ scoped = perm_scope.apply_row_scope(raw['records'], session.user, key, own['fields'],
619
+ st=session.runtime, defn=own)
620
+ for event in scoped:
621
  obj = event['object']
622
  clean = None
623
  if can_read_object(obj):
624
  if 'database' in obj:
625
  database = str(obj['database'])
626
  g = source(database)
627
+ visible = source_keys[database]
628
  changes = event.get('changes') or {}
629
  if event['kind'] == 'field':
630
  field_key = str(obj['id'])
 
636
  corpus = list(g['fields']) + [previous]
637
  hidden = _ut_hidden(session, database, corpus, st=session.runtime)
638
  if field_key not in hidden and field_key not in g.get('hidden', ()):
639
+ visible = visible | {field_key}
640
  admitted = field_key in visible
641
  else:
642
+ admitted = str(obj['id']) in source_pids[database]
643
  # Unscoped readers may see deletions. A scoped missing row fails closed.
644
  if (not admitted and database.startswith('ut_') and database != key
645
  and database not in connected
 
648
  session.user, database, st=session.runtime, defn=g['defn'])):
649
  admitted = True
650
  if admitted:
651
+ clean = (changes if changes.keys() <= visible else
652
+ {name: pair for name, pair in changes.items() if name in visible})
653
  if changes and not clean:
654
  clean = None
655
  elif 'app' in obj:
 
658
  else:
659
  clean = event['changes']
660
  if clean is not None:
661
+ safe = {name: value for name, value in event.items()
662
+ if name in own_keys or name in ('id', 'pid')}
663
+ if 'changes' in safe:
664
+ safe['changes'] = clean
665
  # Byte counts describe the permitted payload, never a hidden value's length.
666
+ if 'changes_original_bytes' in safe:
667
+ safe['changes_original_bytes'] = len(encode_changes(clean).encode())
668
+ if 'changes_truncated' in safe:
669
+ safe['changes_truncated'] = bool(event['changes_truncated'] and clean)
670
+ records.append(safe)
671
  if len(records) >= limit:
672
+ if event is not raw['records'][-1]:
673
  position = [event['occurred_at'], event['id']]
674
  break
675
  except ValueError as exc:
 
1603
 
1604
  def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = "",
1605
  consume_corrections: bool = False, with_rows: bool = True, st=None,
1606
+ *, fields_only: bool = False, needed=None, include_usage: bool = True,
1607
+ include_measures: bool = True):
1608
  """The user-table mirror of `grid_assembly` / `product_assembly` — SAME g-dict keys, so
1609
  `/workspace` and the events route consume any of the three interchangeably.
1610
 
 
1728
  _usage_source = getattr(ctx, "workspace_document", None)
1729
  if not isinstance(_usage_source, dict):
1730
  _usage_source = ops.st
1731
+ # Activity admission needs the complete field wall, without field-manager usage counts.
1732
+ _usage = (_field_usage(session, table_key, fields, defn,
1733
+ _usage_source, ops.table_key, st=st) if include_usage else {})
1734
  except Exception: # noqa: BLE001
1735
  _usage = {}
1736
  if _usage:
 
1794
  # lookback catalogue AND the cells to go with it; every other user table still serves `[]`,
1795
  # which is the honest answer for a hand-typed one rather than a descope.
1796
  today = _recurrence_today
1797
+ measures = ut_measures(table_key, session, include_offer=include_measures)
1798
  derived = aios_grid.cohort_cells(lists) if not fields_only else {}
1799
  materialized_fields = fields if needed is None else [f for f in fields if f.get("key") in needed]
1800
  for _pid, _cells in (_ut_measure_cells(table_key, materialized_fields, pids, today, measures,
 
1852
  pass
1853
 
1854
 
1855
+ def ut_measures(table_key, session, *, include_offer=True):
1856
  """The lookback-measure OFFER for a user database FOR THIS SESSION, or `[]` — W37-T12 /
1857
  owner item 4 (R1), narrowed by the metrics capability in W38-T19.
1858
 
 
1878
  import core.perm_scope as perm_scope
1879
  if not perm_scope.may_metrics(session.user, table_key):
1880
  return []
1881
+ # Activity uses the field and row walls, without the metric picker's catalogue.
1882
+ if not include_offer:
1883
+ return []
1884
  try:
1885
  from harness import semantic as sem
1886
  topic = sem.topic_for_grid(table_key)
platform/core/activity_log.py CHANGED
@@ -12,12 +12,13 @@ OBJECT_TYPES = frozenset(('database', 'workbook', 'file', 'app'))
12
  CHANGES_MAX_BYTES = 4096
13
  RETENTION_MONTHS = 13
14
  PRUNE_BATCH = 250
15
- MAX_PAGE = 1000
16
  MAX_SCAN = 10000
17
  TABLE_NAME = 'activity_events'
18
  _COLUMNS = ('id', 'occurred_at', 'kind', 'object_type', 'object_key', 'object_id',
19
  'actor', 'via', 'on_behalf_of', 'changes', 'changes_truncated',
20
  'changes_original_bytes')
 
21
 
22
 
23
  def _json(value):
@@ -156,17 +157,22 @@ def _backend(rt):
156
  return adapter
157
 
158
 
159
- def _event(values):
160
- row = dict(zip(_COLUMNS, values))
161
- obj_id = row['object_id']
162
- changes = row['changes']
163
- return {'id': int(row['id']), 'pid': int(row['id']),
164
- 'occurred_at': _time(row['occurred_at']).isoformat(), 'kind': row['kind'],
165
- 'object': {row['object_type']: row['object_key'], 'id': json.loads(obj_id)},
166
- 'by': row['actor'], 'via': row['via'], 'on_behalf_of': row['on_behalf_of'],
167
- 'changes': json.loads(changes) if isinstance(changes, str) else changes,
168
- 'changes_truncated': bool(row['changes_truncated']),
169
- 'changes_original_bytes': row['changes_original_bytes']}
 
 
 
 
 
170
 
171
 
172
  def append(rt, *, kind, object, by, via=None, on_behalf_of=None, changes=None):
@@ -214,9 +220,10 @@ def read(rt, *, can_read_object, object=None, by=None, since=None, until=None,
214
  backend = _backend(rt)
215
  rows, scanned, exhausted = [], 0, False
216
  while scanned < scan_limit and len(rows) < limit:
 
217
  batch = backend.page(target=target, actor=actor, since=since.isoformat(),
218
  until=until.isoformat(), before=before,
219
- limit=min(256, scan_limit - scanned))
220
  if not batch:
221
  exhausted = True
222
  break
@@ -228,10 +235,22 @@ def read(rt, *, can_read_object, object=None, by=None, since=None, until=None,
228
  rows.append(event)
229
  if len(rows) >= limit or scanned >= scan_limit:
230
  break
 
 
 
 
231
  # The application must wrap this internal position in its session-bound opaque cursor.
232
  return {'records': rows, 'next_cursor': None if exhausted else before}
233
 
234
 
 
 
 
 
 
 
 
 
235
  class PgActivityStore:
236
  """Indexed activity storage inside the bound PgStore schema, with guarded scratch measurement."""
237
 
@@ -325,15 +344,42 @@ class PgActivityStore:
325
  args += list(before)
326
  return ' AND '.join(clauses), args
327
 
328
- def page(self, *, target, actor, since, until, before, limit):
 
329
  where, args = self._where(target=target, actor=actor, since=since, until=until, before=before)
330
- with self._connection() as con:
331
- if not self._exists(con):
332
- return []
333
- values = con.execute(f'SELECT {", ".join(_COLUMNS)} FROM {self.table} WHERE {where} '
334
- 'ORDER BY occurred_at DESC, id DESC LIMIT %s',
335
- (*args, limit)).fetchall()
336
- return [_event(row) for row in values]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
  def storage_stats(self):
339
  with self._connection() as con:
 
12
  CHANGES_MAX_BYTES = 4096
13
  RETENTION_MONTHS = 13
14
  PRUNE_BATCH = 250
15
+ MAX_PAGE = 10000
16
  MAX_SCAN = 10000
17
  TABLE_NAME = 'activity_events'
18
  _COLUMNS = ('id', 'occurred_at', 'kind', 'object_type', 'object_key', 'object_id',
19
  'actor', 'via', 'on_behalf_of', 'changes', 'changes_truncated',
20
  'changes_original_bytes')
21
+ _decode_json = json.JSONDecoder().decode
22
 
23
 
24
  def _json(value):
 
157
  return adapter
158
 
159
 
160
+ def _event(values, *, decoded_json=None):
161
+ (identity, occurred_at, kind, object_type, object_key, obj_id, actor, via,
162
+ on_behalf_of, changes, truncated, original_bytes) = values
163
+ identity = int(identity)
164
+ if decoded_json is None:
165
+ obj_id = _decode_json(obj_id)
166
+ changes = _decode_json(changes) if isinstance(changes, str) else changes
167
+ else:
168
+ obj_id, changes = decoded_json
169
+ return {'id': identity, 'pid': identity,
170
+ 'occurred_at': _time(occurred_at).isoformat(), 'kind': kind,
171
+ 'object': {object_type: object_key, 'id': obj_id},
172
+ 'by': actor, 'via': via, 'on_behalf_of': on_behalf_of,
173
+ 'changes': changes,
174
+ 'changes_truncated': bool(truncated),
175
+ 'changes_original_bytes': original_bytes}
176
 
177
 
178
  def append(rt, *, kind, object, by, via=None, on_behalf_of=None, changes=None):
 
220
  backend = _backend(rt)
221
  rows, scanned, exhausted = [], 0, False
222
  while scanned < scan_limit and len(rows) < limit:
223
+ batch_limit = min(max(256, limit), scan_limit - scanned)
224
  batch = backend.page(target=target, actor=actor, since=since.isoformat(),
225
  until=until.isoformat(), before=before,
226
+ limit=batch_limit)
227
  if not batch:
228
  exhausted = True
229
  break
 
235
  rows.append(event)
236
  if len(rows) >= limit or scanned >= scan_limit:
237
  break
238
+ if event is batch[-1] and (len(batch) < batch_limit
239
+ or getattr(batch, 'has_more', None) is False):
240
+ exhausted = True
241
+ break
242
  # The application must wrap this internal position in its session-bound opaque cursor.
243
  return {'records': rows, 'next_cursor': None if exhausted else before}
244
 
245
 
246
+ class EventPage(list):
247
+ """Carry storage exhaustion without exposing or consuming the next event."""
248
+
249
+ def __init__(self, events=(), *, has_more=False):
250
+ super().__init__(events)
251
+ self.has_more = has_more
252
+
253
+
254
  class PgActivityStore:
255
  """Indexed activity storage inside the bound PgStore schema, with guarded scratch measurement."""
256
 
 
344
  args += list(before)
345
  return ' AND '.join(clauses), args
346
 
347
+ def page_query(self, *, target, actor, since, until, before, limit):
348
+ """Fetch bounded event values and one indexed existence bit from the same snapshot."""
349
  where, args = self._where(target=target, actor=actor, since=since, until=until, before=before)
350
+ columns = ', '.join('CAST(changes AS TEXT) AS changes' if col == 'changes' else col
351
+ for col in _COLUMNS)
352
+ # Only the full page's last row probes the next indexed position, without loading its values.
353
+ sql = ('SELECT page.*, CASE WHEN row_number() OVER (ORDER BY occurred_at DESC, id DESC) = %s '
354
+ f'THEN EXISTS (SELECT 1 FROM {self.table} WHERE {where} '
355
+ 'AND (occurred_at, id) < (page.occurred_at, page.id)) ELSE NULL END AS has_more '
356
+ f'FROM (SELECT {columns} FROM {self.table} WHERE {where} '
357
+ 'ORDER BY occurred_at DESC, id DESC LIMIT %s) page '
358
+ 'ORDER BY occurred_at DESC, id DESC')
359
+ return sql, (limit, *args, *args, limit)
360
+
361
+ def page(self, *, target, actor, since, until, before, limit):
362
+ sql, args = self.page_query(target=target, actor=actor, since=since, until=until,
363
+ before=before, limit=limit)
364
+ try:
365
+ with self._connection() as con:
366
+ values = con.execute(sql, args).fetchall()
367
+ except Exception as exc:
368
+ # Only PostgreSQL's undefined-table state means no activity; other failures propagate.
369
+ if getattr(exc, 'sqlstate', None) != '42P01':
370
+ raise
371
+ return EventPage()
372
+ events = EventPage(has_more=bool(values and values[-1][-1]))
373
+ # Bound temporary JSON text while sharing immutable keys within each decoded batch.
374
+ for start in range(0, len(values), 256):
375
+ batch = values[start:start + 256]
376
+ decoded = _decode_json('[' + ','.join(part for row in batch
377
+ for part in (row[5], row[9])) + ']')
378
+ if len(decoded) != 2 * len(batch):
379
+ raise ValueError('Activity JSON batch does not match its rows.')
380
+ for row, obj_id, changes in zip(batch, decoded[::2], decoded[1::2]):
381
+ events.append(_event(row[:-1], decoded_json=(obj_id, changes)))
382
+ return events
383
 
384
  def storage_stats(self):
385
  with self._connection() as con:
platform/core/external_oauth.py CHANGED
@@ -659,6 +659,8 @@ def _live_permission_scope(user: dict, st) -> tuple[str, object]:
659
  not isinstance(key, str) or not isinstance(value, dict)
660
  for key, value in definitions.items()):
661
  raise ExternalOAuthAuthError(AUTH_ERROR)
 
 
662
  grants = st.get(shares.SHARES_KEY, fresh=True)
663
  if grants is None:
664
  grants = {}
 
659
  not isinstance(key, str) or not isinstance(value, dict)
660
  for key, value in definitions.items()):
661
  raise ExternalOAuthAuthError(AUTH_ERROR)
662
+ # The native activity database has no stored definition; admit it as every other door does.
663
+ definitions = user_tables._with_activity(definitions)
664
  grants = st.get(shares.SHARES_KEY, fresh=True)
665
  if grants is None:
666
  grants = {}
platform/core/perm_scope.py CHANGED
@@ -1238,7 +1238,7 @@ def _row_audience_field(table_key, st=None, defn=None):
1238
  return ''
1239
 
1240
 
1241
- def _apply_audience_scope(rows, user, module, fields, st=None, defn=None):
1242
  """C16 recipient membership is exact and composes with the permanent wall by AND."""
1243
  source = list(rows or ())
1244
  audience = _row_audience_field(module, st=st, defn=defn)
@@ -1261,7 +1261,7 @@ def _apply_audience_scope(rows, user, module, fields, st=None, defn=None):
1261
  admitted = [row for row in source if isinstance(row, dict)
1262
  and any(isinstance(recipient, str) and recipient == username
1263
  for recipient in recipients(row))]
1264
- if not tickets:
1265
  return admitted
1266
  # S73-T49: a stored recipient list is not current access. A request row quotes its source,
1267
  # so it reaches a reader only while that reader still passes the source's own walls.
@@ -1312,13 +1312,14 @@ def _ticket_source_admits(row, user, module, source_rows, memo, st):
1312
  return False
1313
 
1314
 
1315
- def apply_audience_scope(rows, user, module, fields, st=None, defn=None):
1316
  """C16 alone: the recipient list for a door that admits a whole table without a row wall.
1317
 
1318
  An administrator's grantless Assistant read is that door: no permanent filter applies, but
1319
  the audience still binds every reader, admins included. Undeclared tables return their rows.
1320
  """
1321
- return _apply_audience_scope(rows, user, module, fields, st=st, defn=defn)
 
1322
 
1323
 
1324
  def audience_declared(table_key, st=None, defn=None):
@@ -1337,7 +1338,7 @@ def _audience_source_stamp(st, table_key):
1337
  return {'field': field, 'revision': revision}
1338
 
1339
 
1340
- def apply_row_scope(rows, user, module, fields, ctx=None, st=None, defn=None):
1341
  """The rows this account may receive: `filter_eval.permits` over the permanent filter.
1342
 
1343
  C16's table-declared audience is applied first, including for admins. ``defn`` lends the
@@ -1361,7 +1362,10 @@ def apply_row_scope(rows, user, module, fields, ctx=None, st=None, defn=None):
1361
  `allowed_pids`' own docstring exists to close.
1362
  """
1363
  # The recipient list binds every reader, including admins, before the ordinary row wall.
1364
- rows = _apply_audience_scope(rows, user, module, fields, st=st, defn=defn)
 
 
 
1365
  if perms.is_admin(user):
1366
  return list(rows or ())
1367
  e = entry(user, module)
 
1238
  return ''
1239
 
1240
 
1241
+ def _apply_audience_scope(rows, user, module, fields, st=None, defn=None, recheck_sources=True):
1242
  """C16 recipient membership is exact and composes with the permanent wall by AND."""
1243
  source = list(rows or ())
1244
  audience = _row_audience_field(module, st=st, defn=defn)
 
1261
  admitted = [row for row in source if isinstance(row, dict)
1262
  and any(isinstance(recipient, str) and recipient == username
1263
  for recipient in recipients(row))]
1264
+ if not tickets or not recheck_sources:
1265
  return admitted
1266
  # S73-T49: a stored recipient list is not current access. A request row quotes its source,
1267
  # so it reaches a reader only while that reader still passes the source's own walls.
 
1312
  return False
1313
 
1314
 
1315
+ def apply_audience_scope(rows, user, module, fields, st=None, defn=None, recheck_sources=True):
1316
  """C16 alone: the recipient list for a door that admits a whole table without a row wall.
1317
 
1318
  An administrator's grantless Assistant read is that door: no permanent filter applies, but
1319
  the audience still binds every reader, admins included. Undeclared tables return their rows.
1320
  """
1321
+ return _apply_audience_scope(rows, user, module, fields, st=st, defn=defn,
1322
+ recheck_sources=recheck_sources)
1323
 
1324
 
1325
  def audience_declared(table_key, st=None, defn=None):
 
1338
  return {'field': field, 'revision': revision}
1339
 
1340
 
1341
+ def apply_row_scope(rows, user, module, fields, ctx=None, st=None, defn=None, recheck_sources=True):
1342
  """The rows this account may receive: `filter_eval.permits` over the permanent filter.
1343
 
1344
  C16's table-declared audience is applied first, including for admins. ``defn`` lends the
 
1362
  `allowed_pids`' own docstring exists to close.
1363
  """
1364
  # The recipient list binds every reader, including admins, before the ordinary row wall.
1365
+ # S73-T49: a request row reaches the generic door only while its source is readable. A
1366
+ # reader that masks source values itself (the request tools) opts out.
1367
+ rows = _apply_audience_scope(rows, user, module, fields, st=st, defn=defn,
1368
+ recheck_sources=recheck_sources)
1369
  if perms.is_admin(user):
1370
  return list(rows or ())
1371
  e = entry(user, module)
platform/core/write_execution.py CHANGED
@@ -25,6 +25,11 @@ def replay(metadata):
25
  _execution.reset(token)
26
 
27
 
 
 
 
 
 
28
  def new_id():
29
  state = _execution.get()
30
  if state is None:
 
25
  _execution.reset(token)
26
 
27
 
28
+ def active():
29
+ """Is a confirmed write being replayed in this context?"""
30
+ return _execution.get() is not None
31
+
32
+
33
  def new_id():
34
  state = _execution.get()
35
  if state is None:
platform/harness/datastore.py CHANGED
@@ -1944,6 +1944,9 @@ def _already(con, key, rec):
1944
 
1945
 
1946
  def sync_all(entities=None, max_batches=200, log=print):
 
 
 
1947
  # ⭐ D-10. `{}` rather than a dict of paused phases, and the caller decides why that matters:
1948
  # `api/main.py:354` loops up to 12 times until `all(phase == "live")`, and `all()` over an
1949
  # empty dict is True — so a paused store costs ONE pass instead of twelve rounds of the same
@@ -1957,7 +1960,6 @@ def sync_all(entities=None, max_batches=200, log=print):
1957
  raise RuntimeError("Odoo saved mirror was refused; repair store access and restart before syncing")
1958
  out = {}
1959
  from harness import mirror_store
1960
- selected = list(ENTITIES) if entities is None else list(entities)
1961
  publication = (mirror_store.sync_mirror("odoo", rt.key, rt, report=out, log=log, expected_tables=selected)
1962
  if rt is not None else nullcontext())
1963
  with publication:
 
1944
 
1945
 
1946
  def sync_all(entities=None, max_batches=200, log=print):
1947
+ selected = list(ENTITIES) if entities is None else list(entities)
1948
+ if entities is not None and not selected:
1949
+ return {}
1950
  # ⭐ D-10. `{}` rather than a dict of paused phases, and the caller decides why that matters:
1951
  # `api/main.py:354` loops up to 12 times until `all(phase == "live")`, and `all()` over an
1952
  # empty dict is True — so a paused store costs ONE pass instead of twelve rounds of the same
 
1960
  raise RuntimeError("Odoo saved mirror was refused; repair store access and restart before syncing")
1961
  out = {}
1962
  from harness import mirror_store
 
1963
  publication = (mirror_store.sync_mirror("odoo", rt.key, rt, report=out, log=log, expected_tables=selected)
1964
  if rt is not None else nullcontext())
1965
  with publication:
platform/harness/mirror_store.py CHANGED
@@ -75,8 +75,8 @@ def connected_sources(rt):
75
  sources = []
76
  source = rt.odoo_source()
77
  if source is not None and (getattr(source, "_creds", None) or (
78
- rt.key == "royal-imports" and all(os.environ.get(key) for key in
79
- ("ODOO_URL", "ODOO_DB", "ODOO_USER", "ODOO_API_KEY")))):
80
  sources.append("odoo")
81
  if amazon_store.credential(rt.key, rt=rt):
82
  sources.append("amazon")
 
75
  sources = []
76
  source = rt.odoo_source()
77
  if source is not None and (getattr(source, "_creds", None) or (
78
+ rt.key == "royal-imports" and all((os.environ.get("ODOO_URL"), os.environ.get("ODOO_DB"),
79
+ os.environ.get("ODOO_USER"), os.environ.get("ODOO_API_KEY"))))):
80
  sources.append("odoo")
81
  if amazon_store.credential(rt.key, rt=rt):
82
  sources.append("amazon")
platform/model/knowledge/odoo.yml CHANGED
@@ -164,6 +164,7 @@ databases:
164
  status: [payment_state, move_type]
165
  joins:
166
  - {database: ut_odoo_vendors, from: vendor_id, to: vendor_id}
 
167
  traps:
168
  - id: vendor_refunds
169
  text: "move_type in_refund rows are vendor refunds. Net them against bills or exclude them on purpose."
@@ -297,6 +298,22 @@ databases:
297
  - id: order_currency
298
  text: "Amounts are in the order's own currency field. Do not add amounts across currencies."
299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  ut_odoo_shipments:
301
  label: Odoo shipments
302
  row: "One delivery (stock.picking) for a sale order."
 
164
  status: [payment_state, move_type]
165
  joins:
166
  - {database: ut_odoo_vendors, from: vendor_id, to: vendor_id}
167
+ - {database: ut_odoo_pickings, from: landed_pickings, to: odoo_id}
168
  traps:
169
  - id: vendor_refunds
170
  text: "move_type in_refund rows are vendor refunds. Net them against bills or exclude them on purpose."
 
298
  - id: order_currency
299
  text: "Amounts are in the order's own currency field. Do not add amounts across currencies."
300
 
301
+ ut_odoo_pickings:
302
+ label: Odoo pickings
303
+ row: "One receipt or delivery (stock.picking) that a landed cost ties to a vendor bill."
304
+ fields:
305
+ money: []
306
+ quantity: []
307
+ date: [scheduled_date, done_date]
308
+ status: [state, direction]
309
+ joins:
310
+ - {database: ut_odoo_bills, from: odoo_id, to: landed_pickings}
311
+ traps:
312
+ - id: landed_cost_links_only
313
+ text: "A picking reaches a bill only through a landed cost. A bill with no landed cost has an empty link because Odoo holds none."
314
+ - id: picking_direction
315
+ text: "direction is incoming for receipts and outgoing for deliveries. Filter it before counting either."
316
+
317
  ut_odoo_shipments:
318
  label: Odoo shipments
319
  row: "One delivery (stock.picking) for a sale order."
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- a475204110686ba04c812ebec235ad927a3d771c400b451d7f17dd26e9f3ba58
 
1
+ 73efa05511e649ddca6bdd09ff5c5c0b56a74796eff8e022e71e55473982f664
web/src/assistant/NoticeCard.tsx CHANGED
@@ -57,7 +57,10 @@ const OUTCOME_LINE = { approved: "Done", declined: "Not now" } as const;
57
  /** Reads a C6 payload with narrow guards. Returns null for a feed notice. */
58
  export function readInboxNotice(payload: AssistantLogTurn["payload"]): InboxNotice | null {
59
  const row = record(payload);
60
- const type = INBOX_TYPES.find((kind) => kind === (row.type || row.kind));
 
 
 
61
  if (!payload || !type) return null;
62
  const from = payload.sender;
63
  const sender = (typeof from === "object" && from ? text(from.name) || text(from.username) : text(from))
 
57
  /** Reads a C6 payload with narrow guards. Returns null for a feed notice. */
58
  export function readInboxNotice(payload: AssistantLogTurn["payload"]): InboxNotice | null {
59
  const row = record(payload);
60
+ // A C4 task names its kind beside a `from` object. A feed notice also carries `kind` ("share"),
61
+ // and reading that as an inbox request drops the feed card's Open link.
62
+ const task = typeof row.from === "object" && row.from !== null;
63
+ const type = INBOX_TYPES.find((kind) => kind === (row.type || (task ? row.kind : undefined)));
64
  if (!payload || !type) return null;
65
  const from = payload.sender;
66
  const sender = (typeof from === "object" && from ? text(from.name) || text(from.username) : text(from))
web/wiring_rows/s73_combine.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Consumer contracts for the six uncovered SDLC 73 component mounts."""
2
+
3
+ ROWS = [
4
+ ("S73 combine grid activity reads the mounted database",
5
+ "customer-grid/GridActivity.tsx",
6
+ r"export function GridActivity\([\s\S]*?"
7
+ r"fetch\(`\$\{API_V1\}/tables/\$\{encodeURIComponent\(database\)\}/activity\?\$\{query\}`, \{\s*"
8
+ r"credentials: CREDENTIALS, signal: controller\.signal",
9
+ "customer-grid/CustomerGrid.tsx",
10
+ r"!embedded && !isQueryPreview && <GridActivity\b(?:(?!/>)[\s\S])*?key=\{scope\}"
11
+ r'(?:(?!/>)[\s\S])*?database=\{scope === "customer" \|\| scope === "cohort"'
12
+ r' \? "customer_data" : scope === "product" \? "product_data" : scope\}'),
13
+ ("S73 combine file view reads the selected path",
14
+ "intelligence/FileView.tsx",
15
+ r"export default function FileView\([\s\S]*?api\.readFile\(path, abort\.signal\)",
16
+ "intelligence/IntelligencePage.tsx",
17
+ r"<FileView\b(?:(?!/>)[\s\S])*?key=\{path\}"
18
+ r"(?:(?!/>)[\s\S])*?path=\{path\}(?:(?!/>)[\s\S])*?api=\{api\}"
19
+ r"(?:(?!/>)[\s\S])*?initialHistory=\{initialHistory\}"
20
+ r"(?:(?!/>)[\s\S])*?onChanged=\{\(\) => setRetry\(\(value\) => value \+ 1\)\}"
21
+ r'(?:(?!/>)[\s\S])*?onClose=\{\(\) => setPath\(""\)\}'),
22
+ ("S73 combine history restores the open file",
23
+ "intelligence/History.tsx",
24
+ r"export default function History\([\s\S]*?api\.history\(path, version, abort\.signal\)",
25
+ "intelligence/FileView.tsx",
26
+ r"<History\b(?:(?!/>)[\s\S])*?path=\{path\}(?:(?!/>)[\s\S])*?api=\{api\}"
27
+ r"(?:(?!/>)[\s\S])*?revision=\{file\?\.version \|\| 0\}"
28
+ r"(?:(?!/>)[\s\S])*?onBusy=\{\(busy\) => \{\s*restoring\.current = busy; setRestoreBusy\(busy\);\s*\}\}"
29
+ r"(?:(?!/>)[\s\S])*?onRestored=\{acceptFile\}"),
30
+ ("S73 combine insights reads through the page API",
31
+ "intelligence/Insights.tsx",
32
+ r"export default function Insights\([\s\S]*?api\.insights\(abort\.signal\)",
33
+ "intelligence/IntelligencePage.tsx",
34
+ r'view === "insights" \? <Insights\b(?:(?!/>)[\s\S])*?api=\{api\}'),
35
+ ("S73 combine prompt view renders resolved tools and file text",
36
+ "intelligence/PromptView.tsx",
37
+ r"export default function PromptView\([\s\S]*?\{children\}[\s\S]*?tools\.map\(\(tool\) =>",
38
+ "intelligence/FileView.tsx",
39
+ r'<PromptView\b(?:(?!>)[\s\S])*?tools=\{file\.resolvedTools \|\| \[\]\}>'
40
+ r"\s*<FileMarkdown\b(?:(?!/>)[\s\S])*?body=\{file\.body\}\s*/>\s*</PromptView>"),
41
+ ("S73 combine proposals applies approved files to the drawer",
42
+ "intelligence/Proposals.tsx",
43
+ r"export default function Proposals\([\s\S]*?api\.listProposals\(path, abort\.signal\)",
44
+ "intelligence/FileView.tsx",
45
+ r"<Proposals\b(?:(?!/>)[\s\S])*?key=\{path\}"
46
+ r"(?:(?!/>)[\s\S])*?path=\{path\}(?:(?!/>)[\s\S])*?api=\{api\}"
47
+ r"(?:(?!/>)[\s\S])*?onApproved=\{acceptFile\}"
48
+ r"(?:(?!/>)[\s\S])*?onLoaded=\{onProposalsLoaded\}"),
49
+ ]