diff --git a/RELEASES.json b/RELEASES.json
index c4c2d8111bf25d283e45b6f59a0d785780ebd1e6..503a9e87ebb36767fe2beffe777b0d65442f0b03 100644
--- a/RELEASES.json
+++ b/RELEASES.json
@@ -1,4 +1,4 @@
{
- "current": "f627f4817",
+ "current": "63d6a0ce4",
"releases": []
}
\ No newline at end of file
diff --git a/VERSION b/VERSION
index bc359f0206b4ef6769ff33249e004c5c36cb7d9b..f9fd02c65d537d9274eade3914bd4025c7c014af 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-f627f4817
+63d6a0ce4
diff --git a/api/agent_directory.py b/api/agent_directory.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c0c0bfed8369cf509b8eace17c8c08ff3b47cc3
--- /dev/null
+++ b/api/agent_directory.py
@@ -0,0 +1,288 @@
+"""The workspace directory tool: the people of the caller's own workspace and their access.
+
+R84: the list never crosses tenants. `users._tenant_accounts` is the one tenant wall.
+R92: each entry carries role, modules, databases, row limits and hidden fields.
+R108(c): a field or database the CALLER cannot see is never named.
+Every entry is a whitelist projection: no password hash, salt, MFA secret, recovery code,
+session epoch, phone, email or avatar leaves this module.
+"""
+import logging
+
+from core import perm_scope, perms, users
+
+_LOG = logging.getLogger(__name__)
+
+HIDDEN_FIELD = "a hidden field"
+LIMITED = "Limited by your access"
+REFUSAL = "The directory of your workspace could not be read. Try again in a moment."
+NOT_FOUND = "No one by that name uses Loopable in your workspace."
+
+# Shell.tsx opens these workspace modules for every signed-in account.
+_WORKSPACE_MODULES = ("Sheet", "Data", "App")
+
+_OPS = {
+ "eq": "is", "neq": "is not", "contains": "contains", "doesNotContain": "does not contain",
+ "gt": "is more than", "gte": "is at least", "lt": "is less than", "lte": "is at most",
+ "within": "is within", "isAnyOf": "is one of", "isNoneOf": "is none of",
+ "hasAnyOf": "has any of", "hasAllOf": "has all of", "hasNoneOf": "has none of",
+}
+
+SCHEMA = {
+ "type": "object",
+ "description": ("List the people of your own workspace, with each person's role, what they "
+ "can open, their row limits and hidden fields."),
+ "properties": {"username": {"type": "string"}},
+ "additionalProperties": False,
+}
+
+
+_ADMITTED = {"who uses loopable here", "who uses loopable", "who uses loopable in my workspace",
+ "who is in my workspace", "who are the people in my workspace"}
+
+
+def admits(question):
+ """True for a directory question, so the router can skip its database match."""
+ import re
+ return " ".join(re.findall(r"\w+", str(question).casefold())) in _ADMITTED
+
+
+class DirectoryUnavailable(ValueError):
+ """The registry or the caller's own account could not be read. Fail closed."""
+
+
+def _tenant(session):
+ want = str(getattr(session, "tenant", "") or "").strip().lower()
+ own = str((getattr(session, "user", None) or {}).get("tenant") or "").strip().lower()
+ if not want or (own and own != want):
+ raise DirectoryUnavailable(REFUSAL)
+ return want
+
+
+def _accounts(session):
+ """`[(username, record)]` of the caller's tenant. Refuses when the caller is not among them."""
+ tenant = _tenant(session)
+ accounts = users._tenant_accounts(tenant)
+ me = str(getattr(session, "uname", "") or "").strip().lower()
+ if not me or me not in {str(n).strip().lower() for n, _ in accounts}:
+ # An empty list is a failed read or a revoked caller. Never an answer.
+ raise DirectoryUnavailable(REFUSAL)
+ return sorted(accounts, key=lambda pair: str(pair[0]).lower())
+
+
+def _lend(session):
+ from core import user_tables
+ return user_tables.lend_defs(session.runtime)
+
+
+def _databases(session, st):
+ """`[{key, label}]`: every database this tenant governs, topics and its own `ut_*` tables."""
+ from core import registry, user_tables
+ ut = user_tables.nav_entries(viewer=session.uname, is_admin=True, st=st)
+ topics = list(registry.governable_modules().values())
+ return perms.tenant_governable_modules(session.runtime, topics, ut_entries=ut)
+
+
+def _modules(session):
+ """`[{key, label}]`: the app surfaces this tenant is provisioned for."""
+ return [m for m in perms.governable_surface_modules()
+ if perms.tenant_has_module(session.runtime, m["key"])]
+
+
+def _fields(principal, key, st):
+ """`{field_key: label}` this principal may see on `key`, or None when unreadable."""
+ try:
+ rows = perm_scope.scoped_fields(principal, key, st=st)
+ except Exception: # noqa: BLE001
+ return None
+ return {str(f["key"]): str(f.get("label") or f["key"])
+ for f in rows or () if isinstance(f, dict) and f.get("key")}
+
+
+def _name_field(seen, key):
+ """The label of `key` when the caller can see it, else the hidden placeholder."""
+ return (seen or {}).get(str(key)) or HIDDEN_FIELD
+
+
+def _value(leaf):
+ if isinstance(leaf.get("values"), list):
+ return ", ".join(str(v) for v in leaf["values"])
+ if leaf.get("op") == "between":
+ return f"{leaf.get('value')} and {leaf.get('value2')}"
+ return str(leaf.get("value") if leaf.get("value") is not None else "")
+
+
+def _leaf_sentence(leaf, seen):
+ """One plain sentence for a filter leaf, or None when it names a field the caller cannot see."""
+ col = str(leaf.get("colId") or "")
+ if col not in (seen or {}):
+ return None
+ rhs = leaf.get("rhs")
+ if isinstance(rhs, dict):
+ if str(rhs.get("colId") or "") not in seen:
+ return None
+ target = seen[str(rhs["colId"])]
+ else:
+ target = _value(leaf)
+ op = str(leaf.get("op") or "")
+ label = seen[col]
+ if op == "isEmpty":
+ return f"{label} is empty"
+ if op == "isNotEmpty":
+ return f"{label} is not empty"
+ if op == "between":
+ return f"{label} is between {target}"
+ if op in _OPS:
+ return f"{label} {_OPS[op]} {target}".rstrip()
+ return f"{label} has a ranking condition"
+
+
+def _node_sentence(node, seen):
+ if not isinstance(node, dict):
+ return None
+ if isinstance(node.get("children"), list):
+ parts = [_node_sentence(child, seen) for child in node["children"]]
+ if not parts or any(p is None for p in parts):
+ return None
+ joiner = " or " if node.get("conj") == "or" else " and "
+ return "(" + joiner.join(parts) + ")" if len(parts) > 1 else parts[0]
+ return _leaf_sentence(node, seen)
+
+
+def _filter_sentences(tree, seen, label):
+ """Plain sentences for one stored filter tree. A leaf the caller cannot see reads LIMITED."""
+ if isinstance(tree, dict):
+ nodes = tree.get("nodes") if isinstance(tree.get("nodes"), list) else []
+ conj = "or" if tree.get("conj") == "or" else "and"
+ else:
+ nodes, conj = (tree if isinstance(tree, list) else []), "and"
+ parts = [_node_sentence(n, seen) for n in nodes]
+ if not parts:
+ return []
+ prefix = f"{label}: " if label else ""
+ if conj == "or":
+ if any(p is None for p in parts):
+ return [LIMITED]
+ return [prefix + " or ".join(parts)]
+ return [LIMITED if p is None else prefix + p for p in parts]
+
+
+def _legacy_limits(rec):
+ out = []
+ labels = users.allowed_bus_labels(rec)
+ if "All" not in labels and labels:
+ out.append("Business unit is " + " or ".join(labels))
+ agent = perms.scope_agent(rec)
+ if agent:
+ out.append(f"Sales agent is {agent}")
+ return out
+
+
+def _entry(session, uname, rec, ctx):
+ """The whitelist projection of one colleague, as the caller is allowed to see it."""
+ principal = users._public(uname, rec)
+ st, caller = ctx["st"], session.user
+ admin = perms.is_admin(principal)
+ modules = list(_WORKSPACE_MODULES) + [m["label"] for m in ctx["modules"]
+ if admin or perm_scope.nav_may_open(principal, m["key"], st=st)]
+ named, unnamed, limits, hidden = [], 0, [], []
+ for db in ctx["databases"]:
+ key = db["key"]
+ if not (admin or perm_scope.may_read(principal, key, st=st)):
+ continue
+ seen = ctx["seen"].get(key)
+ if seen is None:
+ # The caller cannot read this database: never name it, count it.
+ unnamed += 1
+ seen = {}
+ else:
+ named.append(db["label"])
+ if admin:
+ continue
+ stored = perm_scope.entry(principal, key) or {}
+ if perm_scope.is_migrated(principal) and stored.get("filter"):
+ limits.extend(_filter_sentences(stored["filter"], seen,
+ db["label"] if key in ctx["seen"] else ""))
+ theirs = _fields(principal, key, st)
+ keys = [str(k) for k in (stored.get("hiddenFields") or ()) if k]
+ if theirs is not None:
+ keys += [k for k in seen if k not in theirs and k not in keys]
+ hidden.extend(_name_field(seen, k) for k in keys)
+ if unnamed:
+ named.append(f"{unnamed} database{'' if unnamed == 1 else 's'} you cannot open")
+ if not admin and not perm_scope.is_migrated(principal):
+ limits = _legacy_limits(rec) + limits
+ return {"username": str(rec.get("username_original") or uname),
+ "name": str(rec.get("name") or uname),
+ "role": "Administrator" if admin else "Member",
+ "modules": modules, "databases": named,
+ "rowLimits": limits, "hiddenFields": hidden}
+
+
+def _context(session):
+ st = _lend(session)
+ databases = [d for d in _databases(session, st) if isinstance(d, dict) and d.get("key")]
+ caller = session.user
+ seen = {}
+ for db in databases:
+ if perm_scope.may_read(caller, db["key"], st=st):
+ seen[db["key"]] = _fields(caller, db["key"], st) or {}
+ return {"st": st, "databases": databases, "modules": _modules(session), "seen": seen}
+
+
+def people(session):
+ """Every active account of the caller's own workspace. Raises DirectoryUnavailable."""
+ try:
+ accounts = _accounts(session)
+ ctx = _context(session)
+ return [_entry(session, n, rec, ctx) for n, rec in accounts]
+ except DirectoryUnavailable:
+ raise
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Workspace directory read failed (%s)", type(exc).__name__)
+ raise DirectoryUnavailable(REFUSAL) from exc
+
+
+def _colleague(session, username):
+ """One same-tenant account, or None when nobody matches. Raises DirectoryUnavailable."""
+ want = str(username or "").strip().casefold()
+ if not want:
+ return None
+ try:
+ accounts = _accounts(session)
+ match = [(n, rec) for n, rec in accounts
+ if want in {str(n).casefold(), str(rec.get("username_original") or "").casefold(),
+ str(rec.get("name") or "").strip().casefold()}]
+ if not match:
+ return None
+ return _entry(session, match[0][0], match[0][1], _context(session))
+ except DirectoryUnavailable:
+ raise
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Workspace directory lookup failed (%s)", type(exc).__name__)
+ raise DirectoryUnavailable(REFUSAL) from exc
+
+
+def colleague(session, username):
+ """One same-tenant active account by username or name, or None. Never crosses tenants."""
+ try:
+ return _colleague(session, username)
+ except DirectoryUnavailable:
+ return None
+
+
+def workspace_people(session, args):
+ """The `workspace_people` tool: the caller's workspace roster, or one person in it."""
+ args = args if isinstance(args, dict) else {}
+ want = str(args.get("username") or "").strip()
+ try:
+ if want:
+ one = _colleague(session, want)
+ if one is None:
+ return {"people": [], "note": NOT_FOUND}
+ return {"people": [one]}
+ return {"people": people(session)}
+ except DirectoryUnavailable:
+ return {"ok": False, "refused": REFUSAL}
+
+
+TOOLS = ({"name": "workspace_people", "schema": SCHEMA, "fn": workspace_people, "effect": "read"},)
diff --git a/api/agent_inbox.py b/api/agent_inbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..19248295039d88d8d73bf4c8013a176aead77a51
--- /dev/null
+++ b/api/agent_inbox.py
@@ -0,0 +1,682 @@
+"""Agent messages: one person's agent sends an access request, a share or a question (C6).
+
+R94: three kinds, one line of text each. A repeat within a day folds into the first message.
+R108(l): the recipient gets one notice turn in their conversation at the next visit, and on
+WhatsApp when connected and inside the 24-hour window (`assistant_feed.post` decides that).
+R81: the inbox has no screen of its own. It lives in the chat.
+R84: a recipient is resolved only among the caller's own workspace accounts.
+`send` is the one door: the `agent_message` tool and the T28 route both use it.
+R93 (S72-T28): an access request goes to the item's owner, and to the Administrators for a
+database. Only a person's click on the C6 route reaches `decide_request`. No agent tool does.
+"""
+import copy
+import datetime as _dt
+import logging
+import re
+import secrets
+
+import ai_enrich
+import agent_directory
+import assistant_log
+from core import alerts, perms, users
+
+_LOG = logging.getLogger(__name__)
+
+STORE_KEY = "agent_inbox"
+KINDS = ("access_request", "share", "question")
+TARGET_KINDS = ("database", "sheet", "view", "app")
+ROLES = ("view", "edit")
+ACTIONS = ["approve", "not_now"]
+C6_KEYS = ("type", "request_id", "sender", "target", "text", "actions", "state")
+TEXT_LIMIT = 280
+FOLD_SECONDS = 24 * 3600
+
+NOT_IN_WORKSPACE = "That person is not in your workspace."
+TWO_NAMES = "Two people share that name. Use their username."
+NOT_YOURSELF = "You cannot send a message to yourself."
+NAME_ASK = "Name the person to ask."
+NAME_TO = "Name the person to send this to."
+NO_KIND = "Choose an access request, a share or a question."
+NO_TEXT = "Write one line to send."
+TOO_LONG = f"Keep the message to one line of {TEXT_LIMIT} characters or fewer."
+NO_TARGET = "Name the database, sheet, view or app this message is about."
+BAD_TARGET = "That target is not a database, sheet, view or app."
+BAD_ROLE = "Ask for view or edit access."
+APP_VIEW_ONLY = "Apps can only be shared for viewing."
+UNAVAILABLE = "The message could not be sent. Try again in a moment."
+NOT_FOUND = "I could not find that item."
+OWN_ITEM = "That item is already yours."
+ALREADY_HELD = "You already have that access."
+NO_ANSWERER = "No one in your workspace can answer this request."
+NO_REQUEST = "I could not find that request."
+BAD_ACTION = "Choose approve or not now."
+ONLY_ADMIN = "Only an Administrator can answer a database request."
+ONLY_OWNER = "Only the owner of this item can answer this request."
+USE_MANAGE_USERS = "Give access to this database in Manage users."
+TURN_ON = "Turn this database on for them in Manage users."
+CHANGED = "Someone changed who has access while you were answering. Try again."
+NOT_GRANTED = "The access could not be granted. Try again in a moment."
+NOT_ANSWERED = "The request could not be answered. Try again in a moment."
+RANK = {None: 0, "view": 1, "edit": 2, "owner": 3}
+
+SCHEMA = {
+ "type": "object",
+ "description": ("Send one short message to a person in your workspace: an access request, "
+ "a share or a question."),
+ "properties": {
+ "type": {"type": "string", "enum": list(KINDS)},
+ "to": {"type": "string"},
+ "target": {"type": "object", "properties": {
+ "kind": {"type": "string", "enum": list(TARGET_KINDS)},
+ "key": {"type": "string"},
+ "label": {"type": "string"}}, "additionalProperties": False},
+ "text": {"type": "string"},
+ "role": {"type": "string", "enum": list(ROLES)},
+ },
+ "required": ["type", "text"],
+ "additionalProperties": False,
+}
+
+
+class Refused(ValueError):
+ """A message that cannot be sent. The text is one plain sentence for the sender."""
+
+
+class Denied(Exception):
+ """A click on the C6 route that changes nothing: an HTTP status, a code and one sentence."""
+
+ def __init__(self, status, code, message):
+ super().__init__(message)
+ self.status, self.code, self.message = status, code, message
+
+
+def _now(now=None):
+ if isinstance(now, _dt.datetime):
+ return now.astimezone(_dt.timezone.utc)
+ from core import write_execution
+ return write_execution.utcnow()
+
+
+def _age(created_at, now):
+ try:
+ return (now - _dt.datetime.fromisoformat(str(created_at))).total_seconds()
+ except (TypeError, ValueError):
+ return None
+
+
+def _recipient(session, who):
+ """`(registry_key, record)` of one active account in the caller's tenant. Raises Refused."""
+ want = str(who or "").strip().casefold()
+ if not want:
+ raise Refused(NOT_IN_WORKSPACE)
+ try:
+ accounts = agent_directory._accounts(session)
+ except agent_directory.DirectoryUnavailable as exc:
+ raise Refused(UNAVAILABLE) from exc
+ match = [(n, rec) for n, rec in accounts
+ if want in {str(n).strip().casefold(),
+ str(rec.get("username_original") or "").strip().casefold()}]
+ if not match:
+ match = [(n, rec) for n, rec in accounts
+ if str(rec.get("name") or "").strip().casefold() == want]
+ if len(match) > 1:
+ raise Refused(TWO_NAMES)
+ if not match:
+ # One sentence for another tenant, an inactive account and nobody alike.
+ raise Refused(NOT_IN_WORKSPACE)
+ uname, rec = match[0]
+ uname = str(uname).strip().lower()
+ if uname == str(session.uname or "").strip().lower():
+ raise Refused(NOT_YOURSELF)
+ return uname, rec
+
+
+def _text(value):
+ text = ai_enrich.no_dashes(" ".join(str(value or "").split())).strip()
+ if not text:
+ raise Refused(NO_TEXT)
+ if len(text) > TEXT_LIMIT:
+ raise Refused(TOO_LONG)
+ return text
+
+
+def _target(kind, value):
+ if value is None or value == {}:
+ if kind == "question":
+ return None
+ raise Refused(NO_TARGET)
+ if not isinstance(value, dict):
+ raise Refused(BAD_TARGET)
+ tkind, key = str(value.get("kind") or ""), str(value.get("key") or "").strip()
+ if tkind not in TARGET_KINDS or not key or len(key) > 200:
+ raise Refused(BAD_TARGET)
+ label = ai_enrich.no_dashes(" ".join(str(value.get("label") or key).split()))[:160]
+ return {"kind": tkind, "key": key, "label": label or key}
+
+
+# ── S72-T28: the real item behind a target, and who answers for it (R93) ──────────────────────
+def _ids(key):
+ """`key`, then its last part: a link key reads `/`."""
+ key = str(key or "").strip()
+ tail = re.split(r"[/:]", key)[-1].strip()
+ return [key] + ([tail] if tail and tail != key else [])
+
+
+def _lower(value):
+ return str(value or "").strip().lower() or None
+
+
+def _database_ref(session, key):
+ from core import user_tables
+ want = str(key).strip().casefold()
+ for db in agent_directory._databases(session, agent_directory._lend(session)) or ():
+ if not isinstance(db, dict) or not db.get("key"):
+ continue
+ if want not in {str(db["key"]).casefold(), str(db.get("label") or "").strip().casefold()}:
+ continue
+ oid = str(db["key"])
+ ref = {"kind": "database", "key": oid, "oid": oid, "label": db.get("label") or oid,
+ "owner": None, "creator": None}
+ if oid.startswith(user_tables.KEY_PREFIX):
+ table = user_tables.get_one(oid, session.runtime)
+ if not table:
+ return None
+ ref["creator"] = _lower(table.get("createdBy"))
+ return ref
+ return None
+
+
+def _sheet_ref(session, key):
+ from core import shares, sheets
+ for oid in _ids(key):
+ try:
+ book = sheets.get_workbook(session.runtime, oid)
+ except sheets.SheetRefusal:
+ continue
+ bid = str(book.get("id") or oid)
+ owner = (shares.grants("workbook", bid, st=session.runtime)["owner"]
+ or _lower(book.get("created_by")))
+ return {"kind": "sheet", "key": bid, "oid": bid, "label": book.get("name") or "A sheet",
+ "owner": owner, "book": book}
+ return None
+
+
+def _view_ref(session, key):
+ import routes_shares
+ from core import shares
+ for oid in _ids(key):
+ topic, creator, view = routes_shares._find_view_record(session, oid)
+ if not topic:
+ continue
+ database = {"customer": "customer_data", "product": "product_data"}.get(topic, topic)
+ owner = shares.grants("view", oid, st=session.runtime)["owner"] or _lower(creator)
+ return {"kind": "view", "key": f"{database}/{oid}", "oid": oid,
+ "label": (view or {}).get("name") or "A view", "owner": owner}
+ return None
+
+
+def _app_ref(session, key):
+ import application_registry as apps
+ found = apps.load(session.runtime).get("applications") or {}
+ for oid in _ids(key):
+ app = found.get(oid)
+ if not isinstance(app, dict) or app.get("templateKind") == apps.FINANCE_TEMPLATE_KIND:
+ continue
+ dbs = [str(d) for d in app.get("compatibleDatabases") or () if d]
+ return {"kind": "app", "key": f"{dbs[0]}/{oid}" if dbs else oid, "oid": oid,
+ "label": app.get("name") or "An app", "owner": _lower(app.get("createdBy")),
+ "app": app}
+ return None
+
+
+_RESOLVERS = {"database": _database_ref, "sheet": _sheet_ref, "view": _view_ref, "app": _app_ref}
+
+
+def _resolve(session, target):
+ """The real item behind a C6 target, with its real label and owner. Raises Refused."""
+ try:
+ ref = _RESOLVERS[target["kind"]](session, target["key"])
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Inbox target was not resolved (%s)", type(exc).__name__)
+ ref = None
+ if not ref:
+ # One sentence for missing, unreadable and failed alike: a refusal never confirms an id.
+ raise Refused(NOT_FOUND)
+ ref["label"] = ai_enrich.no_dashes(" ".join(str(ref["label"]).split()))[:160] or ref["key"]
+ return ref
+
+
+def _public_target(ref):
+ return {"kind": ref["kind"], "key": ref["key"], "label": ref["label"]}
+
+
+def _held(session, ref, principal):
+ """`principal`'s current role on the item: `owner`, `edit`, `view` or None."""
+ from core import perm_scope, shares, sheets, user_tables
+ import application_registry as apps
+ rt, uname = session.runtime, _lower((principal or {}).get("username"))
+ if not uname:
+ return None
+ if perms.is_admin(principal) or (ref["kind"] != "database" and ref.get("owner") == uname):
+ return "owner"
+ kind, oid = ref["kind"], ref["oid"]
+ if kind == "database":
+ if not perm_scope.may_read(principal, oid, st=rt):
+ return None
+ if oid.startswith(user_tables.KEY_PREFIX) and \
+ user_tables.may_edit_database(oid, uname, False, st=rt):
+ return "edit"
+ return "view"
+ if kind == "sheet":
+ return sheets.workbook_role(rt, ref["book"], uname)
+ if kind == "view":
+ return shares.role_for("view", oid, uname, st=rt)
+ if apps.may_edit(ref["app"], uname):
+ return "edit"
+ return "view" if apps.may_read(ref["app"], uname) else None
+
+
+def _answerers(session, ref):
+ """`(usernames, owner)`: who answers a request about `ref` in the caller's tenant (R93).
+
+ A sheet, view or app goes to its active owner. A database, or an item whose owner is not
+ an active account here, goes to every active Administrator.
+ """
+ active = {str(n).strip().lower(): rec for n, rec in agent_directory._accounts(session)}
+ owner = ref.get("owner")
+ if ref["kind"] != "database" and owner in active:
+ return [owner], owner
+ return sorted(n for n, rec in active.items() if perms.is_admin(rec)), None
+
+
+def _route_request(session, ref, role):
+ """Recipients of an access request. Raises Refused for an item the sender already holds."""
+ me = _lower(session.uname)
+ if ref["kind"] != "database" and ref.get("owner") == me:
+ raise Refused(OWN_ITEM)
+ if RANK[_held(session, ref, session.user)] >= RANK[role]:
+ raise Refused(ALREADY_HELD)
+ try:
+ answerers, _owner = _answerers(session, ref)
+ except agent_directory.DirectoryUnavailable as exc:
+ raise Refused(UNAVAILABLE) from exc
+ recipients = [u for u in answerers if u != me]
+ if not recipients:
+ raise Refused(NO_ANSWERER)
+ return recipients
+
+
+def _same(record, sender, recipients, kind, target, text, role, now):
+ """True when `record` is an earlier copy of this message within a day."""
+ if record.get("type") != kind or (record.get("sender") or {}).get("username") != sender:
+ return False
+ if not set(recipients) & set(record.get("recipients") or ()):
+ return False
+ age = _age(record.get("created_at"), now)
+ if age is None or not 0 <= age < FOLD_SECONDS:
+ return False
+ theirs = record.get("target") or {}
+ mine = target or {}
+ if (theirs.get("kind"), theirs.get("key")) != (mine.get("kind"), mine.get("key")):
+ return False
+ if kind == "access_request":
+ return record.get("state") == "pending" and record.get("role") == role
+ return record.get("text") == text
+
+
+def _title(record):
+ name = record["sender"]["name"]
+ label = (record.get("target") or {}).get("label") or ""
+ if record["type"] == "access_request":
+ level = "edit access" if record.get("role") == "edit" else "access"
+ return ai_enrich.no_dashes(f"{name} asks for {level} to {label}")
+ if record["type"] == "share":
+ return ai_enrich.no_dashes(f"{name} shared {label} with you")
+ return ai_enrich.no_dashes(f"{name} has a question" + (f" about {label}" if label else ""))
+
+
+def notice_payload(record, recipient=None):
+ """The C6 payload of one record. `recipient` is reserved for per-recipient state."""
+ kind = record.get("type")
+ state = record.get("state") if kind == "access_request" else "pending"
+ if state not in ("pending", "approved", "declined"):
+ state = "pending"
+ actions = list(ACTIONS) if kind == "access_request" and state == "pending" else []
+ sender = record.get("sender") or {}
+ return {"type": kind, "request_id": record.get("request_id"),
+ "sender": {"username": str(sender.get("username") or ""),
+ "name": str(sender.get("name") or "")},
+ "target": copy.deepcopy(record.get("target")), "text": record.get("text") or "",
+ "actions": actions, "state": state}
+
+
+def get(rt, request_id):
+ """One stored record, or None."""
+ return copy.deepcopy(((rt.get(STORE_KEY) or {}).get("requests") or {}).get(str(request_id)))
+
+
+def update(rt, request_id, fn):
+ """Apply `fn(record) -> record` under the store lock. Returns the new record or None."""
+ out = []
+
+ def apply(raw):
+ data = copy.deepcopy(raw) if isinstance(raw, dict) else {}
+ requests = data.setdefault("requests", {})
+ current = requests.get(str(request_id))
+ if not isinstance(current, dict):
+ return data
+ new = fn(copy.deepcopy(current))
+ if not isinstance(new, dict):
+ raise ValueError("Updating an inbox request needs an object.")
+ new.update(request_id=current["request_id"], updated_at=_now().isoformat())
+ requests[str(request_id)] = new
+ out[:] = [copy.deepcopy(new)]
+ return data
+
+ rt.update(STORE_KEY, apply, flush="sync")
+ return out[0] if out else None
+
+
+def _notice_id(rt, uname, request_id):
+ try:
+ turns = assistant_log.read(rt, uname, limit=20).get("turns") or []
+ except Exception: # noqa: BLE001
+ return None
+ return next((t.get("id") for t in reversed(turns)
+ if (t.get("payload") or {}).get("request_id") == request_id), None)
+
+
+def _public(record, folded):
+ return {"ok": True, "folded": folded, "request_id": record["request_id"],
+ "type": record["type"], "state": record["state"],
+ "to": [str(u) for u in record.get("recipients") or ()],
+ "target": copy.deepcopy(record.get("target")), "text": record["text"]}
+
+
+def _send(session, kind, to, target, text, role, now):
+ if kind not in KINDS:
+ raise Refused(NO_KIND)
+ # R93: an access request is routed to whoever may answer it, so `to` is not needed there.
+ if kind != "access_request" and not str(to or "").strip():
+ raise Refused(NAME_TO)
+ if role not in ROLES:
+ raise Refused(BAD_ROLE)
+ text = _text(text)
+ target = _target(kind, target)
+ if kind == "access_request":
+ if target["kind"] == "app" and role != "view":
+ raise Refused(APP_VIEW_ONLY)
+ ref = _resolve(session, target)
+ recipients = _route_request(session, ref, role)
+ target = _public_target(ref)
+ else:
+ recipients = [_recipient(session, to)[0]]
+ if target is not None:
+ ref = _resolve(session, target)
+ if _held(session, ref, session.user) is None:
+ raise Refused(NOT_FOUND)
+ target = _public_target(ref)
+ me = str(session.uname or "").strip().lower()
+ sender = {"username": me, "name": str((session.user or {}).get("name") or me)}
+ stamp = _now(now)
+ found = {}
+
+ def apply(raw):
+ data = copy.deepcopy(raw) if isinstance(raw, dict) else {}
+ requests = data.setdefault("requests", {})
+ for rec in requests.values():
+ if isinstance(rec, dict) and _same(rec, me, recipients, kind, target, text, role, stamp):
+ found["record"], found["folded"] = copy.deepcopy(rec), True
+ return data
+ from core import write_execution
+ rid = write_execution.new_id()[:24]
+ rec = {"request_id": rid, "type": kind, "sender": sender, "recipients": list(recipients),
+ "target": target, "text": text,
+ "role": role if kind == "access_request" else None,
+ "state": "pending" if kind == "access_request" else "sent",
+ "created_at": stamp.isoformat(), "updated_at": stamp.isoformat(),
+ "notices": {}, "decided_by": None, "decided_at": None}
+ requests[rid] = rec
+ found["record"], found["folded"] = copy.deepcopy(rec), False
+ return data
+
+ session.runtime.update(STORE_KEY, apply, flush="sync")
+ record = found["record"]
+ if found["folded"]:
+ return _public(record, True)
+ rt, rid = session.runtime, record["request_id"]
+ notices = {}
+ for uname in record["recipients"]:
+ alerts.notify(uname, _title(record), topic="inbox", key=rid, detail=record["text"],
+ actor=sender["name"], st=rt, target=copy.deepcopy(record["target"]),
+ inbox=notice_payload(record, uname))
+ turn_id = _notice_id(rt, uname, rid)
+ if turn_id:
+ notices[uname] = turn_id
+ if notices:
+ record = update(rt, rid, lambda rec: {**rec, "notices": {**rec.get("notices", {}),
+ **notices}}) or record
+ return _public(record, False)
+
+
+def send(session, *, type, to, target, text, role="view", now=None): # noqa: A002
+ """Send one message. Returns the request, `folded: true` for a repeat, or a refusal."""
+ try:
+ return _send(session, type, to, target, text, role, now)
+ except Refused as exc:
+ return {"ok": False, "refused": str(exc)}
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Agent message was not sent (%s)", exc.__class__.__name__)
+ return {"ok": False, "refused": UNAVAILABLE}
+
+
+def agent_message(session, args):
+ """The `agent_message` tool."""
+ args = args if isinstance(args, dict) else {}
+ return send(session, type=str(args.get("type") or ""), to=args.get("to"),
+ target=args.get("target"), text=args.get("text"),
+ role=str(args.get("role") or "view"))
+
+
+# ── S72-T28: a person answers an access request (C6 route only) ───────────────────────────────
+# ⛔ No agent tool may call into this section. An agent never changes a grant with no person's
+# click (R93). `verify_agent_inbox` walks every registered tool to prove it.
+def _may_answer(session, ref):
+ """R93: the owner answers a sheet, view or app. An Administrator answers a database."""
+ if ref["kind"] == "database":
+ return bool(session.admin) # only an Administrator grants a database
+ _who, owner = _answerers(session, ref)
+ if owner:
+ return owner == _lower(session.uname)
+ return bool(session.admin)
+
+
+def _asker(session, record):
+ want = _lower((record.get("sender") or {}).get("username"))
+ for n, rec in agent_directory._accounts(session):
+ if str(n).strip().lower() == want:
+ return want, users._public(n, rec)
+ raise Denied(409, "asker_gone", NOT_IN_WORKSPACE)
+
+
+def _with_grant(prior, user, role):
+ """`prior` with `user` at `role`. Every other entry is copied unchanged."""
+ rows = [dict(e) for e in prior or ()]
+ for row in rows:
+ if row.get("user") == user:
+ row["role"] = role
+ return rows
+ return rows + [{"user": user, "role": role}]
+
+
+def _add_grant(kind, oid, user, role, *, owner, granter, st):
+ """Add one grant through `shares.set_grants`, guarded by `expect`, the PUT door's own CAS."""
+ from core import shares
+ held = shares.grants(kind, oid, st=st)
+ return shares.set_grants(kind, oid, _with_grant(held["entries"], user, role),
+ owner=None if held["owner"] else owner, st=st,
+ granter=granter, expect=held["entries"])
+
+
+def _approve_grant(session, ref, asker, principal, role):
+ """Grant exactly `role` to exactly `asker` on exactly the item. Raises Denied."""
+ rt, kind, oid = session.runtime, ref["kind"], ref["oid"]
+ if kind == "app" and role != "view":
+ raise Denied(409, "unsupported_role", APP_VIEW_ONLY)
+ if kind == "database":
+ import routes_admin
+ routes_admin.grant_database_access(session, asker, oid, role)
+ return
+ if RANK[_held(session, ref, principal)] >= RANK[role]:
+ return # The asker holds this already: nothing to write.
+ if kind == "sheet":
+ from core import sheets
+ _add_grant("workbook", oid, asker, role, owner=ref.get("owner"),
+ granter=session.uname, st=rt)
+ if "access" not in ref["book"]:
+ sheets.narrow_workbook(rt, oid) # the marker `routes_sheet.share_sheet` writes too
+ elif kind == "view":
+ # The PUT door's View path: the audience and its field boundary in one transaction.
+ import routes_shares
+ from core import field_permissions, shares
+ held = shares.grants("view", oid, st=rt)
+ _topic, view, grant_topic, _keys, _owned = routes_shares._prepare_view_share(session, oid)
+ field_permissions.set_view_grants_with_boundary(
+ view, grant_topic, _with_grant(held["entries"], asker, role),
+ owner=None if held["owner"] else ref.get("owner"), granter=session.uname,
+ expect=held["entries"], st=rt)
+ else:
+ import application_registry as apps
+ app = (apps.load(rt).get("applications") or {}).get(oid) or {}
+ share = app.get("share") if isinstance(app.get("share"), dict) else {}
+ names = list(share.get("users") or ()) if share.get("mode") == "users" else []
+ apps.mutate(rt, oid, session.uname, session.admin,
+ {"share": {"mode": "users", "users": names + [asker]}}, expect=share)
+
+
+def _claim(rt, request_id, state, who):
+ """Move a pending request to `state` once. Returns `(record, claimed)`."""
+ claimed = []
+
+ def fn(rec):
+ # A store replay must report whether this invocation won the claim.
+ claimed.clear()
+ if rec.get("state") != "pending":
+ return rec
+ claimed.append(True)
+ return {**rec, "state": state, "decided_by": who, "decided_at": _now().isoformat()}
+
+ return update(rt, request_id, fn), bool(claimed)
+
+
+def _close_cards(rt, record):
+ """Rewrite each recipient's notice to the final state with no buttons."""
+ def fn(turn):
+ payload = dict(turn.get("payload") or {}, state=record["state"], actions=[])
+ return {**turn, "payload": payload}
+
+ for uname in record.get("recipients") or ():
+ turn_id = ((record.get("notices") or {}).get(uname)
+ or _notice_id(rt, uname, record["request_id"]))
+ try:
+ if turn_id:
+ assistant_log.update_turn(rt, uname, turn_id, fn)
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Inbox card was not closed (%s)", type(exc).__name__)
+
+
+def _tell_asker(session, record):
+ """One outcome notice to the asker. It never raises: the decision already stands."""
+ me = _lower(session.uname)
+ name = str((session.user or {}).get("name") or me)
+ text = ai_enrich.no_dashes(f"{name} approved your request." if record["state"] == "approved"
+ else f"{name} said not now.")
+ payload = dict(notice_payload(record), sender={"username": me, "name": name}, text=text)
+ try:
+ alerts.notify(record["sender"]["username"], text, topic="inbox",
+ key=record["request_id"], detail=text, actor=name, st=session.runtime,
+ target=copy.deepcopy(record.get("target")), inbox=payload)
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Inbox outcome was not sent (%s)", type(exc).__name__)
+
+
+def _unclaim(rt, request_id, state, who):
+ """Put a claimed request back to pending, only while it still reads `state` by `who`."""
+ def fn(rec):
+ if rec.get("state") != state or rec.get("decided_by") != who:
+ return rec
+ return {**rec, "state": "pending", "decided_by": None, "decided_at": None}
+
+ return update(rt, request_id, fn)
+
+
+def _denied(exc):
+ """The Denied a failed answer maps to. Every refusal stays one plain sentence."""
+ from core import shares
+ from fastapi import HTTPException
+ if isinstance(exc, Denied):
+ return exc
+ if isinstance(exc, HTTPException) and isinstance(exc.detail, dict):
+ error = exc.detail.get('error') or {}
+ return Denied(exc.status_code, error.get('code') or 'not_granted',
+ error.get('message') or NOT_GRANTED)
+ if isinstance(exc, agent_directory.DirectoryUnavailable):
+ return Denied(503, "unavailable", NOT_ANSWERED)
+ if isinstance(exc, PermissionError):
+ return Denied(403, "not_allowed", ONLY_OWNER)
+ if isinstance(exc, shares.GrantsChanged):
+ return Denied(409, "grants_changed", CHANGED)
+ _LOG.warning("Inbox request was not answered (%s)", type(exc).__name__)
+ return Denied(409, "not_granted", NOT_GRANTED)
+
+
+def decide_request(session, request_id, action):
+ """Answer one access request on a person's click (C6, R93). Returns `{"state"}`.
+
+ The decision is claimed before the grant, so a parallel click can never leave a grant under
+ a declined record. A failed grant puts the claim back.
+ """
+ if action not in ACTIONS:
+ raise Denied(400, "bad_action", BAD_ACTION)
+ rt, me = session.runtime, _lower(session.uname)
+ record = get(rt, request_id)
+ # The store is the tenant's own, so another tenant's id is simply not here.
+ if not isinstance(record, dict) or record.get("type") != "access_request" \
+ or not isinstance(record.get("target"), dict):
+ raise Denied(404, "no_request", NO_REQUEST)
+ decided = record.get("state") in ("approved", "declined")
+ try:
+ try:
+ ref = _resolve(session, record["target"])
+ except Refused:
+ if decided and (session.admin or me == record.get("decided_by")
+ or me in (record.get("recipients") or ())):
+ return {"state": record["state"]}
+ raise Denied(404, "no_item", NOT_FOUND)
+ if not _may_answer(session, ref):
+ raise Denied(403, "not_allowed",
+ ONLY_ADMIN if ref["kind"] == "database" else ONLY_OWNER)
+ if decided:
+ return {"state": record["state"]} # A second click changes nothing.
+ asker, principal = _asker(session, record)
+ state = "approved" if action == "approve" else "declined"
+ role = record.get("role")
+ if action == 'approve' and role not in ROLES:
+ raise Denied(409, "unsupported_role", BAD_ROLE)
+ except Exception as exc: # noqa: BLE001
+ raise _denied(exc) from exc
+ final, claimed = _claim(rt, record["request_id"], state, me)
+ if not claimed or not final:
+ return {"state": (final or record).get("state")} # Another click decided first.
+ if action == "approve":
+ try:
+ _approve_grant(session, ref, asker, principal, role)
+ except Exception as exc: # noqa: BLE001
+ _unclaim(rt, record["request_id"], state, me)
+ raise _denied(exc) from exc
+ _close_cards(rt, final)
+ _tell_asker(session, final)
+ return {"state": final["state"]}
+
+
+TOOLS = ({"name": "agent_message", "schema": SCHEMA, "fn": agent_message, "effect": "write"},)
diff --git a/api/agent_runtime.py b/api/agent_runtime.py
index 0b7b0c8004db89b698fdb5048acbbcdb23f143b4..4b50b111e6413f4c179335478713a63b550c4004 100644
--- a/api/agent_runtime.py
+++ b/api/agent_runtime.py
@@ -1,10 +1,14 @@
"""Server-side Assistant turns and principal-bound delete confirmation (C10)."""
+import base64
import copy
import contextvars
import hashlib
+import importlib
import inspect
import json
import logging
+import os
+import re
import threading
import time
import uuid
@@ -18,8 +22,22 @@ import turn_control
import turn_audit
PENDING_TTL_S = 600
+#: R100: a change asked on WhatsApp waits this long for the user's YES.
+CHANGE_TTL_S = 900
+CHANGE_PREVIEW_LINES = 6
DOORS = {"app", "whatsapp", "slack", "wake"}
_MEMORY_BLOCK = contextvars.ContextVar("agent_memory_block", default=None)
+#: The calls this WhatsApp turn holds for YES; None outside a WhatsApp model turn.
+_HELD = contextvars.ContextVar("agent_held_change", default=None)
+_PLACEHOLDER = re.compile(r"\bpending_(\d+)\b")
+#: R99: the photos and PDFs this turn carries; None on a turn without files.
+_ATTACHMENTS = contextvars.ContextVar("agent_attachments", default=None)
+_PRODUCING_TURN = contextvars.ContextVar("agent_producing_turn", default=None)
+_UNSET = object()
+IMAGE_INPUT_ENV = "AIOS_ASSISTANT_IMAGE_INPUT"
+ATTACHMENT_IMAGE_MIMES = {"image/jpeg", "image/png", "image/webp"}
+ATTACHMENT_PDF_MIME = "application/pdf"
+MAX_ATTACHMENTS = 4
_COMPACTION_LOCKS = {}
_LOCKS_GUARD = threading.Lock()
_LOG = logging.getLogger(__name__)
@@ -110,6 +128,8 @@ def _plain(value):
def _result(reply="", *, refused=None, turn=None):
turn = turn or {}
+ notes = dict.fromkeys(call["linkNote"] for call in turn.get("toolCalls", []) if call.get("linkNote"))
+ reply = " ".join([reply, *(note for note in notes if note not in reply)]).strip()
return {"reply": _plain(reply), "toolCalls": turn.get("toolCalls", []),
"pendingDelete": turn.get("pendingDelete"), "artifacts": turn.get("artifacts", []),
"refused": _plain(refused) if refused else None}
@@ -203,8 +223,267 @@ def _dispatch(session, name, args):
entry = agent_tools.registered().get(name)
if entry is not None:
fn = entry["fn"]
- return fn(args) if len(inspect.signature(fn).parameters) == 1 else fn(session, args)
- return external_tools.dispatch(_agent_tool_context(session), name, args)
+ result = fn(args) if len(inspect.signature(fn).parameters) == 1 else fn(session, args)
+ else:
+ result = external_tools.dispatch(_agent_tool_context(session), name, args)
+ producing = _PRODUCING_TURN.get()
+ if producing is not None and producing[0] is session:
+ _observe_sources(session, producing[1], name, args, result)
+ return result
+
+
+def _merge_sources(session, turn, sources):
+ """Keep validated database keys, with unknown evidence sticky for the whole turn."""
+ try:
+ if not isinstance(sources, list) or any(not isinstance(key, str) or not key.strip() for key in sources):
+ raise ValueError("Unknown artifact provenance.")
+ import deps
+ also_as = turn.get("also_as") or []
+ kwargs = {"mode": "schema"}
+ if also_as:
+ kwargs["also_as"] = also_as
+ keys = list(dict.fromkeys(key.strip() for key in sources))
+ for key in keys:
+ deps.assistant_read_scope(session, key, **kwargs)
+ turn["artifactSources"] = sorted(set(turn.get("artifactSources", [])) | set(keys))
+ except Exception:
+ turn["artifactSourcesUnknown"] = True
+
+
+def _turn_sources(turn):
+ if turn.get("artifactSourcesUnknown") or "artifactSources" not in turn:
+ return None
+ return copy.deepcopy(turn["artifactSources"])
+
+
+def producing_turn_sources(session, username=None):
+ """Return caller-bound source proof for a file producer, or None when unknown."""
+ producing = _PRODUCING_TURN.get()
+ if producing is None:
+ return None
+ caller, turn = producing
+ owned = (caller is session if username is None
+ else caller.runtime is session and caller.uname == username)
+ if owned:
+ _seed_sources(caller, turn)
+ return _turn_sources(turn) if owned else None
+
+
+def _argument_sources(value, depth=0):
+ if depth > 12:
+ return None
+ found = []
+ members = value.items() if isinstance(value, dict) else enumerate(value) if isinstance(value, list) else ()
+ for key, item in members:
+ if key in ("database", "sourceDatabase", "compatibleDatabases"):
+ keys = item if key == "compatibleDatabases" else [item]
+ if not isinstance(keys, list) or any(not isinstance(k, str) or not k.strip() for k in keys):
+ return None
+ found.extend(keys)
+ nested = _argument_sources(item, depth + 1)
+ if nested is None:
+ return None
+ found.extend(nested)
+ return found
+
+
+def _seed_sources(session, turn):
+ if not turn.get("artifactSourcesSeeded"):
+ turn["artifactSourcesSeeded"] = True
+ if "memorySources" in turn:
+ _merge_sources(session, turn, [source.get("database") if isinstance(source, dict) else None
+ for source in turn["memorySources"]])
+
+
+def _observe_sources(session, turn, name, args, result):
+ if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
+ return
+ _seed_sources(session, turn)
+ value = result if isinstance(result, dict) else {}
+ if "sources" in value:
+ _merge_sources(session, turn, value["sources"])
+ databases = _argument_sources(args)
+ if databases is None:
+ turn["artifactSourcesUnknown"] = True
+ databases = []
+ if isinstance(value.get("database"), str):
+ databases.append(value["database"])
+ if databases:
+ _merge_sources(session, turn, databases)
+ elif "sources" not in value and agent_tools.classify(name, args) == "read":
+ turn["artifactSourcesUnknown"] = True
+
+
+def _optional_module(name):
+ try:
+ return importlib.import_module(name)
+ except ModuleNotFoundError as exc:
+ if exc.name != name:
+ raise
+ return None
+
+
+def _artifact_result(session, artifact_id, result, call, turn):
+ """Attach only the caller's stored artifact link and conservative turn provenance."""
+ artifacts = _optional_module("assistant_artifacts")
+ get = getattr(artifacts, "get", None)
+ row = get(session.runtime, session.uname, artifact_id) if get else None
+ if row is None:
+ return result
+ if "sources" in row:
+ _merge_sources(session, turn, row["sources"])
+ sources = _turn_sources(turn)
+ amazon = sources is None or any(key.startswith("ut_amzn_") for key in sources) or row.get("amazon") is True
+ # The row lookup binds this update to the caller's tenant and owner.
+ import assistant_log
+ owner = assistant_log._hash(session.runtime, session.uname)
+ seq = artifacts._seq(owner, artifact_id)
+ if seq is not None and (row.get("sources", _UNSET) != sources or row.get("amazon", _UNSET) != amazon):
+ def update(raw):
+ doc = copy.deepcopy(raw)
+ for item in doc.get("items", []):
+ if item.get("id") == artifact_id:
+ item.update(sources=copy.deepcopy(sources), amazon=amazon)
+ return doc
+ session.runtime.update(artifacts._chunk_key(owner, seq // artifacts.CHUNK_ITEMS), update, flush="sync")
+ fields = {"sources": sources, "amazon": amazon}
+ links = getattr(artifacts, "link_fields", None)
+ if links:
+ fields.update(links(row))
+ call.update(copy.deepcopy(fields))
+ return {**result, **fields} if isinstance(result, dict) else result
+
+
+def _after_dispatch(session, door, name, args, result, call, turn, effect):
+ _observe_sources(session, turn, name, args, result)
+ if name == "agent_message":
+ return result
+ if name == "open_items" and isinstance(result, dict):
+ if not result.get("view"):
+ return result
+ view = _after_dispatch(session, door, "view_upsert", result["viewArgs"], result["view"],
+ call, turn, effect)
+ return {**result, **{key: view[key] for key in ("sources", "amazon", "link") if key in view}}
+ snapshot = _optional_module("artifact_snapshot")
+ snapshot_id = snapshot.capture(session, door, name, args, result, turn) if snapshot else None
+ if snapshot_id:
+ result = _artifact_result(session, snapshot_id, result, call, turn)
+ file_id = (result.get("fileId") or result.get("file_id")) if isinstance(result, dict) else None
+ artifact_id = None
+ if file_id:
+ files = _optional_module("assistant_files")
+ owned = getattr(files, "owned_metadata", None)
+ metadata = owned(session.runtime, session.uname, file_id) if owned else None
+ artifact_id = metadata.get("artifactId") if metadata else None
+ if not artifact_id and effect == "write":
+ artifact_id = _record_artifact(session, door, name, args, result, sources=_turn_sources(turn))
+ if artifact_id:
+ if artifact_id not in turn["artifacts"]:
+ turn["artifacts"].append(artifact_id)
+ result = _artifact_result(session, artifact_id, result, call, turn)
+ call["sources"] = _turn_sources(turn)
+ return result
+
+
+def _offered_tools():
+ offered = set(external_tools.TOOLS)
+ try:
+ agent_tools.load_modules()
+ offered |= set(agent_tools.registered())
+ except Exception:
+ _LOG.warning("Assistant tools did not load for the door guidance.", exc_info=True)
+ return offered
+
+
+def whatsapp_guidance(offered=None):
+ """R98 in plain words, naming only the tools this turn is offered."""
+ offered = _offered_tools() if offered is None else set(offered)
+ lines = ["You are answering on WhatsApp. Keep a short answer as plain text."]
+ if "make_xlsx" in offered:
+ lines.append("For a table over 10 rows, call make_xlsx and give its link.")
+ else:
+ lines.append("For a table over 10 rows, show the first 10 rows and say the rest is in Loopable.")
+ if "make_image" in offered:
+ lines.append("For a chart, call make_image.")
+ lines.append("After you create a Sheet, call make_image of it and give the Sheet's link.")
+ else:
+ lines.append("After you create a Sheet, give the Sheet's link.")
+ if "make_pdf" in offered:
+ lines.append("When the user asks for a PDF, call make_pdf.")
+ if "make_xlsx" in offered:
+ lines.append("When the user asks for an Excel file, call make_xlsx.")
+ lines.append("On WhatsApp a change waits for the user's YES, so plan every step, "
+ "then say in a few words what will change.")
+ return " ".join(lines)
+
+
+def reads_images():
+ """True when the setting says the Assistant model reads images (glm-4.7-flash reads text only)."""
+ # A literal name, so the env walk resolves it; IMAGE_INPUT_ENV names the same var.
+ return os.environ.get("AIOS_ASSISTANT_IMAGE_INPUT", "").strip().lower() in {"1", "true"}
+
+
+def _attachments(value):
+ """Validate a turn's files: photos only when the model reads images, PDFs always."""
+ if value is None:
+ return None
+ if not isinstance(value, list) or not value or len(value) > MAX_ATTACHMENTS:
+ raise ValueError("A turn can carry one to four files.")
+ checked = []
+ for item in value:
+ if not isinstance(item, dict) or not isinstance(item.get("data"), bytes) or not item["data"]:
+ raise ValueError("That file could not be read.")
+ kind, mime = item.get("kind"), item.get("mime")
+ if kind == "image" and mime in ATTACHMENT_IMAGE_MIMES:
+ if not reads_images():
+ raise ValueError("I cannot read photos yet. Type what it shows, or send it as a PDF.")
+ elif not (kind == "document" and mime == ATTACHMENT_PDF_MIME):
+ raise ValueError("I can read photos and PDFs only.")
+ filename = item.get("filename") if isinstance(item.get("filename"), str) else None
+ caption = item.get("caption") if isinstance(item.get("caption"), str) else None
+ checked.append({"kind": kind, "mime": mime, "data": item["data"],
+ "filename": (filename or "").strip()[:120] or None, "caption": caption})
+ return checked
+
+
+def has_attachments():
+ """True inside a turn that carries files."""
+ return bool(_ATTACHMENTS.get())
+
+
+def user_content(question):
+ """The user message content: the question alone, or a content list with this turn's files."""
+ items = _ATTACHMENTS.get()
+ if not items:
+ return question
+ parts = [{"type": "text", "text": question}]
+ for item in items:
+ encoded = base64.b64encode(item["data"]).decode("ascii")
+ if item["kind"] == "image":
+ if reads_images():
+ parts.append({"type": "image_url",
+ "image_url": {"url": f"data:{item['mime']};base64,{encoded}"}})
+ else:
+ parts.append({"type": "file", "file": {
+ "filename": item["filename"] or "document.pdf",
+ "file_data": "data:application/pdf;base64," + encoded}})
+ return parts
+
+
+def _attachment_line(items):
+ named = [("a photo" if item["kind"] == "image" else "a PDF")
+ + (f" named {item['filename']}" if item["filename"] else "") for item in items]
+ return "The user sent " + ", ".join(named) + ". Read it before you answer."
+
+
+def door_context(door, context):
+ """The turn context: the caller's context, the door guidance on WhatsApp, and one line naming the files."""
+ caller = context if isinstance(context, str) and context else None
+ items = _ATTACHMENTS.get()
+ files = _attachment_line(items) if items else None
+ if door != "whatsapp":
+ return "\n\n".join(part for part in (caller, files) if part) or None
+ return "\n\n".join(part for part in (caller, whatsapp_guidance(), files) if part)
def _owner(tenant, username):
@@ -261,23 +540,249 @@ def _summary(name, args, session=None):
return f"Remove {subject}."
-def _pending(session, door, name, args):
- now = time.time()
- pid = _owner(session.tenant, session.uname) + "." + uuid.uuid4().hex
- entry = {"id": pid, "tool": name, "args": copy.deepcopy(args), "summary": _summary(name, args, session),
- "tenant": session.tenant, "username": session.uname, "door": door,
- "createdAt": now, "expiresAt": now + PENDING_TTL_S}
+def _put(session, entry):
+ """Store one owner-bound pending entry and drop the expired ones."""
+ now = entry["createdAt"]
def update(raw):
pending = (raw or {}).get("pending", {})
pending = {key: value for key, value in pending.items() if value["expiresAt"] > now}
- pending[pid] = entry
+ pending[entry["id"]] = entry
return {"pending": pending}
session.runtime.update(_pending_key(session), update, flush="sync")
return {key: entry[key] for key in ("id", "summary", "expiresAt")}
+def _pending(session, door, name, args):
+ now = time.time()
+ pid = _owner(session.tenant, session.uname) + "." + uuid.uuid4().hex
+ return _put(session, {"id": pid, "tool": name, "args": copy.deepcopy(args),
+ "summary": _summary(name, args, session),
+ "tenant": session.tenant, "username": session.uname, "door": door,
+ "createdAt": now, "expiresAt": now + PENDING_TTL_S})
+
+
+def waits_for_yes(door, name, args, effect):
+ """R100: on WhatsApp an app write tool or any delete is held for the user's YES."""
+ if door != "whatsapp":
+ return False
+ return effect in {"write", "delete"}
+
+
+def _label(value, limit=60):
+ text = " ".join(_plain(str(value)).split()).rstrip(". ")
+ return text if len(text) <= limit else text[:limit - 3].rstrip() + "..."
+
+
+_SHEET_PARTS = {"sheet_set_styles": "styles", "sheet_set_dimensions": "sizes",
+ "sheet_set_validation": "dropdowns", "sheet_set_freeze": "frozen rows",
+ "sheet_add_rule": "a format rule", "sheet_set_chart": "a chart",
+ "sheet_structure": "rows or columns"}
+_PAST = {"Create": "Created", "Write": "Wrote", "Save": "Saved", "Change": "Changed",
+ "Remove": "Removed", "Add": "Added", "Bind": "Bound", "Run": "Ran", "Clear": "Cleared"}
+
+
+def _change_line(name, args):
+ """One plain imperative line for one held write, built from its name and arguments."""
+ name = name if isinstance(name, str) else ""
+ action = args.get("action")
+ inner = args.get("arguments") if isinstance(args.get("arguments"), dict) else {}
+ tab = args.get("tab") or args.get("worksheet")
+ on_tab = (" on the new tab" if isinstance(tab, str) and _PLACEHOLDER.fullmatch(tab)
+ else f" on tab {_label(tab)}" if tab else "")
+ where = f" in {_label(args['database'])}" if args.get("database") else ""
+ if name == "sheet_create_workbook" or (name == "workbook_object" and action == "create"):
+ title = args.get("name") or inner.get("name")
+ return f"Create workbook {_label(title)}." if title else "Create a workbook."
+ if name == "sheet_add_tab" or (name == "worksheet_object" and action == "add"):
+ title = args.get("name") or inner.get("name")
+ return f"Add tab {_label(title)}." if title else "Add a tab."
+ if name == "sheet_write_cells":
+ count = len(args["cells"]) if isinstance(args.get("cells"), dict) else 0
+ return f"Write {count} cell{'' if count == 1 else 's'}{on_tab}."
+ if name == "range_object":
+ target = f"range {_label(args['range'])}" if args.get("range") else "cells"
+ return f"{'Clear' if action == 'clear' else 'Write'} {target}{on_tab}."
+ if name == "sheet_set_binding":
+ return f"Bind cell {_label(args.get('addr'))}{on_tab}."
+ if name == "sheet_save_template":
+ return f"Save template {_label(args.get('name'))}."
+ if name in _SHEET_PARTS:
+ return f"Change {_SHEET_PARTS[name]}{on_tab}."
+ if name == "view_upsert" or (name == "view_object" and action == "upsert"):
+ view = args.get("view") if isinstance(args.get("view"), dict) else {}
+ title = view.get("name") or view.get("id")
+ return f"Save view {_label(title)}." if title else "Save a view."
+ if name == "app_upsert":
+ verb = "Change" if args.get("app_id") else "Create"
+ title = args.get("name") or args.get("app_id")
+ return f"{verb} app {_label(title)}." if title else f"{verb} an app."
+ if name == "database_object":
+ record = f" on record {_label(args['record_id'])}" if args.get("record_id") is not None else ""
+ field = args.get("field") if isinstance(args.get("field"), dict) else {}
+ if action == "record_create":
+ return f"Add a record{where}."
+ if action == "record_update":
+ keys = list(args["values"]) if isinstance(args.get("values"), dict) else []
+ what = (" and ".join(_label(key) for key in keys) if 0 < len(keys) <= 3
+ else f"{len(keys)} fields" if keys else "values")
+ return f"Change {what}{record}."
+ if action == "field_create":
+ title = field.get("name") or field.get("label") or field.get("key")
+ return f"Add field {_label(title)}{where}." if title else f"Add a field{where}."
+ if action == "field_update":
+ title = args.get("field_key") or field.get("name")
+ return f"Change field {_label(title)}{where}." if title else f"Change a field{where}."
+ if name.endswith("_object"):
+ return f"Change {name.removesuffix('_object')}{on_tab}."
+ return f"Run {_label(name.replace('_', ' '))}." if name else "Run a change."
+
+
+def _change_lines(name, args, session=None):
+ """The preview lines for one held call: a delete names its target, a batch each operation."""
+ args = args if isinstance(args, dict) else {}
+ if name == "validated_batch" and isinstance(args.get("operations"), list):
+ lines = []
+ for operation in args["operations"]:
+ if isinstance(operation, dict):
+ lines.extend(_change_lines(operation.get("name"), operation.get("arguments"), session))
+ return lines or ["Run a batch of changes."]
+ if agent_tools.classify(name, args) == "delete":
+ return [_summary(name, args, session)]
+ return [_change_line(name, args)]
+
+
+def _capped(lines):
+ shown = list(lines[:CHANGE_PREVIEW_LINES])
+ rest = len(lines) - len(shown)
+ if rest:
+ shown.append(f"And {rest} more step{'' if rest == 1 else 's'}.")
+ return shown
+
+
+def _past(line):
+ verb, _, rest = line.partition(" ")
+ return f"{_PAST[verb]} {rest}" if verb in _PAST and rest else line
+
+
+def _hold(session, name, args, effect, held, turn):
+ import assistant_write_preview
+ _seed_sources(session, turn)
+ ref = f"pending_{len(held) + 1}"
+ refs = {step["ref"]: _ref(step["preview"]["result"]) for step in held
+ if _ref(step["preview"]["result"]) is not None}
+ resolved = _fill(args, refs, len(held) + 1)
+ if _PLACEHOLDER.search(json.dumps(resolved)):
+ raise ValueError("A change can only use an earlier step's created object.")
+ preview = assistant_write_preview.prepare(session, name, resolved, prior=held)
+ _observe_sources(session, turn, name, resolved, preview["result"])
+ held.append({"tool": name, "args": copy.deepcopy(args), "effect": effect, "ref": ref,
+ "resolvedArgs": resolved, "preview": preview,
+ "context": {key: copy.deepcopy(turn[key]) for key in
+ ("memorySources", "memoryEvidenceSources", "memoryCompanyRequested", "door")
+ if key in turn},
+ "lines": assistant_write_preview.lines(preview, name, resolved, session),
+ "sources": _turn_sources(turn)})
+ return ref
+
+
+def _store_change(session, door, held, *, turn=None):
+ """Store the turn's held calls as ONE pending change, owner-bound like a delete."""
+ now = time.time()
+ proof = {}
+ for sources in [*(step.get("sources") for step in held),
+ *(call.get("sources") for call in (turn or {}).get("toolCalls", [])
+ if call.get("ok") and not call.get("held"))]:
+ _merge_sources(session, proof, sources)
+ sources = _turn_sources(proof)
+ # Every artifact made by YES belongs to the full producing turn, including late reads.
+ held = [{**step, "sources": copy.deepcopy(sources)} for step in held]
+ lines = [line for step in held for line in step["lines"]]
+ return _put(session, {"id": _owner(session.tenant, session.uname) + "." + uuid.uuid4().hex,
+ "kind": "change", "steps": copy.deepcopy(held),
+ "summary": "\n".join(_capped(lines)),
+ "tenant": session.tenant, "username": session.uname, "door": door,
+ "createdAt": now, "expiresAt": now + CHANGE_TTL_S})
+
+
+def _fill(value, refs, index):
+ """Replace each earlier step's placeholder with the real id that step made."""
+ if isinstance(value, dict):
+ return {key: _fill(item, refs, index) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_fill(item, refs, index) for item in value]
+ if not isinstance(value, str):
+ return value
+
+ def swap(match):
+ step = int(match.group(1))
+ if not 0 < step < index:
+ return match.group(0)
+ if match.group(0) not in refs:
+ raise ValueError(f"Step {step} made nothing that this step can use.")
+ return str(refs[match.group(0)])
+
+ if value in refs:
+ return refs[value]
+ return _PLACEHOLDER.sub(swap, value)
+
+
+def _refusal(result):
+ for key in ("error", "refused", "message"):
+ if isinstance(result.get(key), str) and result[key].strip():
+ return _plain(result[key])
+ return "The app refused it."
+
+
+def _apply_change(session, entry):
+ """Run a confirmed change's steps once, in order, and stop at the first that fails."""
+ steps = entry.get("steps") or []
+ door = entry.get("door") or "whatsapp"
+ turn = {"toolCalls": [], "pendingDelete": None, "artifacts": []}
+ refs, done = {}, []
+ for index, step in enumerate(steps, 1):
+ call = {"name": step["tool"], "args": step["args"], "effect": step["effect"], "ok": False, "ref": None}
+ turn["toolCalls"].append(call)
+ try:
+ args = _fill(step["args"], refs, index)
+ call["args"] = args
+ if "sources" in step and step["sources"] is not None:
+ _merge_sources(session, turn, step["sources"])
+ elif "sources" in step:
+ turn["artifactSourcesUnknown"] = True
+ token = _PRODUCING_TURN.set((session, turn))
+ import routes_query as query
+ context_token = query._AGENT_TURN.set(step.get("context") or {})
+ door_token = query._AGENT_DOOR.set(door)
+ try:
+ import assistant_write_preview
+ if args != step.get("resolvedArgs"):
+ raise ValueError("An earlier step no longer matches this preview. Ask again.")
+ result = assistant_write_preview.apply(session, step)
+ _observe_sources(session, turn, step["tool"], args, result)
+ finally:
+ _PRODUCING_TURN.reset(token)
+ query._AGENT_TURN.reset(context_token)
+ query._AGENT_DOOR.reset(door_token)
+ reason = (_refusal(result) if isinstance(result, dict)
+ and (result.get("ok") is False or result.get("refused")) else None)
+ except Exception as exc:
+ reason = _sentence(exc)
+ if reason is not None:
+ head = f"Step {index} of {len(steps)} did not run: {reason.rstrip('. ')}."
+ tail = (" Ran before it: " + " ".join(_past(line) for line in _capped(done))
+ if done else " Nothing was changed.")
+ return _result(refused=head + tail, turn=turn)
+ ref = _ref(result)
+ call.update(ok=True, ref=ref)
+ if ref is not None:
+ refs[step["ref"]] = ref
+ _after_dispatch(session, door, step["tool"], args, result, call, turn, step["effect"])
+ done.extend(step["lines"])
+ return _result(" ".join(["Done.", *(_past(line) for line in _capped(done))]), turn=turn)
+
+
def _ref(result):
if not isinstance(result, dict):
return None
@@ -293,7 +798,9 @@ def _ref(result):
return ids[0] if isinstance(ids, list) and len(ids) == 1 else None
-def _record_artifact(session, door, name, args, result):
+def _record_artifact(session, door, name, args, result, *, sources=_UNSET):
+ if name == "agent_message":
+ return None
try:
import assistant_artifacts
except ImportError:
@@ -303,6 +810,10 @@ def _record_artifact(session, door, name, args, result):
"view" if name.startswith("view_") else
"schedule" if name.startswith("schedule_") or name == "reminder_create" else "run")
value = result if isinstance(result, dict) else {}
+ if sources is _UNSET:
+ proof = {}
+ _observe_sources(session, proof, name, args, result)
+ sources = _turn_sources(proof)
view = args.get("view") if isinstance(args.get("view"), dict) else {}
made = next((value[key] for key in ("workbook", "view", "schedule", "application")
if isinstance(value.get(key), dict)), {})
@@ -323,9 +834,13 @@ def _record_artifact(session, door, name, args, result):
cursor = page.get("nextCursor")
if cursor is None:
break
- return assistant_artifacts.record(session.runtime, session.uname, {
+ artifact_id = assistant_artifacts.record(session.runtime, session.uname, {
"kind": kind, "ref": str(ref) if ref is not None else None, "title": _plain(title),
- "door": door, "toolCall": {"name": name, "args": copy.deepcopy(args)}, "createdAt": time.time()})
+ "door": door, "toolCall": {"name": name, "args": copy.deepcopy(args)}, "createdAt": time.time(),
+ "sources": sources, "amazon": sources is None or any(key.startswith("ut_amzn_") for key in sources)})
+ if sources is None:
+ _artifact_result(session, artifact_id, result, {}, {"artifactSourcesUnknown": True})
+ return artifact_id
def execute(session, name, args, *, door, turn):
@@ -347,21 +862,33 @@ def _execute(session, name, args, *, door, turn):
return {"ok": False, "error": "Evaluation turns permit read tools only."}
if not isinstance(args, dict):
raise ValueError("Tool arguments must be an object.")
+ if waits_for_yes(door, name, args, effect):
+ held = _HELD.get()
+ if held is None:
+ return {"ok": False, "error": "On WhatsApp a change waits for the user's YES, "
+ "and this turn cannot hold one."}
+ ref = _hold(session, name, args, effect, held, turn)
+ call.update(ok=True, ref=ref, held=True)
+ return {"ok": True, "pending": True, "ref": ref, "preview": copy.deepcopy(held[-1]["lines"]),
+ "message": (f"Nothing changed yet. The user's YES applies this step. Use {ref} "
+ "wherever a later step needs the id this step creates.")}
if effect == "delete":
pending = _pending(session, door, name, args)
turn["pendingDelete"] = pending
call.update(ok=True, ref=pending["id"])
return {"ok": True, "pendingDelete": pending,
"message": "Nothing is removed until the user confirms this delete."}
- result = _dispatch(session, name, args)
+ token = _PRODUCING_TURN.set((session, turn))
+ try:
+ result = _dispatch(session, name, args)
+ finally:
+ _PRODUCING_TURN.reset(token)
if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
return result
call.update(ok=True, ref=_ref(result))
- if effect == "write":
- artifact_id = _record_artifact(session, door, name, args, result)
- if artifact_id:
- turn["artifacts"].append(artifact_id)
- return result
+ if getattr(session.runtime, "preview_only", False):
+ return result
+ return _after_dispatch(session, door, name, args, result, call, turn, effect)
except Exception as exc:
# Plugin failures are tool results too, so no tool exception escapes to a chat door.
return {"ok": False, "error": _sentence(exc)}
@@ -387,12 +914,14 @@ def cancel(rt, principal, id):
return False
-def run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None):
+def run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None,
+ attachments=None):
handle = turn_control.TurnHandle((principal["tenant"], principal["username"]), door, ())
result = None
try:
result = _run_turn(rt, principal, door, text, confirm=confirm, chat=chat,
- context=context, model=model, audit_handle=handle)
+ context=context, model=model, audit_handle=handle,
+ **({"attachments": attachments} if attachments is not None else {}))
return result
finally:
if not handle.audit_delegated and (result or {}).get("status") != "code_received" and not (confirm is None and door in {"whatsapp", "slack"}
@@ -402,9 +931,14 @@ def run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None
turn_audit.write(handle, rt, result=result)
-def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None, audit_handle=None):
+def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=None, model=None, audit_handle=None,
+ attachments=None):
if door not in DOORS:
raise ValueError("That Assistant door is not available.")
+ try:
+ attachments = _attachments(attachments)
+ except ValueError as exc:
+ return _result(refused=str(exc))
also_as = principal.get("also_as") or []
if any(member is None for member in also_as):
return _result(refused="A member of this channel has not linked a Loopable account.")
@@ -428,14 +962,21 @@ def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=Non
if confirm is not None:
pid = str(confirm)
owner = _owner(session.tenant, session.uname)
+ # WhatsApp holds every change, deletes included, so its confirm names a change.
+ noun, gone = (("change", "That change no longer exists.") if door == "whatsapp"
+ else ("delete", "That delete request no longer exists."))
if _foreign_id(pid, owner):
foreign = session.runtime.get("agent_pending_" + pid.split(".")[0]) or {}
- sentence = ("Only the person who asked can confirm this delete."
- if pid in foreign.get("pending", {}) else "That delete request no longer exists.")
+ sentence = (f"Only the person who asked can confirm this {noun}."
+ if pid in foreign.get("pending", {}) else gone)
return _result(refused=sentence)
entry = _take(session, pid)
if entry is None:
- return _result(refused="That delete request no longer exists.")
+ return _result(refused=gone)
+ if entry.get("kind") == "change":
+ if entry["expiresAt"] <= time.time():
+ return _result(refused="That change expired. Ask again to make it.")
+ return _apply_change(session, entry)
if entry["expiresAt"] <= time.time():
return _result(refused="That delete request expired. Ask again to delete it.")
turn = {"toolCalls": [{"name": entry["tool"], "args": entry["args"], "effect": "delete",
@@ -451,14 +992,20 @@ def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=Non
return _result(refused=_sentence(exc), turn=turn)
token = query._AGENT_DOOR.set(door)
memory_token = _MEMORY_BLOCK.set(memory_block(rt, principal))
- context_token = query._AGENT_CONTEXT.set(context if isinstance(context, str) else None)
+ # Set before the context: door_context names the files, user_content carries them.
+ files_token = _ATTACHMENTS.set(attachments)
+ context_token = query._AGENT_CONTEXT.set(door_context(door, context))
+ held = [] if door == "whatsapp" else None
+ held_token = _HELD.set(held)
try:
body = {"question": text}
if model is not None:
body["model"] = model
response = query._submit(body, session, chat=chat, also_as=also_as, door=door, audit_handle=audit_handle)
finally:
+ _HELD.reset(held_token)
query._AGENT_CONTEXT.reset(context_token)
+ _ATTACHMENTS.reset(files_token)
_MEMORY_BLOCK.reset(memory_token)
query._AGENT_DOOR.reset(token)
if response.get("status") in {"joined", "stopped", "paused", "code_received"}:
@@ -466,8 +1013,11 @@ def _run_turn(rt, principal, door, text, *, confirm=None, chat=None, context=Non
message = response["message"]
if door == "slack":
maybe_compact(rt, session.uname, chat=chat)
- return _result(message["content"], refused=message["content"] if message.get("reason") else None,
- turn=message)
+ result = _result(message["content"], refused=message["content"] if message.get("reason") else None,
+ turn=message)
+ if held and not result["refused"]:
+ result["pendingChange"] = _store_change(session, door, held, turn=message)
+ return result
except (external_access.ExternalAccessError, HTTPException, ValueError) as exc:
return _result(refused=_sentence(exc))
diff --git a/api/agent_tools.py b/api/agent_tools.py
index f9f1f782ccdbcb63124b5a197558a398f22ba885..06ddb07ead39369ecb765fb8281ae0fef8268e98 100644
--- a/api/agent_tools.py
+++ b/api/agent_tools.py
@@ -8,6 +8,7 @@ import copy
import importlib
import json
import logging
+import re
from core import external_tools
@@ -69,6 +70,54 @@ def load_modules():
register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
except (KeyError, TypeError, ValueError) as exc:
_LOG.info("Assistant tool entry in %s was skipped (%s)", name, type(exc).__name__)
+ # S72-T26: the directory sits outside AGENT_TOOL_MODULES, which verify_query pins exactly.
+ # A failure here must not take every turn down.
+ try:
+ import agent_directory
+ for entry in agent_directory.TOOLS:
+ register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Assistant directory tool is unavailable (%s)", type(exc).__name__)
+ # S72-T27: agent messages, outside AGENT_TOOL_MODULES for the same reason.
+ try:
+ import agent_inbox
+ for entry in agent_inbox.TOOLS:
+ register(entry["name"], entry["schema"], entry["fn"], effect=entry["effect"])
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("Assistant inbox tool is unavailable (%s)", type(exc).__name__)
+
+
+_NOT_A_NAME = r"(?!(?:me|us|my|our|the|a|an|what|how|who|which|when|why|where|about)\b)"
+_DIRECTORY = tuple(re.compile(p) for p in (
+ r"^who (?:uses|is using) loopable\b",
+ r"^who(?: is| are)? (?:in|on) (?:my|our) (?:workspace|team)\b",
+ r"^who has access to \w",
+ r"^what access does \w[\w .'-]* have\b",
+))
+_INBOX = tuple(re.compile(p) for p in (
+ r"^(?:please )?ask " + _NOT_A_NAME + r"\w+(?: \w+)? for (?:edit |view )?access to \w",
+ r"^(?:please )?request (?:edit |view )?access to \w",
+ r"^(?:please )?tell " + _NOT_A_NAME + r"\w+(?: \w+)? (?:that|to|about|we|i|our|the|my|it)\b",
+ r"^(?:please )?ask " + _NOT_A_NAME + r"\w+(?: \w+)? (?:whether|if|about) \w",
+))
+
+
+def admitted_tools(question):
+ """The tools a directory or inbox question admits without a database match, else empty."""
+ text = " ".join(str(question or "").casefold().replace("\u2019", "'").split()).strip(" ?.!")
+ if not text:
+ return frozenset()
+ if any(p.search(text) for p in _INBOX):
+ return frozenset({"workspace_people", "agent_message"})
+ try:
+ import agent_directory
+ if agent_directory.admits(question):
+ return frozenset({"workspace_people"})
+ except Exception: # noqa: BLE001
+ pass
+ if any(p.search(text) for p in _DIRECTORY):
+ return frozenset({"workspace_people"})
+ return frozenset()
def _connector_setup_link(session, args):
diff --git a/api/amazon_relational.py b/api/amazon_relational.py
index 10ad666c38a5d403fd403d323c5b99caacc73959..262492bf319ed9202a89375a82461d1596142e53 100644
--- a/api/amazon_relational.py
+++ b/api/amazon_relational.py
@@ -149,7 +149,7 @@ _QUANTITY = {"quantity", "quantity_purchased", "starting_warehouse_balance",
def _label(col):
- return col.replace("_", " ").strip().capitalize()
+ return connector_spec._label(col)
def _ftype(col, duck_type):
@@ -160,6 +160,8 @@ def _ftype(col, duck_type):
name is allowed to override. The store's `_coltype` already refuses to guess a type for text
it cannot parse; this is the presentation half of the same judgement.
"""
+ if col == "per_unit_volume":
+ return "int"
if any(col == s or col.endswith(s) for s in _DATEISH):
return "date"
if col in _MONEY or col.endswith(("_amount", "_fee")) or any(col.endswith(s) for s in _RATE_SUFFIX):
@@ -378,6 +380,7 @@ def _fields_for(cur, key):
"source": "overlay",
"default": name == pinned or name in _DEFAULT_COLUMNS or name in product,
"pinned": name == pinned,
+ **({"format": {"decimals": 4}} if name == "per_unit_volume" else {}),
}, flow="amazon_relational"))
for lookup in derived.get(name, ()):
field = {"key": lookup["key"], "label": lookup["label"], "type": "text",
@@ -525,9 +528,10 @@ def grid_source(cur, key):
for name, dtype in columns:
kind = _ftype(name, dtype)
expr = _quoted(name)
+ fractional = kind == "currency" or name == "per_unit_volume"
if kind in ("currency", "int"):
- expr = f"TRY_CAST({expr} AS {'DOUBLE' if kind == 'currency' else 'BIGINT'})"
- cols[name] = (expr, {"currency": _number, "int": _integer}.get(kind, _text))
+ expr = f"TRY_CAST({expr} AS {'DOUBLE' if fractional else 'BIGINT'})"
+ cols[name] = (expr, _number if fractional else {"int": _integer}.get(kind, _text))
# S67-T30: the product lookups bind like any mirror column, so a filter (`=` a parent), a
# group (count by parent) and a sort compile against them in SQL with no per-row Python.
for lookup in lookups(cur, key, names):
diff --git a/api/application_registry.py b/api/application_registry.py
index fb032ee681feacf5a6ad55212c140f589ae181fc..ac9c2d08eb5011c085d61f56366087b60de5b11e 100644
--- a/api/application_registry.py
+++ b/api/application_registry.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import copy
import json
-from core import write_execution
+from core import shares, write_execution
from modules.finance_apps import (finance_application as _finance_application,
finance_applications as _finance_applications,
@@ -74,6 +74,55 @@ class ApplicationError(ValueError):
pass
+#: R103: the one sentence a second App of a template is refused with. No dash: it reaches a screen.
+APP_EXISTS_MESSAGE = "You already have this App."
+
+
+class ApplicationExistsError(ApplicationError):
+ """The caller already owns an App of this template; `existing` is its {id, name}."""
+
+ def __init__(self, existing=None):
+ super().__init__(APP_EXISTS_MESSAGE)
+ self.existing = existing
+
+
+def template_identity(app):
+ """The template an App counts against: route, catalog or finance:; None for no template."""
+ if not isinstance(app, dict):
+ return None
+ kind = str(app.get("templateKind") or "")
+ if kind == FINANCE_TEMPLATE_KIND:
+ key = str(app.get("financeKey") or "")
+ return f"{FINANCE_TEMPLATE_KIND}:{key}" if key else None
+ return kind if kind in APPLICATION_WIZARD_TEMPLATE_KINDS else None
+
+
+def _own_template_app(applications, user, identity):
+ """R103: the caller's OWN live App of `identity`; shared and retired Apps never count."""
+ if not identity:
+ return None
+ for app in applications.values():
+ if (isinstance(app, dict) and app.get("createdBy") == user
+ and app.get("retired") is not True and template_identity(app) == identity):
+ return app
+ return None
+
+
+def own_template_apps(runtime, user):
+ """{template identity: {id, name}} of the caller's own Apps, for the template picker."""
+ owned = {}
+ apps = sorted((app for app in load(runtime)["applications"].values() if isinstance(app, dict)),
+ key=lambda app: (str(app.get("createdAt") or ""), str(app.get("id") or "")))
+ for app in apps:
+ identity = template_identity(app)
+ if (identity and identity not in owned and app.get("createdBy") == user
+ and app.get("retired") is not True):
+ owned[identity] = {"id": app.get("id"), "name": app.get("name"),
+ "deepLink": app.get("deepLink"),
+ "sourceDatabase": app.get("sourceDatabase")}
+ return owned
+
+
def template_contracts():
"""The trusted renderer contracts offered by the Application creation flow."""
return [copy.deepcopy(_TEMPLATE_CONTRACTS[kind]) for kind in APPLICATION_WIZARD_TEMPLATE_KINDS]
@@ -89,11 +138,8 @@ def finance_applications(may_open=None):
return _finance_applications(may_open=may_open)
-# R6: Finance records are read-only projections of finance_apps.py, never validated, created,
-# mutated, or persisted. Adding "finance" to APPLICATION_TYPES buys nothing and weakens
-# validate_application's governed type vocabulary.
-# This remains true for the SEEDED six. Users may now persist their own Finance applications
-# through templateKind, pointing to the same trusted surface without modifying those projections.
+# R102: the App home lists no code projection. These records name the pre-wave Finance tiles, so
+# the copy migration and routes_module_index can map their ids; nav_applications never returns them.
def finance_application_records(may_open=None):
"""Project the grant-filtered Finance catalogue as seeded Application records."""
return [
@@ -242,6 +288,52 @@ def may_edit(app, user, is_admin=False):
return bool(is_admin or (isinstance(app, dict) and app.get("createdBy") == user))
+def _listed(app, user):
+ """R102: the App home lists what the caller owns or was shared, for an Administrator too."""
+ if not isinstance(app, dict) or app.get("retired") is True:
+ return False
+ if app.get("createdBy") == user:
+ return True
+ share = app.get("share") if isinstance(app.get("share"), dict) else {}
+ return share.get("mode") == "tenant" or user in set(share.get("users") or ())
+
+
+def _is_finance(app):
+ return isinstance(app, dict) and app.get("templateKind") == FINANCE_TEMPLATE_KIND
+
+
+def _finance_permission(app):
+ try:
+ return _finance_application(str(app.get("financeKey") or ""))["permissionKey"]
+ except KeyError:
+ return None
+
+
+def _account_wall(runtime, user_record):
+ """The `deps.Session.require` predicate for one account, without a request."""
+ from core import perm_scope
+ config = getattr(getattr(runtime, "tenant", None), "config", None) or {}
+ modules = config.get("modules", "all") if isinstance(config, dict) else "all"
+
+ def may_open(key):
+ if not perm_scope.nav_may_open(user_record, key, st=runtime):
+ return False
+ return modules == "all" or str(key) in {str(item) for item in (modules or [])}
+ return may_open
+
+
+def _user_wall(runtime, user):
+ """Resolve one username's wall from the account registry; fail closed on any read error."""
+ try:
+ from core import users
+ record = (users.registry() or {}).get(user)
+ if not isinstance(record, dict) or record.get("active") is False:
+ return lambda _key: False
+ return _account_wall(runtime, users._public(user, record))
+ except Exception:
+ return lambda _key: False
+
+
def _compat(raw):
values=[]
for item in raw if isinstance(raw, (list, tuple)) else ():
@@ -470,11 +562,8 @@ def _public(app, user, is_admin=False, *, allowed_databases=None, target_databas
row["starred"] = user in (app.get("starredBy") or ())
row["isDefault"] = bool(is_default)
if row.get("templateKind") == FINANCE_TEMPLATE_KIND:
- # The database-bound mutation doors cannot edit Finance definitions. Honour that in
- # every card rather than displaying controls that can only refuse.
- row["capabilities"].update({key: False for key in (
- "edit", "share", "delete", "duplicate", "star", "default")})
- row["starred"] = False
+ # A Finance App is a user's own copy: owner controls apply. Defaults bind a database.
+ row["capabilities"]["default"] = False
row["isDefault"] = False
target_database = target_database if target_database in compatible else (compatible[0] if compatible else None)
row["openTarget"]={"kind":"application","id":row["id"],"type":row["type"],
@@ -514,14 +603,28 @@ def dependent_view_counts(runtime, database):
def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starred=None,
- allowed_databases=None):
+ allowed_databases=None, may_open=None):
+ """List Applications. Unfiltered is the App home; a database filter is how a View resolves."""
doc = load(runtime)
+ walls = []
+
+ def finance_open(app):
+ # Hidden, never deleted, while the caller's wall refuses the Finance permission key.
+ if not walls:
+ walls.append(may_open if callable(may_open) else _user_wall(runtime, user))
+ key = _finance_permission(app)
+ return bool(key and walls[0](key))
+
rows=[]
for app in doc["applications"].values():
- if not may_read(app,user,is_admin): continue
- if database and database not in (app.get("compatibleDatabases") or ()): continue
+ if database:
+ # A View resolves its App only through this read, so a retired seed stays listed here.
+ if not may_read(app,user,is_admin): continue
+ if database not in (app.get("compatibleDatabases") or ()): continue
+ elif not _listed(app, user): continue
if (app.get("templateKind") != FINANCE_TEMPLATE_KIND
and not _allowed(app.get("compatibleDatabases"), allowed_databases)): continue
+ if _is_finance(app) and not finance_open(app): continue
if kind and app.get("type") != kind: continue
if starred is not None and bool(user in (app.get("starredBy") or ())) != bool(starred): continue
default_key = f"{database}::{app.get('type')}" if database else ""
@@ -539,8 +642,8 @@ def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starre
def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_databases=None):
- """The ONE generic navigation read for stored and seeded Application records (R6)."""
- rows = [{"id": app["id"], "name": app.get("name"),
+ """The App home read: stored records the caller owns or was shared, never a code projection."""
+ return [{"id": app["id"], "name": app.get("name"),
"type": app.get("type"), "templateKind": app.get("templateKind"),
"deepLink": app.get("deepLink"),
"origin": "tenant",
@@ -550,8 +653,8 @@ def nav_applications(runtime, user, is_admin=False, *, may_open=None, allowed_da
"capabilities": app.get("capabilities"), "starred": app.get("starred"),
"isDefault": app.get("isDefault")}
for index, app in enumerate(list_apps(runtime, user, is_admin,
- allowed_databases=allowed_databases))]
- return rows + finance_application_records(may_open=may_open)
+ allowed_databases=allowed_databases,
+ may_open=may_open))]
def _build_application(tenant, user, payload, *, semantic_records=None, field_contracts=None,
@@ -593,32 +696,55 @@ def create(runtime, tenant, user, payload, *, semantic_records=None, field_contr
tenant, user, payload, semantic_records=semantic_records, field_contracts=field_contracts,
allowed_databases=allowed_databases)
app_id = app["id"]
+ identity = template_identity(app)
def apply(raw):
doc=_clean_doc(raw)
if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
+ # R103: counted on the document being written, so two concurrent creates cannot both pass.
+ held = _own_template_app(doc["applications"], user, identity)
+ if held is not None:
+ raise ApplicationExistsError({"id": held.get("id"), "name": held.get("name")})
doc["applications"][app_id]=app; return doc
runtime.update(_KEY,apply)
return _public(app,user,allowed_databases=allowed_databases)
-def ensure_route_application(runtime, tenant):
- """R15: migrate route references once per tenant, never from an Application read."""
- from core import route_system
-
- # list_routes() suppresses read errors; an unknown count must remain retryable at boot.
+def _read_strict(runtime, key):
+ """Read one document so that a failure RAISES; the lenient `runtime.get` answers {} instead."""
# ⛔ D-260: `runtime.get` is the LENIENT display read. A failed hub read there answers {},
# which counted as 0 routes and wrote the one-shot marker as "no_routes", so a tenant WITH
# routes never got its App. Read STRICTLY (the timeseries_retirement._read door) so a failure
- # raises into the retryable skip below. Only a double exposing no strict door reads via get.
+ # raises into the retryable skip. Only a double exposing no strict door reads via get.
+ strict = getattr(runtime, "_read_strict", None)
+ if callable(strict):
+ return strict(key)
+ if callable(getattr(runtime, "_store", None)) and callable(getattr(runtime, "store_key", None)):
+ return runtime._store()._read_strict(runtime.store_key(key))
+ return runtime.get(key)
+
+
+def ensure_route_application(runtime, tenant, *, accounts=None, wall=None):
+ """R15: boot migrations, once per tenant, never from an Application read.
+
+ Runs the Routing seed migration, then `ensure_user_app_copies`, and folds both into one dict.
+ """
+ result = _ensure_route_seed(runtime, tenant)
+ copies = ensure_user_app_copies(runtime, tenant, accounts=accounts, wall=wall)
+ folded = dict(result)
+ folded["userCopies"] = copies
+ note = "user copies " + copies["outcome"] + (
+ ": " + copies["reason"] if copies.get("reason") else "")
+ folded["reason"] = result["reason"] + "; " + note if result.get("reason") else note
+ return folded
+
+
+def _ensure_route_seed(runtime, tenant):
+ """R15: migrate route references once per tenant into the seeded Routing App."""
+ from core import route_system
+
+ # list_routes() suppresses read errors; an unknown count must remain retryable at boot.
try:
- strict = getattr(runtime, "_read_strict", None)
- if callable(strict):
- route_doc = strict(route_system.STORE_KEY)
- elif callable(getattr(runtime, "_store", None)) and callable(
- getattr(runtime, "store_key", None)):
- route_doc = runtime._store()._read_strict(runtime.store_key(route_system.STORE_KEY))
- else:
- route_doc = runtime.get(route_system.STORE_KEY)
+ route_doc = _read_strict(runtime, route_system.STORE_KEY)
if route_doc is None:
routes = []
elif isinstance(route_doc, dict):
@@ -668,8 +794,184 @@ def ensure_route_application(runtime, tenant):
return result
+_COPIES = "userAppCopies"
+_APP_INDEX_KEY = "module_index_app"
+
+
+def _active_accounts(tenant):
+ """`[(username, public user record)]` for this tenant's active accounts; raises if unreadable."""
+ from core import users
+ if not isinstance(users.registry(), dict):
+ raise ApplicationError("the account registry is unreadable")
+ return [(name, users._public(name, record)) for name, record in users._tenant_accounts(tenant)]
+
+
+def _copy_id(tenant, old_id, username):
+ """One stable id per (tenant, old App id, account), so a rerun cannot duplicate a copy."""
+ import hashlib
+ digest = hashlib.sha256(f"{tenant}\x1f{old_id}\x1f{username}".encode("utf-8")).hexdigest()
+ return "app_" + digest[:16]
+
+
+def _seed_route_app(doc):
+ """The tenant-shared Routing App the route migration seeded, or None."""
+ seed_id = ((doc.get("migrations") or {}).get("routeApplication") or {}).get("appId")
+ seed = doc["applications"].get(seed_id) if seed_id else None
+ if (isinstance(seed, dict) and seed.get("createdBy") == "loopable"
+ and (seed.get("share") or {}).get("mode") == "tenant"):
+ return seed
+ return None
+
+
+def _move_placements(runtime, moves):
+ """Move each account's App-home folder placement from an old App id to its copy id."""
+ doc = _read_strict(runtime, _APP_INDEX_KEY)
+ owners = (doc or {}).get("users") if isinstance(doc, dict) else None
+ if not isinstance(owners, dict):
+ return 0
+ if not any(old in ((owners.get(name) or {}).get("itemFolders") or {})
+ for name, pairs in moves.items() for old in pairs):
+ return 0
+ moved = [0]
+
+ def apply(raw):
+ state = copy.deepcopy(raw) if isinstance(raw, dict) else raw
+ buckets = state.get("users") if isinstance(state, dict) else None
+ for name, pairs in moves.items():
+ bucket = buckets.get(name) if isinstance(buckets, dict) else None
+ placed = bucket.get("itemFolders") if isinstance(bucket, dict) else None
+ if not isinstance(placed, dict):
+ continue
+ changed = False
+ for old, new in pairs.items():
+ if old in placed:
+ folder = placed.pop(old)
+ placed.setdefault(new, folder)
+ changed = True
+ moved[0] += 1
+ if changed:
+ # A client holding the old revision must reload before it writes folders again.
+ bucket["rev"] = int(bucket.get("rev") or 0) + 1
+ return state
+ runtime.update(_APP_INDEX_KEY, apply)
+ return moved[0]
+
+
+def ensure_user_app_copies(runtime, tenant, *, accounts=None, wall=None):
+ """R102: give every account its own copy of each App it could see, once per tenant.
+
+ Finance tiles become stored Finance copies for accounts whose wall admits the permission key.
+ The seeded Routing App becomes one private copy per active account and is then retired: hidden
+ from the App home but kept, so a View holding its id still resolves. Folder placements move to
+ the copy ids. A failed read returns a retryable `skipped` and writes no marker.
+ """
+ try:
+ current = _read_strict(runtime, _KEY)
+ if current is not None and not isinstance(current, dict):
+ raise ApplicationError("the Application registry must be an object")
+ except Exception as exc:
+ return {"outcome": "skipped", "reason": f"registry read failed: {type(exc).__name__}: {exc}"}
+ migrations = _clean_doc(current).get("migrations") or {}
+ marker = migrations.get(_COPIES)
+ if isinstance(marker, dict) and marker.get("state") == "done":
+ return {"outcome": "skipped", "reason": "user App copies already applied"}
+ if "routeApplication" not in migrations:
+ return {"outcome": "skipped", "reason": "route Application migration pending"}
+
+ if isinstance(marker, dict) and isinstance(marker.get("moves"), dict):
+ moves = copy.deepcopy(marker["moves"])
+ copies = int(marker.get("copies") or 0)
+ else:
+ try:
+ people = list(_active_accounts(tenant) if accounts is None else accounts)
+ wall = wall or (lambda record: _account_wall(runtime, record))
+ plan = []
+ for username, record in people:
+ may_open = wall(record)
+ admitted = [app for app in _finance_applications()
+ if may_open(app["permissionKey"])]
+ plan.append((str(username), admitted))
+ except Exception as exc:
+ return {"outcome": "skipped",
+ "reason": f"account read failed: {type(exc).__name__}: {exc}"}
+ if not plan:
+ return {"outcome": "skipped", "reason": "no active accounts"}
+ landed = {}
+
+ def apply(raw):
+ doc = _clean_doc(raw)
+ state = doc.setdefault("migrations", {})
+ if isinstance(state.get(_COPIES), dict):
+ landed.update(copy.deepcopy(state[_COPIES]))
+ return raw
+ now = write_execution.utcnow().isoformat()
+ seed = _seed_route_app(doc)
+ moves, made = {}, 0
+ for username, admitted in plan:
+ pairs = moves.setdefault(username, {})
+ for index, app in enumerate(_finance_applications()):
+ if app not in admitted:
+ continue
+ old_id = f"finance_{app['key']}"
+ new_id = _copy_id(tenant, old_id, username)
+ pairs[old_id] = new_id
+ if new_id in doc["applications"]:
+ continue
+ record = _build_application(
+ tenant, username,
+ {"templateKind": FINANCE_TEMPLATE_KIND, "financeKey": app["key"],
+ "name": app["navLabel"], "navPlacement": {"section": "app", "order": index}},
+ allowed_databases=set())
+ record.update(id=new_id, migratedFrom=old_id)
+ doc["applications"][new_id] = record
+ made += 1
+ if seed is not None:
+ new_id = _copy_id(tenant, seed["id"], username)
+ pairs[seed["id"]] = new_id
+ if new_id not in doc["applications"]:
+ record = copy.deepcopy(seed)
+ for key in ("retired", "retiredAt"):
+ record.pop(key, None)
+ record.update(
+ id=new_id, createdBy=username, share={"mode": "private", "users": []},
+ starredBy=[username] if username in (seed.get("starredBy") or ()) else [],
+ createdAt=now, updatedAt=now, revision=1, migratedFrom=seed["id"])
+ doc["applications"][new_id] = record
+ made += 1
+ if seed is not None:
+ seed.update(retired=True, retiredAt=now)
+ for key in [key for key, value in doc["defaults"].items() if value == seed["id"]]:
+ doc["defaults"].pop(key)
+ state[_COPIES] = {"state": "copied", "at": now, "accounts": len(plan),
+ "copies": made, "seed": seed["id"] if seed else None,
+ "moves": moves}
+ landed.update(copy.deepcopy(state[_COPIES]))
+ return doc
+ runtime.update(_KEY, apply)
+ if landed.get("state") == "done":
+ return {"outcome": "skipped", "reason": "user App copies already applied"}
+ moves, copies = landed.get("moves") or {}, int(landed.get("copies") or 0)
+
+ try:
+ moved = _move_placements(runtime, moves)
+ except Exception as exc:
+ return {"outcome": "skipped",
+ "reason": f"folder placement move failed: {type(exc).__name__}: {exc}"}
+ def finish(raw):
+ doc = _clean_doc(raw)
+ state = (doc.get("migrations") or {}).get(_COPIES)
+ if not isinstance(state, dict) or state.get("state") == "done":
+ return raw
+ state.update(state="done", moved=moved, doneAt=write_execution.utcnow().isoformat())
+ return doc
+ runtime.update(_KEY, finish)
+ return {"outcome": "copied", "copies": copies, "accounts": len(moves), "moved": moved,
+ "reason": f"{copies} copies for {len(moves)} accounts, {moved} folder placements moved"}
+
+
def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
- allowed_databases=None, target_database=None):
+ allowed_databases=None, target_database=None, expect=None):
+ """Apply a patch, optionally requiring the current share's mode and users to match `expect`."""
patch=patch if isinstance(patch,dict) else {}; landed={}
immutable = sorted(set(patch) & {
"id", "tenant", "type", "templateKind", "sourceDatabase", "fieldMap", "navPlacement",
@@ -681,7 +983,7 @@ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
def apply(raw):
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
if not app: raise ApplicationError("application does not exist")
- if not _allowed(app.get("compatibleDatabases"), allowed_databases):
+ if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
raise ApplicationError("application does not exist")
if app.get("templateKind") in APPLICATION_TEMPLATE_KINDS and "compatibleDatabases" in patch:
raise ApplicationError("a template Application's sourceDatabase is immutable")
@@ -690,6 +992,17 @@ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
if not may_read(app,user,is_admin): raise PermissionError("application is not available")
elif not may_edit(app,user,is_admin):
raise PermissionError("application belongs to another user")
+ if expect is not None:
+ def share_state(value):
+ value = value if isinstance(value, dict) else {}
+ mode = str(value.get("mode") or "private")
+ return mode, _users(value.get("users")) if mode == "users" else []
+ # Compare the fresh share on every store replay before changing any Application field.
+ if share_state(app.get("share")) != share_state(expect):
+ raise shares.GrantsChanged(
+ 'this item was shared with somebody else while you were editing, so nothing '
+ 'was saved. Reopen the sharing panel to see who has access now, then make '
+ 'your change again.')
if "name" in patch:
name=" ".join(str(patch["name"] or "").split())[:120]
if not name: raise ApplicationError("application name is required")
@@ -725,30 +1038,108 @@ def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records
field_contracts=None, allowed_databases=None):
app=load(runtime)["applications"].get(app_id)
if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
- if not _allowed(app.get("compatibleDatabases"), allowed_databases):
+ if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
raise ApplicationError("application does not exist")
payload={"type":app["type"],"name":f"{app['name']} copy",
"compatibleDatabases":app.get("compatibleDatabases"),
"semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")}
- for key in ("templateKind", "sourceDatabase", "fieldMap", "navPlacement"):
+ for key in ("templateKind", "sourceDatabase", "fieldMap", "navPlacement", "financeKey"):
if key in app: payload[key]=copy.deepcopy(app[key])
return create(runtime,tenant,user,payload,
semantic_records=semantic_records, field_contracts=field_contracts,
allowed_databases=allowed_databases)
-def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None):
+_ANY_NAME = object()
+
+
+def _strip_view_refs(doc, app_id):
+ """Remove `config.application` naming `app_id` from every View in one workspace document.
+
+ Walks every top-level member, reserved ones included, and each owner's trash entries.
+ Returns the number of Views changed. Mutates `doc` in place.
+ """
+ def views_of(bucket):
+ views = bucket.get("views")
+ yield from (views.values() if isinstance(views, dict)
+ else views if isinstance(views, list) else ())
+ trash = bucket.get("trash")
+ for entry in (trash.values() if isinstance(trash, dict)
+ else trash if isinstance(trash, list) else ()):
+ if isinstance(entry, dict) and isinstance(entry.get("view"), dict):
+ yield entry["view"]
+
+ cleared = 0
+ for bucket in (doc.values() if isinstance(doc, dict) else ()):
+ if not isinstance(bucket, dict):
+ continue
+ for view in views_of(bucket):
+ config = view.get("config") if isinstance(view, dict) else None
+ ref = config.get("application") if isinstance(config, dict) else None
+ if isinstance(ref, dict) and str(ref.get("id") or "") == app_id:
+ config.pop("application")
+ cleared += 1
+ return cleared
+
+
+def clear_view_references(runtime, app_id, databases):
+ """D-2233: drop a deleted App's id from saved Views so each opens as a plain View.
+
+ Returns `(views cleared, reasons for databases not cleared)`. Never raises.
+ """
+ from core.view_templates import workspace_key
+ cleared, failed = 0, []
+ for database in dict.fromkeys(str(value or "") for value in databases or ()):
+ key = workspace_key(database)
+ if not key:
+ continue
+ try:
+ # A strict read: a failed read is reported, never counted as no reference.
+ if not _strip_view_refs(copy.deepcopy(_read_strict(runtime, key)), app_id):
+ continue
+ count = [0]
+
+ def apply(raw):
+ doc = copy.deepcopy(raw)
+ count[0] = _strip_view_refs(doc, app_id)
+ return doc if count[0] else raw
+ runtime.update(key, apply)
+ cleared += count[0]
+ except Exception as exc:
+ failed.append(f"{database}: {type(exc).__name__}")
+ return cleared, failed
+
+
+def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None,
+ confirm_name=_ANY_NAME):
+ """Delete one App record. Its databases, Views and records stay; Views lose the dead id.
+
+ `confirm_name`, when given, must equal the stored name inside the same atomic update.
+ """
+ removed = {}
+
def apply(raw):
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
if not app: raise ApplicationError("application does not exist")
- if not _allowed(app.get("compatibleDatabases"), allowed_databases):
+ if not _is_finance(app) and not _allowed(app.get("compatibleDatabases"), allowed_databases):
raise ApplicationError("application does not exist")
if not may_edit(app,user,is_admin): raise PermissionError("application belongs to another user")
- doc["applications"].pop(app_id)
+ if confirm_name is not _ANY_NAME and (
+ not isinstance(confirm_name, str) or confirm_name != app.get("name")):
+ raise ApplicationError("enter the exact App name to confirm deletion")
+ removed.update(doc["applications"].pop(app_id))
for key in list(doc["defaults"]):
if doc["defaults"][key]==app_id: doc["defaults"].pop(key)
return doc
- runtime.update(_KEY,apply); return {"deleted":app_id}
+ runtime.update(_KEY,apply)
+ result = {"deleted": app_id}
+ # After the registry write: a failed clear is reported, never an undone delete.
+ cleared, failed = clear_view_references(runtime, app_id, removed.get("compatibleDatabases"))
+ if cleared:
+ result["viewsCleared"] = cleared
+ if failed:
+ result["viewsNotCleared"] = "; ".join(failed)
+ return result
def set_default(runtime, database, kind, app_id, user, is_admin=False, *, allowed_databases=None):
@@ -775,11 +1166,12 @@ def resolve_default(runtime, database, kind, user, is_admin=False, *, allowed_da
raise PermissionError("that database is not available")
doc=load(runtime); explicit=doc["defaults"].get(f"{database}::{kind}")
app=doc["applications"].get(explicit)
- if app and may_read(app,user,is_admin) and database in (app.get("compatibleDatabases") or ()) and app.get("type")==kind:
+ if app and app.get("retired") is not True and may_read(app,user,is_admin) and database in (app.get("compatibleDatabases") or ()) and app.get("type")==kind:
return {"resolution":"explicit","application":_public(
app,user,is_admin,allowed_databases=allowed_databases,target_database=database,
is_default=True)}
- matches=[x for x in doc["applications"].values() if x.get("type")==kind and database in (x.get("compatibleDatabases") or ()) and may_read(x,user,is_admin)]
+ # A retired seed still resolves by id but is never offered as the latest default.
+ matches=[x for x in doc["applications"].values() if x.get("type")==kind and database in (x.get("compatibleDatabases") or ()) and may_read(x,user,is_admin) and x.get("retired") is not True]
matches.sort(key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
return {"resolution":"latest" if matches else "blank",
"application":_public(matches[0],user,is_admin,allowed_databases=allowed_databases,
diff --git a/api/artifact_share.py b/api/artifact_share.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e5ac6a68ba18f2d48c46c7710b981a10ebe3098
--- /dev/null
+++ b/api/artifact_share.py
@@ -0,0 +1,257 @@
+"""Signed frozen artifact links enforce phone binding and Amazon sign-in (C7, R85, R86, R97)."""
+from __future__ import annotations
+
+import base64
+import binascii
+import hmac
+import json
+import os
+import re
+import secrets
+import time
+from hashlib import sha256
+
+import assistant_artifacts
+import loopy_links
+
+TTL_S = 86400
+# A separate key derived from the session secret, so a share token never verifies as a session.
+_KEY_LABEL = b"loopable artifact share v1"
+_SHARE_ID = re.compile(r"[A-Za-z0-9_\-]{22}")
+_PART = re.compile(r"[A-Za-z0-9_\-]+")
+MAX_TOKEN = 600
+SENT = "A new link is on its way to your WhatsApp."
+ALREADY = "A new link was already sent to your WhatsApp."
+STILL_OPEN = "This link still works. Open it again."
+NOT_VALID = "This link is not valid."
+NOT_SENT = "We could not send a new link. Ask Loopy on WhatsApp for one."
+LINK_TEXT = "Here is your new Loopable link: {link}"
+
+
+class ShareRefused(ValueError):
+ """A refused signed link with an optional normal artifact sign-in destination."""
+
+ def __init__(self, message, *, link=None):
+ super().__init__(message)
+ self.link = link
+
+
+def _secret() -> bytes | None:
+ raw = os.environ.get("AIOS_SESSION_SECRET") or ""
+ return hmac.new(raw.encode("utf-8"), _KEY_LABEL, sha256).digest() if raw else None
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def _unb64(text: str) -> bytes:
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
+
+
+def _sign(key: bytes, payload: bytes) -> str:
+ return _b64(hmac.new(key, b"token:" + payload, sha256).digest())
+
+
+def _phone_tag(key: bytes, phone: str) -> str:
+ return _b64(hmac.new(key, b"phone:" + phone.encode("utf-8"), sha256).digest()[:12])
+
+
+def _doc_key(share_id: str) -> str:
+ return f"artifact_share_{share_id}"
+
+
+def needs_sign_in(row) -> bool:
+ """Require normal sign-in for Amazon content and unknown provenance under R86."""
+ if not isinstance(row, dict):
+ return True
+ try:
+ return assistant_artifacts.c7(row)["amazon"] is not False
+ except Exception:
+ return True
+
+
+def _lookup(phone):
+ import whatsapp_identity
+ return whatsapp_identity.lookup(phone)
+
+
+def _eligible(rt, artifact_id, phone):
+ """Return the owner's username, or raise ShareRefused with a plain reason."""
+ if not isinstance(phone, str) or not phone:
+ raise ShareRefused("This number is not connected to Loopable.")
+ bound = _lookup(phone)
+ if not bound:
+ raise ShareRefused("This number is not connected to Loopable.")
+ tenant, owner = bound
+ if tenant != getattr(rt, "key", None):
+ raise ShareRefused("This number belongs to another workspace.")
+ row = assistant_artifacts.get(rt, owner, artifact_id)
+ if row is None:
+ raise ShareRefused("That item is not yours.")
+ if row.get("status") != "active":
+ raise ShareRefused("That item is no longer available.")
+ if needs_sign_in(row):
+ raise ShareRefused("That item requires sign in to open.", link=loopy_links.artifact_link(row["id"]))
+ if row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"} or not row.get("frozen_at"):
+ raise ShareRefused("That item has no frozen content to share.")
+ return owner
+
+
+def _mint(rt, artifact_id, owner, phone, key, now):
+ share_id = _b64(secrets.token_bytes(16))
+ expires = int(now) + TTL_S
+ record = {"artifact_id": artifact_id, "owner": owner, "phone": phone,
+ "expires": expires, "created": int(now)}
+ rt.update(_doc_key(share_id), lambda _raw: dict(record), flush="sync")
+ claims = {"t": rt.key, "s": share_id, "a": artifact_id, "p": _phone_tag(key, phone), "x": expires}
+ payload = json.dumps(claims, separators=(",", ":"), sort_keys=True).encode("utf-8")
+ return f"{_b64(payload)}.{_sign(key, payload)}"
+
+
+def signed_link(rt, artifact_id, *, phone, now=None):
+ """Mint a signed link, or refuse with a normal artifact link when sign-in is required."""
+ key = _secret()
+ if key is None or loopy_links.public_base() is None:
+ return None
+ owner = _eligible(rt, artifact_id, phone)
+ token = _mint(rt, artifact_id, owner, phone, key, time.time() if now is None else now)
+ return loopy_links.shared_artifact_link(token)
+
+
+def _claims(token, key):
+ """The verified claims of a token, or None for a bad shape or signature."""
+ if not isinstance(token, str) or len(token) > MAX_TOKEN or token.count(".") != 1:
+ return None
+ body, sig = token.split(".")
+ if not _PART.fullmatch(body) or not _PART.fullmatch(sig):
+ return None
+ try:
+ payload = _unb64(body)
+ except (binascii.Error, ValueError):
+ return None
+ if _b64(payload) != body:
+ return None
+ if not hmac.compare_digest(sig, _sign(key, payload)):
+ return None
+ try:
+ claims = json.loads(payload.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError):
+ return None
+ shape = {"t": str, "s": str, "a": str, "p": str, "x": int}
+ if not isinstance(claims, dict) or set(claims) != set(shape) or not all(
+ isinstance(claims[name], kind) and not isinstance(claims[name], bool)
+ for name, kind in shape.items()):
+ return None
+ return claims if _SHARE_ID.fullmatch(claims["s"]) else None
+
+
+def _runtime(slug):
+ from harness import runtime as _rt
+ try:
+ if slug not in _rt.known_tenants():
+ return None
+ rt = _rt.get_runtime(slug)
+ except Exception:
+ return None
+ return rt if getattr(rt, "key", None) == slug else None
+
+
+def resolve(token, now=None):
+ """Return ok, expired, sign_in or invalid; only ok carries anonymous content rights."""
+ invalid = {"state": "invalid", "rt": None, "share": None, "row": None}
+ key = _secret()
+ if key is None:
+ return invalid
+ claims = _claims(token, key)
+ if claims is None:
+ return invalid
+ rt = _runtime(claims["t"])
+ if rt is None or getattr(rt, "key", None) != claims["t"]:
+ return invalid
+ try:
+ share = rt.get(_doc_key(claims["s"]))
+ except Exception:
+ return invalid
+ if (not isinstance(share, dict) or share.get("artifact_id") != claims["a"]
+ or share.get("expires") != claims["x"] or not isinstance(share.get("phone"), str)
+ or not isinstance(share.get("owner"), str)
+ or not hmac.compare_digest(_phone_tag(key, share["phone"]), claims["p"])):
+ return invalid
+ try:
+ row = assistant_artifacts.get(rt, share["owner"], claims["a"])
+ except Exception:
+ return invalid
+ if (row is None or row.get("id") != claims["a"] or row.get("status") != "active"
+ or row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"}
+ or not row.get("frozen_at")):
+ return invalid
+ now = time.time() if now is None else now
+ created = share.get("created")
+ if (not isinstance(created, int) or isinstance(created, bool)
+ or claims["x"] - created != TTL_S or now < created):
+ return invalid
+ try:
+ if _lookup(share["phone"]) != (rt.key, share["owner"]):
+ return invalid
+ except Exception:
+ return invalid
+ if needs_sign_in(row):
+ return {"state": "sign_in", "rt": rt, "share": share,
+ "row": {"id": row["id"], "status": row["status"]}}
+ if now >= claims["x"]:
+ return {"state": "expired", "rt": rt, "share": share, "row": row}
+ return {"state": "ok", "rt": rt, "share": share, "row": row}
+
+
+def _send(phone, text, link, *, tenant, username):
+ """Send inside the 24 hour window as text, outside it as the approved template."""
+ import telnyx_whatsapp
+ send = getattr(telnyx_whatsapp, "send_reply", None)
+ kwargs = {"purpose": "artifact_link", "tenant": tenant, "username": username}
+ if send is not None:
+ return send(phone, text, link=link, **kwargs)
+ if telnyx_whatsapp.within_window(phone):
+ return telnyx_whatsapp.send_text(phone, text, **kwargs)
+ return telnyx_whatsapp.send_template(phone, telnyx_whatsapp.ping_template(), [text, link], **kwargs)
+
+
+def request_again(token, now=None):
+ """Send a fresh link for an expired token to the same number; return {"outcome", "message"}."""
+ now = time.time() if now is None else now
+ found = resolve(token, now)
+ if found["state"] == "ok":
+ return {"outcome": "still_open", "message": STILL_OPEN}
+ if found["state"] != "expired":
+ return {"outcome": "invalid", "message": NOT_VALID}
+ rt, share = found["rt"], found["share"]
+ share_id = _claims(token, _secret())["s"]
+ try:
+ owner = _eligible(rt, share["artifact_id"], share["phone"])
+ except ShareRefused:
+ return {"outcome": "refused", "message": NOT_VALID}
+ if owner != share["owner"]:
+ return {"outcome": "refused", "message": NOT_VALID}
+ claimed = []
+
+ def claim(raw):
+ claimed.clear()
+ raw = dict(raw or {})
+ if raw.get("renewed") is None:
+ raw["renewed"] = int(now)
+ claimed.append(True)
+ return raw
+ # One fresh link per expired token, so a visitor cannot flood the number.
+ rt.update(_doc_key(share_id), claim, flush="sync")
+ if not claimed:
+ return {"outcome": "already", "message": ALREADY}
+ try:
+ link = signed_link(rt, share["artifact_id"], phone=share["phone"], now=now)
+ delivery = _send(share["phone"], LINK_TEXT.format(link=link), link,
+ tenant=rt.key, username=owner) if link else None
+ if isinstance(delivery, dict) and delivery.get("status") in {"sandbox", "sent"}:
+ return {"outcome": "sent", "message": SENT}
+ except Exception:
+ pass
+ rt.update(_doc_key(share_id), lambda raw: {**(raw or {}), "renewed": None}, flush="sync")
+ return {"outcome": "failed", "message": NOT_SENT}
diff --git a/api/artifact_snapshot.py b/api/artifact_snapshot.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b260b538d60425d718b82a44bbd1d716705c4b6
--- /dev/null
+++ b/api/artifact_snapshot.py
@@ -0,0 +1,466 @@
+"""S72-T68: freeze what a turn made or answered into one `snapshot` artifact (C7, R96, A3)."""
+import copy
+import datetime
+import importlib
+import json
+import logging
+import re
+import time
+
+import assistant_artifacts
+
+LOG = logging.getLogger(__name__)
+
+ROW_LIMIT = 200
+MAX_CONTENT_BYTES = 256 * 1024
+MAX_SUMMED_COLUMNS = 15
+MAX_SHEET_COLUMNS = 52
+RECORD_TOOLS = frozenset({"query_database", "database_object"})
+SUMMED_TYPES = frozenset({"currency", "int"})
+OPEN_SENTENCE = "Open in Loopable to see every row."
+_SHEET_READS = {"sheet_read_cells", "sheet_delete_tab"}
+_OBJECT_READS = {"workbook_object": {"list", "get", "export"}, "worksheet_object": {"list", "get"},
+ "range_object": {"read"}, "calculation_object": set()}
+_ADDR = re.compile(r"([A-Z]{1,3})([0-9]{1,7})")
+
+
+def _module(name):
+ """Import a live reader by name at call time; a fixture swaps it in `sys.modules`."""
+ return importlib.import_module(name)
+
+
+def _query(session, database, payload):
+ return _module("routes_external")._query_database(session, database, payload)
+
+
+def _visible_keys(session, database):
+ """The field keys the maker may read, from the Assistant read scope."""
+ scoped = _module("deps").assistant_read_scope(session, database, mode="schema")
+ return {field["key"] for field in scoped.get("fields") or ()
+ if isinstance(field, dict) and isinstance(field.get("key"), str)}
+
+
+def _authorization_scope(session, database):
+ """Resolve current field and row authority without reading source values."""
+ from core import perm_scope
+ scoped = _module("deps").assistant_read_scope(session, database, mode="schema")
+ grant = perm_scope.assistant_entry(session.user, database) or {}
+ fields = scoped.get("fields") or ()
+ audience = False
+ if database.startswith("ut_"):
+ definitions = session.runtime.get_projection("user_tables", drop=("rows",))
+ definition = definitions.get(database) if isinstance(definitions, dict) else None
+ if not isinstance(definition, dict):
+ raise ValueError("The source definition is unavailable.")
+ audience = perm_scope.audience_declared(database, st=session.runtime, defn=definition)
+ fields = definition.get("fields") or ()
+ pool = perm_scope.derive_pool_scope(session.user, database)
+ return {"database": database,
+ "fields": sorted(field["key"] for field in scoped.get("fields") or ()
+ if isinstance(field, dict) and isinstance(field.get("key"), str)),
+ "field_types": {field["key"]: field.get("type") for field in fields
+ if isinstance(field, dict) and isinstance(field.get("key"), str)},
+ "hidden": sorted(str(key) for key in grant.get("hiddenFields") or ()),
+ "filter": copy.deepcopy(grant.get("filter")) or None,
+ "pool": list(pool), "audience": audience}
+
+
+def _authorization_proof(session, sources):
+ """Bind a server-captured document to its maker, tenant and permission scopes."""
+ return {"version": 1, "tenant": session.tenant, "owner": session.uname,
+ "scopes": [_authorization_scope(session, source) for source in sources]}
+
+
+def require_permission(session, sources, content):
+ """Refuse frozen values whose current authorization cannot be proved without live rows."""
+ def refuse():
+ raise _module("deps").err(403, "assistant_forbidden",
+ "Your current permissions do not allow this snapshot.")
+
+ if sources is None or content.get("sources") != sources:
+ refuse()
+ proof = content.get("_authorization")
+ try:
+ current = _authorization_proof(session, sources)
+ except Exception:
+ refuse()
+ # Recipient membership can change independently of the rows-free permission contract.
+ if any(scope["audience"] for scope in current["scopes"]):
+ refuse()
+ if proof is not None:
+ if proof != current:
+ refuse()
+ return
+ # Legacy sheets and unknown origins cannot prove which fields supplied their displayed values.
+ if len(sources) != 1 or content.get("kind_of") not in ("records", "view", "app"):
+ refuse()
+ scope = current["scopes"][0]
+ if scope["hidden"] or scope["filter"] or any(value is not None for value in scope["pool"]):
+ refuse()
+ columns, sums = content.get("columns"), (content.get("totals") or {}).get("sum")
+ if not isinstance(columns, list) or not isinstance(sums, dict):
+ refuse()
+ visible = set(scope["fields"])
+ if (any(not isinstance(column, dict) or column.get("key") not in visible for column in columns)
+ or not set(sums).issubset(visible)):
+ refuse()
+
+
+def _load_view(session, database, view_id):
+ found = _module("routes_external")._view_context(session, database, {}).table.find_view(
+ view_id, prefer_owner=session.uname)
+ return found[1] if found else None
+
+
+def _load_workbook(session, workbook_id):
+ book = _module("core.sheets").get_workbook(session.runtime, workbook_id)
+ routes = _module("routes_sheet")
+ routes._require_reader(session, book)
+ return routes._read_for(session, book)
+
+
+def _binding_readable(session, binding, book, tab):
+ """True only when the maker can resolve this binding now."""
+ try:
+ _module("routes_sheet")._resolve_cell_binding(session, binding, book, tab.get("id"))
+ return True
+ except Exception:
+ return False
+
+
+def _now():
+ return datetime.datetime.fromtimestamp(time.time(), datetime.timezone.utc).isoformat()
+
+
+def _text(value):
+ return value.strip() if isinstance(value, str) and value.strip() else None
+
+
+def _kind_of(name, args):
+ action = args.get("action")
+ if name == "query_database" or (name == "database_object" and action == "query"):
+ return "records"
+ if name.startswith("sheet_") and name not in _SHEET_READS:
+ return "sheet"
+ if name.startswith("workbook_") and name != "workbook_object":
+ return "sheet"
+ if name in _OBJECT_READS and action not in _OBJECT_READS[name] and action != "delete":
+ return "sheet"
+ if name == "view_upsert" or (name == "view_object" and action == "upsert"):
+ return "view"
+ if name == "app_upsert":
+ return "app"
+ return None
+
+
+def _rows_sentence(shown, total, cause):
+ return f"Showing {shown:,} of {total:,} rows because {cause}. {OPEN_SENTENCE}"
+
+
+def _totals(session, database, filters, columns):
+ """Count every permitted row and sum the number columns, server side, over ALL rows."""
+ numeric = [col["key"] for col in columns if col.get("type") in SUMMED_TYPES]
+ notes = []
+ if len(numeric) > MAX_SUMMED_COLUMNS:
+ notes.append(f"Totals cover the first {MAX_SUMMED_COLUMNS} number columns.")
+ numeric = numeric[:MAX_SUMMED_COLUMNS]
+ base = {"limit": 1}
+ if filters:
+ base["filters"] = copy.deepcopy(filters)
+ specs = [{"fn": "count"}] + [{"fn": "sum", "field": key} for key in numeric]
+ try:
+ answer = _query(session, database, {**base, "aggregates": specs})
+ except Exception:
+ if not numeric:
+ raise
+ notes.append("Totals show the row count only because a number column holds text.")
+ answer = _query(session, database, {**base, "aggregates": [{"fn": "count"}]})
+ totals = {"count": None, "sum": {}}
+ for agg in answer.get("aggregates") or ():
+ if agg.get("fn") == "count" and agg.get("field") is None:
+ totals["count"] = agg.get("value")
+ elif agg.get("fn") == "sum":
+ totals["sum"][agg["field"]] = agg.get("value")
+ if not isinstance(totals["count"], int):
+ raise ValueError("the reader returned no row count")
+ return totals, notes
+
+
+def _columns(fields, keys, visible):
+ """Column order follows `keys`; a field hidden from the maker never becomes a column."""
+ by_key = {f["key"]: f for f in fields or () if isinstance(f, dict) and isinstance(f.get("key"), str)}
+ out = []
+ for key in keys:
+ if key in by_key and key in visible:
+ field = by_key[key]
+ out.append({"key": key, "label": _text(field.get("label")) or key, "type": field.get("type")})
+ return out
+
+
+def _table_content(session, database, title, kind_of, result, filters, page_read, column_keys=None):
+ """Build records, view or app content from one reader result."""
+ visible = _visible_keys(session, database)
+ fields = result.get("fields") or []
+ keys = column_keys if column_keys is not None else [f.get("key") for f in fields if isinstance(f, dict)]
+ columns = _columns(fields, keys, visible)
+ records = result.get("records") or []
+ rows = [[copy.deepcopy(rec.get(col["key"])) for col in columns] for rec in records[:ROW_LIMIT]]
+ totals, notes = _totals(session, database, filters, columns)
+ total = totals["count"]
+ if len(rows) < total:
+ cause = ("Loopy read only those rows" if page_read and len(records) <= ROW_LIMIT
+ else f"a snapshot keeps the first {ROW_LIMIT}")
+ notes.insert(0, _rows_sentence(len(rows), total, cause))
+ return {"title": title, "kind_of": kind_of,
+ "columns": [{"key": c["key"], "label": c["label"]} for c in columns],
+ "rows": rows, "totals": totals, "row_count": total, "shown": len(rows),
+ "notes": notes, "sources": [database]}
+
+
+def _record_list(session, name, args, result):
+ if (not isinstance(result, dict) or not isinstance(result.get("records"), list)
+ or result.get("groups")):
+ return None
+ database = _text(args.get("database")) or _text(result.get("database"))
+ if database is None:
+ return None
+ query = args.get("query") if name == "database_object" else args
+ filters = (query or {}).get("filters")
+ title = f"{_text(result.get('label')) or database} records"
+ return _table_content(session, database, title, "records", result, filters, True)
+
+
+def _view_payload(config, visible):
+ keys = config.get("visible")
+ keys = list(keys) if isinstance(keys, list) else None
+ order = [k for k in config.get("order") or () if isinstance(k, str)]
+ if keys is not None and order:
+ keys = [k for k in order if k in keys] + [k for k in keys if k not in order]
+ payload = {"limit": ROW_LIMIT}
+ if keys is not None:
+ payload["fields"] = [k for k in dict.fromkeys(keys) if k in visible]
+ sorts = [{"field": rule.get("colId"), "direction": rule.get("dir")}
+ for rule in config.get("sorts") or () if isinstance(rule, dict)]
+ if sorts:
+ payload["sorts"] = sorts[:8]
+ filters = config.get("filters")
+ if isinstance(filters, list) and filters:
+ payload["filters"] = {"conj": config.get("filterConj") or "and", "nodes": filters}
+ elif isinstance(filters, dict) and filters.get("nodes"):
+ payload["filters"] = filters
+ return payload
+
+
+def _view(session, args, result):
+ database = _text(args.get("database")) or _text((result or {}).get("database"))
+ draft = args.get("view") if isinstance(args.get("view"), dict) else {}
+ view_id = _text((result or {}).get("view_id")) or _text(draft.get("id"))
+ if database is None or view_id is None:
+ return None
+ view = _load_view(session, database, view_id) or draft
+ config = view.get("config") if isinstance(view.get("config"), dict) else {}
+ payload = _view_payload(config, _visible_keys(session, database))
+ answer = _query(session, database, payload)
+ title = _text(view.get("name")) or "Saved View"
+ return _table_content(session, database, title, "view", answer, payload.get("filters"), False,
+ payload.get("fields"))
+
+
+def _app(session, args, result):
+ app = (result or {}).get("application")
+ app = app if isinstance(app, dict) else {}
+ title = _text(app.get("name")) or _text(args.get("name")) or "App"
+ compatible = app.get("compatibleDatabases") or args.get("compatibleDatabases") or []
+ database = (_text(app.get("sourceDatabase")) or _text(args.get("sourceDatabase"))
+ or (_text(compatible[0]) if isinstance(compatible, list) and compatible else None))
+ if database is None:
+ return {"title": title, "kind_of": "app", "columns": [], "rows": [], "totals": {"count": 0, "sum": {}},
+ "row_count": 0, "shown": 0, "notes": ["This App reads no database."], "sources": None}
+ payload = {"limit": ROW_LIMIT}
+ field_map = app.get("fieldMap") or args.get("fieldMap")
+ if isinstance(field_map, dict) and field_map:
+ visible = _visible_keys(session, database)
+ payload["fields"] = [k for k in dict.fromkeys(field_map.values()) if k in visible]
+ answer = _query(session, database, payload)
+ return _table_content(session, database, title, "app", answer, None, False, payload.get("fields"))
+
+
+def _col_index(letters):
+ n = 0
+ for ch in letters:
+ n = n * 26 + ord(ch) - 64
+ return n
+
+
+def _col_name(n):
+ out = ""
+ while n:
+ n, rem = divmod(n - 1, 26)
+ out = chr(65 + rem) + out
+ return out
+
+
+def _cell_shown(cell):
+ for key in ("display", "text"):
+ if isinstance(cell.get(key), str) and cell[key] != "":
+ return cell[key]
+ value = cell.get("value")
+ return "" if value is None else value
+
+
+def _sheet(session, name, args, result):
+ result = result if isinstance(result, dict) else {}
+ nested = result.get("workbook") if isinstance(result.get("workbook"), dict) else {}
+ workbook_id = (_text(args.get("workbook_id")) or _text(result.get("workbook_id"))
+ or _text(nested.get("id")) or _text(result.get("id")))
+ if workbook_id is None:
+ return None
+ book = _load_workbook(session, workbook_id)
+ tabs = [tab for tab in book.get("sheets") or () if isinstance(tab, dict)]
+ if not tabs:
+ return None
+ wanted = args.get("tab") or args.get("worksheet") or result.get("tab")
+ wanted = wanted.get("id") if isinstance(wanted, dict) else wanted
+ tab = next((t for t in tabs if wanted is not None and wanted in (t.get("id"), t.get("name"))), tabs[0])
+ cells = {}
+ for addr, cell in (tab.get("cells") or {}).items():
+ match = _ADDR.fullmatch(str(addr).strip().upper())
+ if match and isinstance(cell, dict):
+ cells[(int(match.group(2)), _col_index(match.group(1)))] = cell
+ sources, unnamed, checked = set(), False, {}
+ # A displayed formula can read a binding on another tab.
+ for source_tab in tabs:
+ for cell in (source_tab.get("cells") or {}).values():
+ if not isinstance(cell, dict) or cell.get("binding") is None:
+ continue
+ binding = cell["binding"]
+ database = _text(binding.get("database")) if isinstance(binding, dict) else None
+ if database is None:
+ unnamed = True
+ else:
+ sources.add(database)
+ shown = {}
+ for at, cell in cells.items():
+ binding = cell.get("binding")
+ if binding is not None:
+ database = _text(binding.get("database")) if isinstance(binding, dict) else None
+ if database is None:
+ continue
+ memo = json.dumps(binding, sort_keys=True, default=str)
+ if memo not in checked:
+ checked[memo] = _binding_readable(session, binding, book, tab)
+ if not checked[memo]:
+ continue
+ shown[at] = copy.deepcopy(_cell_shown(cell))
+ last_row = max((r for r, _ in cells), default=0)
+ last_col = max((c for _, c in cells), default=0)
+ notes = []
+ if last_col > MAX_SHEET_COLUMNS:
+ notes.append(f"Showing the first {MAX_SHEET_COLUMNS} columns because a snapshot keeps "
+ f"{MAX_SHEET_COLUMNS} columns. Open in Loopable to see every column.")
+ width = min(last_col, MAX_SHEET_COLUMNS)
+ rows = [[shown.get((r, c), "") for c in range(1, width + 1)] for r in range(1, min(last_row, ROW_LIMIT) + 1)]
+ if last_row > ROW_LIMIT:
+ notes.insert(0, _rows_sentence(ROW_LIMIT, last_row, f"a snapshot keeps the first {ROW_LIMIT}"))
+ book_name = _text(book.get("name")) or "Sheet"
+ tab_name = _text(tab.get("name"))
+ return {"title": f"{book_name}, {tab_name}" if tab_name and len(tabs) > 1 else book_name,
+ "kind_of": "sheet",
+ "columns": [{"key": _col_name(c), "label": _col_name(c)} for c in range(1, width + 1)],
+ "rows": rows, "totals": {"count": last_row, "sum": {}}, "row_count": last_row,
+ "shown": len(rows), "notes": notes, "sources": None if unnamed else sorted(sources)}
+
+
+def _size(content):
+ return len(json.dumps(content, sort_keys=True, default=str).encode("utf-8"))
+
+
+def _finish(content, frozen_at):
+ """Apply the byte bound, join the notes and stamp the time, keeping totals over all rows."""
+ content = json.loads(json.dumps(content, default=str))
+ notes = content.pop("notes")
+ content.update(frozen_at=frozen_at, note=" ".join(notes) or None)
+ if _size(content) > MAX_CONTENT_BYTES:
+ lo, hi, rows = 0, len(content["rows"]), content["rows"]
+ notes = [n for n in notes if not re.match(r"Showing [\d,]+ of [\d,]+ rows because ", n)]
+
+ def bounded(count):
+ content["rows"] = rows[:count]
+ content["shown"] = count
+ content["note"] = " ".join([
+ _rows_sentence(count, content["row_count"],
+ f"a snapshot keeps at most {MAX_CONTENT_BYTES // 1024} KB"), *notes])
+ return _size(content) <= MAX_CONTENT_BYTES
+
+ if not bounded(0):
+ raise ValueError("Snapshot labels and totals exceed the content bound.")
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ lo, hi = (mid, hi) if bounded(mid) else (lo, mid - 1)
+ bounded(lo)
+ return {key: content[key] for key in ("title", "kind_of", "columns", "rows", "totals", "row_count",
+ "shown", "note", "sources", "frozen_at", "_authorization")
+ if key in content}
+
+
+def _retire_earlier(rt, username, turn):
+ """Keep one active record-list snapshot per turn."""
+ for item_id in list(turn.get("artifacts") or ()):
+ row = assistant_artifacts.get(rt, username, item_id)
+ if (row and row.get("kind") == "snapshot" and row.get("status") == "active"
+ and row.get("toolCall", {}).get("name") in RECORD_TOOLS):
+ assistant_artifacts.set_status(rt, username, item_id, "deleted")
+
+
+def capture(session, door, name, args, result, turn):
+ """Store a frozen snapshot of this tool call when it qualifies; return its id or None. Never raises."""
+ try:
+ if (door not in assistant_artifacts.DOORS or not isinstance(name, str)
+ or not isinstance(turn, dict) or not isinstance(turn.get("artifacts"), list)):
+ return None
+ args = args if isinstance(args, dict) else {}
+ kind_of = _kind_of(name, args)
+ if kind_of is None:
+ return None
+ build = {"records": lambda: _record_list(session, name, args, result),
+ "sheet": lambda: _sheet(session, name, args, result),
+ "view": lambda: _view(session, args, result),
+ "app": lambda: _app(session, args, result)}[kind_of]
+ content = build()
+ if content is None:
+ return None
+ if content["sources"] is not None:
+ if kind_of == "sheet":
+ try:
+ content["_authorization"] = _authorization_proof(session, content["sources"])
+ except Exception:
+ pass # A blanked unreadable binding retains protected provenance.
+ else:
+ content["_authorization"] = _authorization_proof(session, content["sources"])
+ rt, username = session.runtime, session.uname
+ frozen_at = _now()
+ content = _finish(content, frozen_at)
+ ref = assistant_artifacts.store_snapshot(rt, username, content)
+ if kind_of == "records":
+ _retire_earlier(rt, username, turn)
+ item_id = assistant_artifacts.record(rt, username, {
+ "kind": "snapshot", "ref": ref, "title": content["title"], "door": door,
+ "toolCall": {"name": name, "args": copy.deepcopy(args)}, "createdAt": time.time(),
+ "sources": content["sources"], "frozen_at": frozen_at})
+ turn["artifacts"].append(item_id)
+ return item_id
+ except Exception as exc:
+ LOG.warning("snapshot not captured for %s: %s: %s", name, type(exc).__name__, exc)
+ return None
+
+
+def read(rt, artifact_id):
+ """Return the stored artifact and its frozen content; read only those two documents."""
+ row = assistant_artifacts.get_by_id(rt, artifact_id)
+ if row is None or row.get("kind") != "snapshot" or row.get("status") == "deleted":
+ return None
+ content = assistant_artifacts.read_snapshot(rt, row)
+ if content is None:
+ return None
+ return {"artifact": assistant_artifacts.c7(row),
+ "snapshot": {key: value for key, value in content.items() if key != "_authorization"}}
diff --git a/api/assistant_artifacts.py b/api/assistant_artifacts.py
index 99bf467765f7f35c9170be1e4781425c40bad09a..f30a97126cd6b435c17d190be0f78b2ff642f87b 100644
--- a/api/assistant_artifacts.py
+++ b/api/assistant_artifacts.py
@@ -4,13 +4,20 @@ import datetime
import heapq
import json
import math
+import re
+import uuid
import assistant_log
+import loopy_links
CHUNK_ITEMS = 200
-KINDS = {"view", "sheet", "report", "run", "query", "schedule", "pdf"}
+KINDS = {"view", "sheet", "report", "run", "query", "schedule", "pdf", "xlsx", "image", "snapshot"}
+FROZEN_KINDS = {"snapshot", "pdf", "xlsx", "image"}
DOORS = {"app", "whatsapp", "wake"}
STATUSES = {"active", "paused", "deleted"}
+AMAZON_PREFIX = "ut_amzn_"
+_ITEM_ID = re.compile(r"([0-9a-f]{24})\.([0-9]+)")
+_SNAPSHOT_REF = re.compile(r"[0-9a-f]{32}")
def timestamp(value):
@@ -35,6 +42,86 @@ def _chunk_key(h, n):
return f"assistant_artifacts_{h}_{n}"
+def _source_keys(sources):
+ """Return normalized database keys, or None for unknown or malformed provenance."""
+ if not isinstance(sources, list) or not all(isinstance(key, str) and key.strip() for key in sources):
+ return None
+ return [key.strip() for key in sources]
+
+
+def is_amazon(sources):
+ """R86 applies to Amazon databases and unknown or malformed provenance."""
+ keys = _source_keys(sources)
+ return keys is None or any(key.startswith(AMAZON_PREFIX) for key in keys)
+
+
+def _optional_text(item, field, sentence):
+ value = item.get(field)
+ if value is not None and (not isinstance(value, str) or not value.strip()):
+ raise ValueError(sentence)
+ return value.strip() if value is not None else None
+
+
+def _c7_inputs(item, kind, args, created_at):
+ """Validate the optional C7 inputs and return sources, amazon, file_id, mime and frozen_at."""
+ sources = item.get("sources")
+ if sources is not None and _source_keys(sources) is None:
+ raise ValueError("Artifact sources must be a list of database names.")
+ if sources is None and kind in ("view", "query") and isinstance(args.get("database"), str) \
+ and args["database"].strip():
+ sources = [args["database"].strip()]
+ elif sources is not None:
+ sources = _source_keys(sources)
+ if "amazon" in item and not isinstance(item["amazon"], bool):
+ raise ValueError("The artifact Amazon flag must be true or false.")
+ amazon = is_amazon(sources) or item.get("amazon") is True
+ file_id = _optional_text(item, "file_id", "An artifact file id must be text.")
+ mime = _optional_text(item, "mime", "An artifact file type must be text.")
+ frozen = item.get("frozen_at")
+ try:
+ frozen = timestamp(frozen) if frozen is not None else None
+ except (TypeError, ValueError, OverflowError, OSError) as exc:
+ raise ValueError("An artifact needs a valid frozen time.") from exc
+ if frozen is None and kind in FROZEN_KINDS:
+ frozen = created_at
+ return sources, amazon, file_id, mime, frozen
+
+
+def _app_database(rt, ref, args):
+ compatible = args.get("compatibleDatabases")
+ if isinstance(compatible, list) and compatible and isinstance(compatible[0], str) and compatible[0].strip():
+ return compatible[0]
+ if isinstance(args.get("sourceDatabase"), str) and args["sourceDatabase"].strip():
+ return args["sourceDatabase"]
+ try:
+ import application_registry
+ stored = application_registry.load(rt)["applications"].get(ref) or {}
+ first = (stored.get("compatibleDatabases") or [None])[0]
+ return first if isinstance(first, str) and first.strip() else None
+ except Exception:
+ # A registry read failure falls back to the artifact link.
+ return None
+
+
+def _link(rt, row):
+ """The absolute link that opens this row's work, or None with no public base."""
+ kind, ref, call = row["kind"], row["ref"], row["toolCall"]
+ args = call["args"]
+ # A fixture links module can carry only the artifact builder, so a missing builder means no link.
+ build = lambda name, *values: (getattr(loopy_links, name, None) or (lambda *_: None))(*values)
+ link = None
+ if ref is not None:
+ if kind == "sheet":
+ link = build("sheet_link", ref)
+ elif kind == "view":
+ link = build("view_link", args.get("database"), ref)
+ elif kind == "query":
+ link = build("query_link", ref)
+ elif kind == "run" and call["name"] == "app_upsert":
+ link = build("application_link", ref, _app_database(rt, ref, args))
+ return link or loopy_links.artifact_link(row["id"])
+
+
def record(rt, username, item):
"""Validate and append exactly one C14 item; return its principal-bound id."""
from routes_query import _no_dashes
@@ -60,9 +147,12 @@ def record(rt, username, item):
at = timestamp(item.get("createdAt"))
except (TypeError, ValueError, OverflowError, OSError) as exc:
raise ValueError("An artifact needs JSON arguments and a valid creation time.") from exc
+ sources, amazon, file_id, mime, frozen = _c7_inputs(item, item["kind"], call["args"], at)
value = {"kind": item["kind"], "ref": ref, "title": _no_dashes(item["title"]).strip()[:200],
"door": item["door"], "toolCall": {"name": call["name"], "args": copy.deepcopy(call["args"])},
- "createdAt": at, "status": "active"}
+ "createdAt": at, "status": "active", "sources": sources, "amazon": amazon}
+ value.update({key: got for key, got in (("file_id", file_id), ("mime", mime), ("frozen_at", frozen))
+ if got is not None})
h = assistant_log._hash(rt, username)
allocated = []
def allocate(raw):
@@ -76,6 +166,7 @@ def record(rt, username, item):
rt.update(f"assistant_artifacts_{h}_index", allocate, flush="sync")
seq, n = allocated
row = {**value, "id": f"{h}.{seq}", "seq": seq}
+ row["link"] = _link(rt, row)
def insert(raw):
existing = {entry["seq"]: entry for entry in (raw or {}).get("items", [])}
existing.setdefault(seq, row)
@@ -130,6 +221,64 @@ def get(rt, username, item_id):
return next((copy.deepcopy(row) for row in chunk.get("items", []) if row["id"] == item_id), None)
+def get_by_id(rt, item_id):
+ """Read one row by its `h.seq` id alone, for a page that has no username."""
+ match = _ITEM_ID.fullmatch(item_id) if isinstance(item_id, str) else None
+ if match is None:
+ return None
+ h, seq = match.group(1), int(match.group(2))
+ chunk = rt.get(_chunk_key(h, seq // CHUNK_ITEMS)) or {}
+ return next((copy.deepcopy(row) for row in chunk.get("items", []) if row.get("id") == item_id), None)
+
+
+def _snapshot_key(h, ref):
+ # The content lives in its own document: a read is billed at the document's text size.
+ return f"assistant_snapshot_{h}_{ref}"
+
+
+def store_snapshot(rt, username, content):
+ """Write one frozen snapshot content document and return its `ref`."""
+ if not isinstance(content, dict):
+ raise ValueError("A snapshot must be an object.")
+ json.dumps(content, allow_nan=False)
+ ref = uuid.uuid4().hex
+ frozen = copy.deepcopy(content)
+ rt.update(_snapshot_key(assistant_log._hash(rt, username), ref), lambda _raw: frozen, flush="sync")
+ return ref
+
+
+def read_snapshot(rt, row):
+ """Read the content document of one snapshot row, or None; it touches no other key."""
+ if not isinstance(row, dict) or row.get("kind") != "snapshot" or not isinstance(row.get("id"), str):
+ return None
+ match, ref = _ITEM_ID.fullmatch(row["id"]), row.get("ref")
+ if match is None or not isinstance(ref, str) or not _SNAPSHOT_REF.fullmatch(ref):
+ return None
+ content = rt.get(_snapshot_key(match.group(1), ref))
+ return copy.deepcopy(content) if content else None
+
+
+def c7(row):
+ """Project C7 with Amazon protection for unknown provenance, including malformed legacy sources."""
+ sources = _source_keys(row.get("sources"))
+ out = {"id": row["id"], "kind": row["kind"], "title": row["title"], "created_at": row["createdAt"],
+ "frozen_at": row.get("frozen_at"), "sources": sources,
+ "amazon": is_amazon(sources) or row.get("amazon", False) is not False,
+ "link": row["link"] if "link" in row else loopy_links.artifact_link(row["id"])}
+ file_id = row.get("file_id") or (row.get("ref") if row["kind"] == "pdf" else None)
+ if file_id:
+ out["file_id"] = file_id
+ if row.get("mime"):
+ out["mime"] = row["mime"]
+ return out
+
+
+def link_fields(row):
+ """The link a tool result carries, or a plain note when no public base is set."""
+ link = (row or {}).get("link")
+ return {"link": link} if link else {"link": None, "linkNote": loopy_links.NO_LINK_NOTE}
+
+
def set_status(rt, username, item_id, status):
if not isinstance(status, str) or status not in STATUSES:
raise ValueError("That artifact status is not available.")
diff --git a/api/assistant_feed.py b/api/assistant_feed.py
index 3bb3aa0b621ab1a19a0ccdb1c52f0b6a22ee23ac..fa00915a0f829e7da55dcfecfd2f3eff61e45576 100644
--- a/api/assistant_feed.py
+++ b/api/assistant_feed.py
@@ -12,6 +12,7 @@ from core import alerts
CUTOVER_KEY = "assistant_notice_cutover"
+INBOX_KEYS = ("type", "request_id", "sender", "target", "text", "actions", "state")
_LOCK = threading.RLock()
_LOG = logging.getLogger(__name__)
@@ -20,6 +21,8 @@ def _target(item):
if isinstance(item.get("target"), dict):
return copy.deepcopy(item["target"])
topic, key = str(item.get("topic") or ""), str(item.get("alertId") or "")
+ if topic == "inbox":
+ return None # A C6 target arrives as a dict above. A question may have none.
view = str(item.get("viewId") or "")
if topic == "automation" and key:
return {"module": "automation", "id": key, "tab": "runs"}
@@ -54,6 +57,53 @@ def _link(target):
return ""
+def _inbox_link(target):
+ """The deep link of a C6 target `{kind, key, label}`, or "" when it has no address."""
+ if not isinstance(target, dict):
+ return ""
+ kind, key = target.get("kind"), str(target.get("key") or "")
+ pair = re.split(r"[/:]", key, maxsplit=1)
+ if not key:
+ return ""
+ if kind == "database":
+ return "#/data?" + urlencode({"database": key})
+ if kind == "view":
+ if len(pair) == 2 and all(pair):
+ return "#/data?" + urlencode({"database": pair[0], "view": pair[1]})
+ return "#/data?" + urlencode({"view": key})
+ if kind == "sheet":
+ return "#/sheet?" + urlencode({"wb": key})
+ if kind == "app" and len(pair) == 2 and all(pair):
+ # An app opens inside its database: `#/app?database=&application=`.
+ return "#/app?" + urlencode({"database": pair[0], "application": pair[1]})
+ return ""
+
+
+def _inbox_payload(inbox, subject, body):
+ """Exactly the C6 keys, plus title, body, link and source for the external door."""
+ payload = {key: copy.deepcopy(inbox.get(key)) for key in INBOX_KEYS}
+ sender = payload.get("sender")
+ if isinstance(sender, dict):
+ sender["name"] = ai_enrich.no_dashes(" ".join(str(sender.get("name") or "").split()))
+ payload.update(title=subject, body=body, link=_inbox_link(payload.get("target")),
+ source="inbox")
+ return payload
+
+
+def _inside_window(rt, username):
+ """True when the recipient has a WhatsApp phone inside the 24-hour window."""
+ try:
+ import telnyx_whatsapp
+ from core import users
+ record = dict(users._tenant_accounts(assistant_log._tenant_of(rt))).get(username)
+ whatsapp = record.get("whatsapp") if isinstance(record, dict) else None
+ phone = whatsapp.get("phone") if isinstance(whatsapp, dict) else None
+ return bool(phone) and bool(telnyx_whatsapp.within_window(phone))
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("WhatsApp window was not read: %s", type(exc).__name__)
+ return False
+
+
def post(rt, username, item):
"""Append one notice, drop legacy unread rows once, and use the optional external door."""
if item.get("topic") == "ticket":
@@ -66,10 +116,14 @@ def post(rt, username, item):
fallback = {"automation": "Agents", "share": "A teammate"}.get(source, "Alerts")
sender = ai_enrich.no_dashes(item.get("actor") or fallback)
target = _target(item)
- payload = {"title": subject, "subject": subject, "body": body, "sender": sender,
- "target": target, "link": _link(target), "source": source,
- "notificationId": item.get("id"), "alertId": item.get("alertId"),
- "viewId": item.get("viewId"), "rowId": item.get("rowId")}
+ inbox = item.get("inbox") if isinstance(item.get("inbox"), dict) else None
+ if inbox is not None:
+ payload = _inbox_payload(inbox, subject, body)
+ else:
+ payload = {"title": subject, "subject": subject, "body": body, "sender": sender,
+ "target": target, "link": _link(target), "source": source,
+ "notificationId": item.get("id"), "alertId": item.get("alertId"),
+ "viewId": item.get("viewId"), "rowId": item.get("rowId")}
turn = {"role": "system", "door": "wake", "kind": "notice", "text": body,
"payload": payload, "at": item.get("at") or alerts._now_iso()}
with _LOCK:
@@ -78,13 +132,25 @@ def post(rt, username, item):
rt.update(CUTOVER_KEY, lambda _data: {"version": 1, "purged": True}, flush="sync")
turn_id = assistant_log.append(rt, username, turn)
turn["id"] = turn_id
+ if getattr(rt, "preview_only", False):
+ rt.deferred_notices.append({"username": username, "turn": copy.deepcopy(turn),
+ "inside_window_only": inbox is not None})
+ return turn_id
+ deliver_external(rt, username, turn, inside_window_only=inbox is not None)
+ return turn_id
+
+
+def deliver_external(rt, username, turn, *, inside_window_only=False):
+ """Deliver an already committed notice, including a notice held by an Assistant preview."""
external = getattr(ping_doors, "notify_external", None)
+ if inside_window_only and not _inside_window(rt, username):
+ # R108(l): an agent message reaches WhatsApp only inside the window, never as a template.
+ external = None
if callable(external):
try:
external(rt, username, copy.deepcopy(turn))
except Exception as exc:
_LOG.warning("External notice was not delivered: %s", type(exc).__name__)
- return turn_id
alerts.set_sink(post)
diff --git a/api/assistant_files.py b/api/assistant_files.py
index 38ea9dda6b01630dd8573340f101a82d54318b46..4cc17b96fcb83ec4838f62c4c493be411f5bff37 100644
--- a/api/assistant_files.py
+++ b/api/assistant_files.py
@@ -1,4 +1,4 @@
-"""Store assistant PDFs and durable capabilities under their tenant and owner."""
+"""Store assistant files and durable capabilities under their tenant and owner."""
import base64
import copy
import hashlib
@@ -15,6 +15,9 @@ import assistant_artifacts
import assistant_log
MAX_TTL = 3600
+XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+IMAGE_MIME = "image/png"
+_FORMATS = {"application/pdf": ("pdf", "pdf"), XLSX_MIME: ("xlsx", "xlsx"), IMAGE_MIME: ("png", "image")}
_FILE_ID = re.compile(r"[0-9a-f]{32}")
_TENANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,62}")
_TOKEN_PART = re.compile(r"[A-Za-z0-9_-]{48}")
@@ -58,7 +61,8 @@ def _key(file_id):
def _path(item):
- return f"assistant_files/{item['ownerHash']}/{item['id']}.pdf"
+ extension = _FORMATS[item["mime"]][0]
+ return f"assistant_files/{item['ownerHash']}/{item['id']}.{extension}"
def metadata(rt, file_id):
@@ -70,7 +74,7 @@ def metadata(rt, file_id):
or item.get("tenant") != assistant_log._tenant_of(rt)
or not isinstance(item.get("owner"), str) or not item["owner"]
or item.get("ownerHash") != assistant_log._hash(rt, item["owner"])
- or item.get("mime") != "application/pdf"
+ or not isinstance(item.get("mime"), str) or item["mime"] not in _FORMATS
or not isinstance(item.get("size"), int) or item["size"] < 0
or not isinstance(item.get("artifactId"), str)):
return None
@@ -94,16 +98,51 @@ def read_bytes(rt, item):
def _public_metadata(item):
fields = ("id", "filename", "size", "mime", "artifactId", "createdAt")
- return {**{key: item[key] for key in fields}, "link": _artifact_link(item["artifactId"])}
+ result = {**{key: item[key] for key in fields}, "link": _artifact_link(item["artifactId"])}
+ if item["mime"] in (XLSX_MIME, IMAGE_MIME):
+ result.update(file_id=item["id"], bytes=item["size"], created_at=item["createdAt"],
+ frozen_at=item["createdAt"], sources=copy.deepcopy(item.get("sources")),
+ amazon=item.get("amazon", True))
+ return result
-def save(rt, username, *, title, data, mime, door, tool_call):
- """Save one PDF and its replayable artifact, returning its file and artifact links."""
+def save(rt, username, *, title, data, mime, door, tool_call, sources=None, amazon=False):
+ """Save one file and its replayable artifact with validated source provenance."""
h = assistant_log._hash(rt, username)
if not isinstance(title, str) or not title.strip():
raise ValueError("A file needs a title.")
- if mime != "application/pdf" or not isinstance(data, (bytes, bytearray, memoryview)):
- raise ValueError("A file needs PDF bytes and the PDF media type.")
+ if not isinstance(mime, str) or mime not in _FORMATS or not isinstance(data, (bytes, bytearray, memoryview)):
+ raise ValueError("A file needs bytes and a supported media type.")
+ extension, kind = _FORMATS[mime]
+ import agent_runtime
+ if agent_runtime._PRODUCING_TURN.get() is not None:
+ proof = agent_runtime.producing_turn_sources(rt, username)
+ if proof is None:
+ sources = None
+ else:
+ if sources is not None and assistant_artifacts._source_keys(sources) is None:
+ raise ValueError("A file needs valid source provenance.")
+ sources = sorted(set(proof) | set(sources or []))
+ amazon = amazon or assistant_artifacts.is_amazon(sources)
+ if mime == XLSX_MIME:
+ from loopy_xlsx import MAX_BYTES
+ if len(data) > MAX_BYTES:
+ raise ValueError("Excel export exceeds the 20 MiB file limit. Filter the rows or select fewer fields and ask again. No file was stored.")
+ if sources is None:
+ raise ValueError("An Excel file needs validated source provenance. Read its sources and ask again.")
+ if mime == IMAGE_MIME:
+ from loopy_image import MAX_BYTES
+ if len(data) > MAX_BYTES:
+ raise ValueError("The image exceeds the 20 MiB limit. Select fewer fields and ask again. No file was stored.")
+ if sources is None:
+ raise ValueError("An image needs validated source provenance. Read its sources and ask again.")
+ if (sources is not None and assistant_artifacts._source_keys(sources) is None
+ or type(amazon) is not bool):
+ raise ValueError("A file needs valid source provenance and its Amazon flag.")
+ sources = list(dict.fromkeys(assistant_artifacts._source_keys(sources))) if sources is not None else None
+ amazon = amazon or assistant_artifacts.is_amazon(sources)
+ if kind not in assistant_artifacts.KINDS:
+ raise ValueError(f"{kind.capitalize()} artifacts are not available on this build. Update the artifact registry and ask again. No file was stored.")
if not isinstance(door, str) or door not in assistant_artifacts.DOORS:
raise ValueError("That file door is not available.")
if (not isinstance(tool_call, dict) or not isinstance(tool_call.get("name"), str)
@@ -115,26 +154,29 @@ def save(rt, username, *, title, data, mime, door, tool_call):
file_id = secrets.token_hex(16)
item = {"id": file_id, "owner": username, "ownerHash": h,
"tenant": assistant_log._tenant_of(rt), "title": title,
- "filename": (re.sub(r"[^A-Za-z0-9._-]+", "_", title).strip("._")[:100] or "document") + ".pdf",
+ "filename": (re.sub(r"[^A-Za-z0-9._-]+", "_", title).strip("._")[:100] or "document") + "." + extension,
"size": len(data), "mime": mime, "door": door,
"createdAt": assistant_artifacts.timestamp(time.time()),
- "toolCall": copy.deepcopy(tool_call)}
- _bytes_runtime(rt).upload_bytes(_path(item), bytes(data), message="Save assistant PDF")
+ "toolCall": copy.deepcopy(tool_call), "sources": copy.deepcopy(sources), "amazon": amazon}
+ _bytes_runtime(rt).upload_bytes(_path(item), bytes(data), message=f"Save assistant {kind.upper()}")
item["artifactId"] = assistant_artifacts.record(rt, username, {
- "kind": "pdf", "ref": file_id, "title": title, "door": door,
- "toolCall": tool_call, "createdAt": item["createdAt"]})
+ "kind": kind, "ref": file_id, "title": title, "door": door,
+ "toolCall": tool_call, "createdAt": item["createdAt"],
+ "created_at": item["createdAt"], "frozen_at": item["createdAt"],
+ "sources": sources, "amazon": amazon, "file_id": file_id, "mime": mime})
rt.update(_key(file_id), lambda _raw: copy.deepcopy(item), flush="sync")
- return {"id": file_id, "artifactId": item["artifactId"], "link": _artifact_link(item["artifactId"])}
+ return {"id": file_id, "artifactId": item["artifactId"], "link": _artifact_link(item["artifactId"]),
+ "file_id": file_id, "mime": mime, "bytes": len(data)}
def created_in_turn(rt, username, since):
- """Return all owned PDF metadata created at or after the turn's start."""
+ """Return all owned file metadata created at or after the turn's start."""
boundary = assistant_artifacts.timestamp(since)
h = assistant_log._hash(rt, username)
index = assistant_artifacts._index(rt.get(f"assistant_artifacts_{h}_index"))
items = []
for row in assistant_artifacts._rows(rt, h, index):
- if row["kind"] != "pdf" or row["status"] == "deleted" or row["createdAt"] < boundary:
+ if row["kind"] not in ("pdf", "xlsx", "image") or row["status"] == "deleted" or row["createdAt"] < boundary:
continue
item = owned_metadata(rt, username, row["ref"])
if item and item["createdAt"] >= boundary:
@@ -163,6 +205,8 @@ def capability_url(rt, file_id, ttl=MAX_TTL):
item = metadata(rt, file_id)
if item is None:
raise ValueError("That file does not exist.")
+ if assistant_artifacts.is_amazon(item.get("sources")) or item.get("amazon") is not False:
+ raise ValueError("Amazon files cannot use a public download link. Download the file in the app instead.")
tenant = assistant_log._tenant_of(rt)
if not _TENANT.fullmatch(tenant):
raise ValueError("A file link needs a valid tenant.")
@@ -205,6 +249,8 @@ def resolve_capability(token):
item = owned_metadata(rt, entry["owner"], entry.get("fileId"))
if item is None:
return None
+ if assistant_artifacts.is_amazon(item.get("sources")) or item.get("amazon") is not False:
+ return None
now = time.time()
if now < born:
return None
diff --git a/api/assistant_log.py b/api/assistant_log.py
index c8e9c5517a9224ef8ae9ed6e10c25364c93f784b..8259da0c37267326c6251b053389b59eca661308 100644
--- a/api/assistant_log.py
+++ b/api/assistant_log.py
@@ -6,7 +6,8 @@ turns without an ever-growing message-id index; old ids remain in payload for ra
import copy
import datetime
import hashlib
-from core import freeze_notice
+import inspect
+from core import freeze_notice, grid_events
CHUNK_TURNS = 200
ROLES = {"user", "assistant", "system"}
@@ -14,6 +15,25 @@ DOORS = {"app", "whatsapp", "wake"}
KINDS = {"text", "ping", "confirm", "divider", "notice"}
+def _get(rt, key):
+ """Bypass a process cache when the bound runtime supports fresh reads."""
+ try:
+ if "fresh" in inspect.signature(rt.get).parameters:
+ return rt.get(key, fresh=True)
+ return rt.get(key)
+ except Exception as exc:
+ raise grid_events.StoreUnavailable("Conversation store read failed.") from exc
+
+
+def _update(rt, key, fn):
+ try:
+ return rt.update(key, fn, flush="sync")
+ except ValueError:
+ raise
+ except Exception as exc:
+ raise grid_events.StoreUnavailable("Conversation store write failed.") from exc
+
+
def _tenant_of(rt):
# TenantRuntime.tenant is a Tenant object; its key is the session's tenant slug.
tenant = getattr(rt, "key", None) or getattr(rt, "tenant", None)
@@ -32,6 +52,7 @@ def _index(raw):
raw = raw or {}
return {"version": 1, "nextSeq": int(raw.get("nextSeq", 0)),
"chunks": copy.deepcopy(raw.get("chunks") or {}),
+ "pending": copy.deepcopy(raw.get("pending") or {}),
"folded": bool(raw.get("folded")), "foldedFrom": copy.deepcopy(raw.get("foldedFrom"))}
@@ -54,15 +75,45 @@ def _put_rows(rt, h, n, rows):
if len(existing) > CHUNK_TURNS:
raise ValueError("A conversation chunk is full.")
return {"version": 1, "turns": [existing[seq] for seq in sorted(existing)]}
- rt.update(_chunk_key(h, n), update, flush="sync")
+ _update(rt, _chunk_key(h, n), update)
+
+
+def _ack(rt, h, rows):
+ committed = []
+ def finish(raw):
+ current = _index(raw)
+ for row in rows:
+ current["pending"].pop(str(row["seq"]), None)
+ committed[:] = [copy.deepcopy(current)]
+ return current
+ _update(rt, f"assistant_log_{h}_index", finish)
+ return committed[0]
+
+
+def _recover(rt, h, index):
+ """Publish journalled rows before removing their durable recovery copies."""
+ rows = list(index["pending"].values())
+ if not rows:
+ return index
+ chunks = {}
+ for row in rows:
+ chunks.setdefault(row["seq"] // CHUNK_TURNS, []).append(row)
+ for n, values in chunks.items():
+ _put_rows(rt, h, n, values)
+ _ack(rt, h, rows)
+ # Keep this read's sequence boundary when other appends allocate during recovery.
+ return {**index, "pending": {}}
def _ensure_fold(rt, h):
+ available = getattr(rt, "available", None)
+ if callable(available) and not available():
+ raise grid_events.StoreUnavailable("Conversation store is unavailable.")
key = f"assistant_log_{h}_index"
- index = _index(rt.get(key))
+ index = _index(_get(rt, key))
if index["folded"]:
- return index
- old = rt.get("query_user_" + h) or {}
+ return _recover(rt, h, index)
+ old = _get(rt, "query_user_" + h) or {}
threads, messages = old.get("threads") or {}, old.get("messages") or {}
rows = sorted(messages.values(), key=lambda row: (
str(row.get("createdAt") or ""), 0 if row.get("role") == "user" else 1,
@@ -95,8 +146,8 @@ def _ensure_fold(rt, h):
for n in range((len(turns) + CHUNK_TURNS - 1) // CHUNK_TURNS)}
committed[:] = [copy.deepcopy(current)]
return current
- rt.update(key, finish, flush="sync")
- return committed[0]
+ _update(rt, key, finish)
+ return _recover(rt, h, committed[0])
def append(rt, username, turn):
@@ -127,15 +178,19 @@ def append(rt, username, turn):
count = index["chunks"].get(str(n), 0)
if count >= CHUNK_TURNS:
raise ValueError("A conversation chunk is full.")
+ if len(index["pending"]) >= CHUNK_TURNS:
+ raise grid_events.StoreUnavailable("Conversation publication needs recovery.")
index["nextSeq"] = seq + 1
index["chunks"][str(n)] = count + 1
+ index["pending"][str(seq)] = _turn(h, seq, value)
allocated[:] = [seq, n]
return index
- # Exactly one atomic allocation, then exactly one chunk update.
- rt.update(f"assistant_log_{h}_index", allocate, flush="sync")
+ # Allocation retains the row until its chunk is durable.
+ _update(rt, f"assistant_log_{h}_index", allocate)
seq, n = allocated
row = _turn(h, seq, value)
_put_rows(rt, h, n, [row])
+ _ack(rt, h, [row])
return row["id"]
@@ -150,40 +205,52 @@ def _seq(h, turn_id):
return None
+def _rows(rt, h, index, n):
+ rows = (_get(rt, _chunk_key(h, n)) or {}).get("turns", [])
+ expected = set(range(n * CHUNK_TURNS, min((n + 1) * CHUNK_TURNS, index["nextSeq"])))
+ if not expected.issubset({row["seq"] for row in rows}):
+ raise grid_events.StoreUnavailable("Conversation chunk is incomplete.")
+ return rows
+
+
def _newest(rt, h, index, before=None):
end = min(index["nextSeq"], before) if before is not None else index["nextSeq"]
for n in range((end - 1) // CHUNK_TURNS, -1, -1):
if not index["chunks"].get(str(n)):
continue
- chunk = rt.get(_chunk_key(h, n)) or {}
- for row in sorted(chunk.get("turns", []), key=lambda row: row["seq"], reverse=True):
+ for row in sorted(_rows(rt, h, index, n), key=lambda row: row["seq"], reverse=True):
if row["seq"] < end:
yield copy.deepcopy(row)
-def read(rt, username, *, before=None, limit=50):
- """Newest page by default; each page is oldest first and its first id pages backward."""
- if freeze_notice.enabled():
- # Project a pending legacy fold in memory while maintenance forbids durable writes.
- # The same fold and paging code still determines the visible conversation.
- source_rt = rt
+class _Projection:
+ """Fold and recover read results in memory while maintenance forbids durable writes."""
+ def __init__(self, source):
+ self.source = source
+ self.key = _tenant_of(source)
+ self.documents = {}
+
+ def get(self, key):
+ return copy.deepcopy(self.documents[key] if key in self.documents else _get(self.source, key))
+
+ def available(self):
+ return getattr(self.source, "available", lambda: True)()
- class Projection:
- key = _tenant_of(source_rt)
+ def update(self, key, fn, **kwargs):
+ current = self.get(key) or {}
+ changed = fn(current)
+ self.documents[key] = copy.deepcopy(current if changed is None else changed)
+ return self.get(key)
- def __init__(self):
- self.documents = {}
- def get(self, key):
- return copy.deepcopy(self.documents[key] if key in self.documents else source_rt.get(key))
+def _read_runtime(rt):
+ return _Projection(rt) if freeze_notice.enabled() and not isinstance(rt, _Projection) else rt
- def update(self, key, fn, **kwargs):
- current = self.get(key) or {}
- changed = fn(current)
- self.documents[key] = copy.deepcopy(current if changed is None else changed)
- return self.get(key)
- rt = Projection()
+def read(rt, username, *, before=None, limit=50):
+ """Newest page by default; each page is oldest first and its first id pages backward."""
+ if freeze_notice.enabled():
+ rt = _read_runtime(rt)
h = _hash(rt, username)
index = _ensure_fold(rt, h)
limit = max(1, min(CHUNK_TURNS, int(limit)))
@@ -210,14 +277,15 @@ def read(rt, username, *, before=None, limit=50):
def find(rt, username, turn_id):
"""Find a turn by C12 id, sequence, or the legacy message id in payload."""
+ rt = _read_runtime(rt)
h = _hash(rt, username)
index = _ensure_fold(rt, h)
seq = _seq(h, turn_id)
if seq is not None:
if seq < 0 or seq >= index["nextSeq"]:
return None
- chunk = rt.get(_chunk_key(h, seq // CHUNK_TURNS)) or {}
- return next((copy.deepcopy(row) for row in chunk.get("turns", []) if row["seq"] == seq), None)
+ return next((copy.deepcopy(row) for row in _rows(rt, h, index, seq // CHUNK_TURNS)
+ if row["seq"] == seq), None)
return next((row for row in _newest(rt, h, index)
if (row.get("payload") or {}).get("id") == turn_id), None)
@@ -239,7 +307,7 @@ def update_turn(rt, username, turn_id, fn):
current["turns"][i] = new
changed[:] = [copy.deepcopy(new)]
return current
- rt.update(_chunk_key(h, row["seq"] // CHUNK_TURNS), update, flush="sync")
+ _update(rt, _chunk_key(h, row["seq"] // CHUNK_TURNS), update)
return changed[0] if changed else None
@@ -247,6 +315,7 @@ def search(rt, username, query, limit=10):
words = str(query or "").casefold()[:1000].split()
if not words:
return []
+ rt = _read_runtime(rt)
h = _hash(rt, username)
index = _ensure_fold(rt, h)
limit = max(1, min(CHUNK_TURNS, int(limit)))
diff --git a/api/assistant_memory.py b/api/assistant_memory.py
index cd9e589db0854038626bd2e5f91a998b56d143c3..a28df1b812c3104033ded47f7ae041331ef17531 100644
--- a/api/assistant_memory.py
+++ b/api/assistant_memory.py
@@ -36,7 +36,8 @@ def _key(rt, username):
def _now():
- return datetime.datetime.now(datetime.timezone.utc).isoformat()
+ from core import write_execution
+ return write_execution.utcnow().isoformat()
def _document(raw):
@@ -110,16 +111,32 @@ def _capture_sources(user, sources):
if key not in {"bus", "bu", "businessUnit"}}, "bus": bus} for source in sources]
-def _write_company(rt, user, text, *, sources, door, kind=None):
+def _subject(value):
+ """Normalize the model-supplied key that names what a company note is about."""
+ if value is None or value == "":
+ return None
+ subject = value.strip().lower() if isinstance(value, str) else None
+ if not subject or not re.fullmatch(r"[a-z0-9_]{1,60}", subject):
+ raise ValueError("A note subject uses only lowercase letters, digits and underscores, at most 60 characters.")
+ return subject
+
+
+def _write_company(rt, user, text, *, sources, door, kind=None, subject=None):
from core import perms
- if not perms.is_admin(user):
- raise PermissionError("Only an Administrator can share a company fact.")
+ # R105: every active member writes company notes. The author's role decides which note prevails.
+ if not isinstance(user, dict) or not isinstance(user.get("username"), str) or not user["username"]:
+ raise PermissionError("Only an active member of this workspace can share a company note.")
if door not in {"app", "whatsapp", "slack", "wake"}:
raise ValueError("That Assistant memory door is not available.")
+ subject = _subject(subject)
sources = _sources(sources)
bus = sorted(set().union(*(_source_bus(source) for source in sources))) if sources else []
- entry = {"id": uuid.uuid4().hex, "text": _text(text), "sources": sources,
- "door": door, "at": _now(), "scope": "company", "bus": bus}
+ from core import write_execution
+ entry = {"id": write_execution.new_id(), "text": _text(text), "sources": sources,
+ "door": door, "at": _now(), "scope": "company", "bus": bus, "author": user["username"],
+ "authorRole": "admin" if perms.is_admin(user) else "member"}
+ if subject:
+ entry["subject"] = subject
entry["kind"] = _kind(entry["text"], kind)
def update(raw):
doc = _document(raw)
@@ -202,7 +219,8 @@ def remember(rt, username, text, *, sources, door):
"""Store in the narrowest container. Slack's explicit-remember policy belongs to its door."""
if door not in {"app", "whatsapp", "slack", "wake"}:
raise ValueError("That Assistant memory door is not available.")
- entry = {"id": uuid.uuid4().hex, "text": _text(text), "sources": _sources(sources),
+ from core import write_execution
+ entry = {"id": write_execution.new_id(), "text": _text(text), "sources": _sources(sources),
"door": door, "at": _now()}
entry["kind"] = _kind(entry["text"])
key = _key(rt, username)
@@ -244,11 +262,20 @@ def _forget_at(rt, key, id):
def forget_company(rt, principal, id):
+ """An Administrator erases any company note. Its author erases only their own."""
from core import perms
- if not perms.is_admin(_active_writer(rt, principal)):
- return False
- if not any(entry.get("id") == id for entry in company_document(rt)["entries"]):
+ user = _active_writer(rt, principal)
+ entries = company_document(rt)["entries"]
+ entry = next((row for row in entries if row.get("id") == id), None)
+ if entry is None:
return False
+ if not perms.is_admin(user):
+ if entry.get("author") != user.get("username"):
+ return False
+ # Erase removes every note with the same text. A member never erases another author's note.
+ text = _normalized(entry["text"])
+ if any(_normalized(row["text"]) == text and row.get("author") != user.get("username") for row in entries):
+ return False
return _forget_at(rt, _company_key(rt), id)
@@ -372,6 +399,25 @@ def _readable(rt, principal, sources, *, company=False):
return False
+def _prevailing(entry):
+ """Rank the company notes on one subject: an Administrator's note first, then the newest."""
+ return (entry.get("authorRole") == "admin", _oldest(entry))
+
+
+def _superseded(entries, tombstones):
+ """Ids of company notes that another note on the same subject overrides."""
+ groups = {}
+ for entry in entries:
+ if (isinstance(entry, dict) and isinstance(entry.get("subject"), str) and entry["subject"]
+ and isinstance(entry.get("text"), str) and _normalized(entry["text"]) not in tombstones):
+ groups.setdefault(entry["subject"], []).append(entry)
+ superseded = set()
+ for group in groups.values():
+ winner = max(group, key=_prevailing)
+ superseded.update(id(entry) for entry in group if entry is not winner)
+ return superseded
+
+
def recall(rt, principal, query=None, limit=20):
"""Recall the authorized union with current source access for every channel member."""
try:
@@ -389,10 +435,15 @@ def recall(rt, principal, query=None, limit=20):
return result
entries = [(entry, "personal", doc["tombstones"]) for entry in doc["entries"]]
entries.extend((entry, "company", company["tombstones"]) for entry in company["entries"])
+ # The prevailing note is chosen before the query and source filters, so a withheld winner
+ # never lets a superseded note through.
+ superseded = _superseded(company["entries"], company["tombstones"])
for entry, scope, tombstones in sorted(reversed(entries), key=lambda row: _oldest(row[0]), reverse=True):
if (not isinstance(entry, dict) or not all(key in entry for key in ("id", "text", "sources", "door", "at"))
or not isinstance(entry["text"], str)):
continue
+ if scope == "company" and id(entry) in superseded:
+ continue
if _normalized(entry["text"]) in tombstones:
continue
if words and not all(word in str(entry.get("text", "")).casefold() for word in words):
@@ -609,7 +660,6 @@ def _principal(session):
def _remember(session, args):
from routes_query import _AGENT_DOOR, _AGENT_TURN
turn = _AGENT_TURN.get() or {}
- from core import perms
scope = args.get("scope", "personal")
if scope not in {"personal", "company"}:
raise ValueError("Memory scope must be personal or company.")
@@ -628,16 +678,13 @@ def _remember(session, args):
if not _readable(session.runtime, principal, sources):
raise PermissionError("Your current permissions do not allow this fact's source.")
door = turn.get("door") or _AGENT_DOOR.get()
- if requested and perms.is_admin(user):
+ if requested:
if not _readable(session.runtime, principal, sources, company=True):
raise PermissionError("This fact's source scope could not be proven.")
- return _write_company(session.runtime, user, args.get("text"), sources=sources, door=door)
- result = {"id": remember(session.runtime, session.uname, args.get("text"), sources=sources, door=door),
- "scope": "personal"}
- if requested:
- result["message"] = "I remembered this only for you. Only an Administrator can share a fact with everyone."
- turn["memoryReply"] = result["message"]
- return result
+ return _write_company(session.runtime, user, args.get("text"), sources=sources, door=door,
+ subject=args.get("subject"))
+ return {"id": remember(session.runtime, session.uname, args.get("text"), sources=sources, door=door),
+ "scope": "personal"}
def admits(question):
@@ -666,9 +713,14 @@ def memory_tools():
import agent_tools
source = {"type": "object", "properties": {"database": {"type": "string"},
"fields": {"type": "array", "items": {"type": "string"}}}, "required": ["database", "fields"]}
- agent_tools.register("remember", {"type": "object", "description": "Remember a sourced fact. Use company scope for everyone. Only Administrators can share company facts.",
+ agent_tools.register("remember", {"type": "object", "description": (
+ "Remember a sourced fact. Use company scope for a fact about the business that "
+ "everyone should share, such as when the fiscal year starts. Any user can add a company note."),
"properties": {"text": {"type": "string"},
"scope": {"type": "string", "enum": ["personal", "company"]},
+ "subject": {"type": "string", "description": (
+ "A short key for what the note is about, such as fiscal_year_start. "
+ "Reuse it for a note that replaces another.")},
"sources": {"type": "array", "items": source}}, "required": ["text"]},
_remember, effect="write")
agent_tools.register("recall_memory", {"type": "object", "description": "Search this user's readable memory.",
diff --git a/api/assistant_open_items.py b/api/assistant_open_items.py
index 8575c0e5067c46a9884b58cb5d169da5d395392e..6e6607f7f74c5cc9976be1503a957e98b8366b38 100644
--- a/api/assistant_open_items.py
+++ b/api/assistant_open_items.py
@@ -70,8 +70,9 @@ def open_items(session, args):
assignments = sorted({username, *(str(row["assigned_to"]) for row in mine)})
if any(len(assignment) > 500 for assignment in assignments):
raise ValueError("A ticket assignment exceeds the saved View filter limit.")
+ from core import write_execution
view_args = {"database": database, "view": {
- "id": "open_items_" + uuid.uuid4().hex, "name": "Open for me", "config": {
+ "id": "open_items_" + write_execution.new_id(), "name": "Open for me", "config": {
"filters": [{"colId": "status", "op": "eq", "value": "Open"},
{"conj": "or", "children": [
{"colId": "assigned_to", "op": "eq", "value": assignment}
diff --git a/api/assistant_write_preview.py b/api/assistant_write_preview.py
new file mode 100644
index 0000000000000000000000000000000000000000..f835581d2ac4fe7c0179c365b5aecd4ab832de27
--- /dev/null
+++ b/api/assistant_write_preview.py
@@ -0,0 +1,198 @@
+"""Run authorized Assistant writers on a private store, then commit only their held documents.
+
+The ordinary writer remains the permission/field/BU validator. Revalidation uses the held
+execution clock and ids, and must reproduce the exact documents before any real write.
+"""
+import copy
+import time
+import uuid
+
+from deps import Session
+from core import write_execution
+
+
+def _digest(value):
+ from routes_external import _json_digest
+ return _json_digest(value)
+
+
+def _changes(before, after, path=()):
+ """Exact store deltas, including absent keys and list removal rather than null cells."""
+ if before == after:
+ return []
+ if isinstance(before, dict) and isinstance(after, dict):
+ changes = []
+ for key in sorted(before.keys() | after.keys()):
+ at = [*path, key]
+ if key not in after:
+ changes.append({"path": at, "remove": True})
+ elif key not in before:
+ changes.append({"path": at, "after": copy.deepcopy(after[key])})
+ else:
+ changes.extend(_changes(before[key], after[key], at))
+ return changes
+ if isinstance(before, list) and isinstance(after, list):
+ changes = []
+ for i in range(min(len(before), len(after))):
+ changes.extend(_changes(before[i], after[i], [*path, i]))
+ changes.extend({"path": [*path, i], "after": copy.deepcopy(after[i])}
+ for i in range(len(before), len(after)))
+ changes.extend({"path": [*path, i], "remove": True}
+ for i in range(len(before) - 1, len(after) - 1, -1))
+ return changes
+ return [{"path": list(path), "after": copy.deepcopy(after)}]
+
+
+def project(current, document):
+ if _digest(current) != document["before_digest"]:
+ raise ValueError("The data changed after preview. Ask again to preview the change.")
+ value = copy.deepcopy(current)
+ for op in document["patch"]:
+ path = op["path"]
+ if not path:
+ value = copy.deepcopy(op["after"])
+ continue
+ parent = value
+ for key in path[:-1]:
+ parent = parent[key]
+ key = path[-1]
+ if op.get("remove"):
+ del parent[key]
+ elif isinstance(parent, list) and key == len(parent):
+ parent.append(copy.deepcopy(op["after"]))
+ else:
+ parent[key] = copy.deepcopy(op["after"])
+ if _digest(value) != document["after_digest"]:
+ raise ValueError("The held change could not be verified. Preview the change again.")
+ return value
+
+
+def prepare(session, name, args, *, prior=(), execution=None):
+ import agent_runtime
+ import routes_external as external
+
+ runtime = external._PreviewRuntime(session.runtime)
+ runtime.preview_only = True
+ runtime.deferred_notices = []
+ runtime.deferred_audits = []
+ for step in prior:
+ for key, document in step["preview"]["documents"].items():
+ runtime.put(key, project(runtime.get(key), document))
+ # Prior held steps are the starting point for this step, not part of its diff.
+ runtime._initial = copy.deepcopy(runtime._docs)
+ actor = Session(session.tenant, copy.deepcopy(session.user), copy.deepcopy(session.claims), runtime)
+ execution = execution or {"seed": uuid.uuid4().hex, "timestamp": time.time()}
+ with write_execution.replay(execution):
+ result = agent_runtime._dispatch(actor, name, copy.deepcopy(args))
+ if isinstance(result, dict) and (result.get("ok") is False or result.get("refused")):
+ raise ValueError(agent_runtime._refusal(result))
+ documents = runtime.changed()
+ diff, truncated = external._diff_documents(documents)
+ if truncated:
+ raise ValueError("The complete change is too large to preview. Split it into smaller changes.")
+ # A valid no-op still goes through the writer and may have a meaningful return value.
+ preview = {"execution": execution, "documents": {
+ key: {"before_digest": _digest(pair["before"]), "after_digest": _digest(pair["after"]),
+ "patch": _changes(pair["before"], pair["after"])}
+ for key, pair in documents.items()}, "result": result,
+ "reads": {key: _digest(value) for key, value in runtime._initial.items()}, "diff": diff,
+ "notices": runtime.deferred_notices, "audits": runtime.deferred_audits}
+ external._canonical_json(preview)
+ return preview
+
+
+def lines(preview, name, args, session):
+ import agent_runtime
+ import json
+ result = preview["result"]
+ heading = agent_runtime._change_lines(name, args, session)
+ if isinstance(result, dict):
+ if result.get("label") and (name.startswith("schedule_") or name == "reminder_create"):
+ return [f"{name.replace('_', ' ').capitalize()}: {result['label']}.",
+ result.get("message") or f"{result['inWords']} ({result['timezone']})."]
+ elif name.startswith("ticket_") and result.get("title"):
+ detail = ("Assigned to: " + result["assigned_to"] if name == "ticket_assign" else
+ "Snoozed until: " + result["snoozed_until"] if name == "ticket_snooze" else
+ "Status: " + result["status"])
+ return [f"{name.replace('_', ' ').capitalize()}: {result['title']}.", detail]
+ elif name == "remember":
+ from assistant_memory import _text
+ return ["Remember: " + _text(args.get("text")), "Scope: " + str(result.get("scope") or "company")]
+ elif name == "tool_save":
+ saved = result["saved"]
+ return ["Save tool " + saved["title"] + " for you.",
+ *(step["tool"].replace("_", " ") + ": " + json.dumps(step["args"], ensure_ascii=True)
+ for step in saved["steps"])]
+ elif name == "tool_share":
+ return ["Share tool " + args["name"] + ".", result.get("message") or "Share with the workspace."]
+ elif name == "tool_share_decide":
+ return [("Share " + result["tool"]["title"] + " with the workspace."
+ if result.get("shared") else "Decline the tool sharing request.")]
+ elif name == "agent_message":
+ return ["Send " + args["type"].replace("_", " ") + " to " + str(args.get("to") or "the item owner") + ".",
+ str(result.get("text") or args.get("text") or "")]
+ elif name == "open_items":
+ return str(result["message"]).splitlines()
+ # The held delta contains every normalized change. Show values relevant to the decision;
+ # revisions, attribution and store addresses do not help a person approve a change.
+ metadata = {"id", "rev", "schemaVersion", "created_at", "updated_at", "createdAt", "updatedAt",
+ "created_by", "updatedBy", "writes", "writesFrom", "refreshed_at", "has_access"}
+ details = []
+ def show(value):
+ if isinstance(value, dict):
+ if value.get("kind") == "literal":
+ return value.get("value")
+ return {k: show(v) for k, v in value.items() if k not in metadata}
+ return [show(v) for v in value] if isinstance(value, list) else value
+ for row in preview["diff"]:
+ path = row["path"].split("/")[1:]
+ if not path or path[-1] in metadata or path[0] == "sheet_workbooks" or "writes" in path:
+ continue
+ if name in {"sheet_create_workbook", "sheet_add_tab", "sheet_delete_tab", "view_delete", "query_view_delete", "app_delete"}:
+ continue
+ label = path[-1].replace("_", " ").capitalize()
+ if "cells" in path:
+ index = path.index("cells")
+ label = "Cell " + path[index + 1] + (" " + path[-1] if len(path) > index + 2 else "")
+ elif "rows" in path:
+ index = path.index("rows")
+ label = "Record " + path[index + 1] + (" " + label.lower() if len(path) > index + 2 else "")
+ elif "rules" in path:
+ label = "Format rule"
+ elif "charts" in path:
+ label = "Chart"
+ details.append(label + ": " + json.dumps(show(row["after"]), ensure_ascii=True))
+ return [*heading, *details]
+
+
+def apply(session, step):
+ import routes_external as external
+ held = step["preview"]
+ # Every read used by the planner must still match, including permission/owner documents.
+ for key, before_digest in held["reads"].items():
+ try:
+ current = session.runtime.get(key, fresh=True)
+ except TypeError:
+ current = session.runtime.get(key)
+ if _digest(current) != before_digest:
+ raise ValueError("The data changed after preview. Ask again to preview the change.")
+ checked = prepare(session, step["tool"], step["resolvedArgs"], execution=held["execution"])
+ if any(checked[key] != held[key] for key in ("documents", "notices", "audits")):
+ raise ValueError("The data or permissions changed after preview. Ask again to preview the change.")
+ # Commit the approved plan, rather than recomputing a plan inside a live writer.
+ revisions = {key: session.runtime.revision(key) for key in held["documents"]}
+ if any(not isinstance(rev, dict) or type(rev.get("rev")) is not int for rev in revisions.values()):
+ raise ValueError("This store cannot safely confirm the preview. Nothing was changed.")
+ for key, pair in held["documents"].items():
+ def exact(current, pair=pair):
+ return project(current, pair)
+ session.runtime.update(key, exact, flush="sync", expect_rev=revisions[key]["rev"])
+ if held["notices"]:
+ import assistant_feed
+ for notice in held["notices"]:
+ assistant_feed.deliver_external(session.runtime, **notice)
+ if held["audits"]:
+ from core import audit
+ for detail in held["audits"]:
+ audit.record("external.query", session.tenant, session.uname, detail)
+ return copy.deepcopy(held["result"])
diff --git a/api/deps.py b/api/deps.py
index abe3b31b30e2dc0e25a9c7717bc5f3b01d06c118..fc045a2ec43c8c70e262068f033e19e37b607fe5 100644
--- a/api/deps.py
+++ b/api/deps.py
@@ -186,8 +186,7 @@ def _assistant_tenant_allows(session: Session, database: str) -> bool:
def _assistant_preflight_request(session: Session, database: str, canonical_fields,
- requested_fields, filters, *, require_explicit_grant: bool,
- permission_fields=None):
+ requested_fields, filters, *, require_explicit_grant: bool):
"""Refuse an unresolved grant, field or filter before a stored record is touched."""
import core.perm_scope as perm_scope
@@ -198,8 +197,7 @@ def _assistant_preflight_request(session: Session, database: str, canonical_fiel
visible = (perm_scope.assistant_visible_fields(canonical_fields, session.user, database)
if grant is not None else list(canonical_fields or ()))
try:
- perm_scope.validate_assistant_filter((grant or {}).get("filter"),
- canonical_fields if permission_fields is None else permission_fields)
+ perm_scope.validate_assistant_filter((grant or {}).get("filter"), canonical_fields)
_assistant_requested_fields(requested_fields, visible)
perm_scope.validate_assistant_filter(filters, visible)
except ValueError as exc:
@@ -208,7 +206,7 @@ def _assistant_preflight_request(session: Session, database: str, canonical_fiel
def _assistant_cached_builtin(session: Session, database: str, requested_fields=None, filters=None,
- *, mode=None, permission_scope=None, members=()):
+ *, mode=None):
"""The exact in-process snapshot for one built-in database, or a loud cache-miss refusal.
This intentionally reads `runtime.pool_cache` directly. Calling either route's `_pool_for`
@@ -224,29 +222,18 @@ def _assistant_cached_builtin(session: Session, database: str, requested_fields=
_assistant_refuse(403, "assistant_forbidden",
"your current permissions do not allow this database")
- # Resolve the grid's permitted field contract without rows before any cache read.
+ # Resolve the customer grid's permitted field contract without rows before any cache read.
# Its derived and overlay cells below must match the ordinary grid's scoped assembly.
import aios_grid
+ fields = aios_grid.FIELDS if database == "customer_data" else aios_grid.product_fields()
+ customer_grid = None
if database == "customer_data":
from routes_customers import grid_assembly
- grid_scope = "customer"
- else:
- from routes_products import product_assembly as grid_assembly
- grid_scope = "product"
- grid = grid_assembly(session, scope=grid_scope, consume_corrections=False, with_rows=False)
- fields = grid["fields"]
- internal = grid.get("_permission_scope") or {"fields": fields, "rows": [], "row_fields": fields}
+ customer_grid = grid_assembly(session, scope="customer", consume_corrections=False, with_rows=False)
+ fields = customer_grid["fields"]
_assistant_preflight_request(session, database, fields, requested_fields, filters,
- require_explicit_grant=True, permission_fields=internal["fields"])
- for member in members:
- try:
- perm_scope.validate_assistant_filter(
- (perm_scope.assistant_entry(member, database) or {}).get("filter"), internal["fields"])
- except ValueError as exc:
- _assistant_refuse(400, "assistant_bad_filter", str(exc))
+ require_explicit_grant=True)
if mode in ("schema", "query_schema"):
- if permission_scope is not None and "_permission_scope" in grid:
- permission_scope.update(internal)
return [], [dict(field) for field in fields], {"read": "field contract"}
team_id, agent = perm_scope.derive_pool_scope(session.user, database)
@@ -281,12 +268,15 @@ def _assistant_cached_builtin(session: Session, database: str, requested_fields=
or any(not isinstance(row, dict) for row in entry[1])):
_assistant_refuse(409, "assistant_snapshot_unavailable",
"this database has no app-stored snapshot for your current scope")
- grid = grid_assembly(session, scope=grid_scope, consume_corrections=False, with_rows=True)
- if permission_scope is not None and "_permission_scope" in grid:
- permission_scope.update(grid["_permission_scope"])
- rows = aios_grid.rows_from_pool(grid["rows_src"], fields,
- (grid.get("ws") or {}).get("overlays") or {},
- derived=grid.get("derived"))
+ if customer_grid is not None:
+ customer_grid = grid_assembly(session, scope="customer", consume_corrections=False, with_rows=True)
+ rows = aios_grid.rows_from_pool(customer_grid["rows_src"], fields,
+ (customer_grid.get("ws") or {}).get("overlays") or {},
+ derived=customer_grid.get("derived"))
+ else:
+ import routes_products
+ product_grid = routes_products.product_assembly(session, consume_corrections=False)
+ rows = routes_products.product_rows(product_grid)
return rows, [dict(field) for field in fields if isinstance(field, dict)], entry[0]
@@ -751,6 +741,7 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
⭐ S67-T34: `mode` changes only HOW a database is read, never who may read it
(every wall below runs unchanged): "schema" returns the field contract with no row read,
"query_schema" resolves the answerable SQL fields without reading rows,
+ "query_plan" uses query_schema for mirrors and the incumbent snapshot for other sources,
("aggregate", specs) adds `server_aggregates` and `total_rows` computed in SQL over every
permitted row; an optional third options dict pages SQL groups. ("page", offset, limit)
returns one SQL page plus `total_rows`. Every other
@@ -813,11 +804,10 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
_assistant_refuse(403, "assistant_forbidden",
"Every aggregate and grouping field must be visible to every member.")
extra = {}
- builtin_scope = {}
_audience_defn = None # the held definition lends C16's declaration without a store read
if key in _ASSISTANT_BUILT_INS:
rows, canonical_fields, source_version = _assistant_cached_builtin(
- session, key, fields, filters, mode=mode, permission_scope=builtin_scope, members=members)
+ session, key, fields, filters, mode=mode)
label = _ASSISTANT_BUILT_INS[key]["label"]
source_kind = "runtime_cache"
elif key.startswith("ut_"):
@@ -848,6 +838,8 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
session, key, fields, filters, defn=_defn, lent=_lent)
source_kind = "materialised_user_table"
else:
+ if mode == "query_plan":
+ mode = "query_schema"
if perm_scope.audience_declared(key, st=session.runtime, defn=_defn):
# C16 on a mirror-served table would have to run inside the SQL before counting
# and paging; filtering the returned page afterwards gives a wrong total. Refuse.
@@ -880,11 +872,10 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
# Spelled as membership so a third user-table source is one line, not a growing chain.
_assistant_refuse(403, "assistant_forbidden",
"your current permissions do not allow this database")
- if not builtin_scope:
- try:
- perm_scope.validate_assistant_filter((grant or {}).get("filter"), canonical_fields)
- except ValueError as exc:
- _assistant_refuse(400, "assistant_bad_filter", str(exc))
+ try:
+ perm_scope.validate_assistant_filter((grant or {}).get("filter"), canonical_fields)
+ except ValueError as exc:
+ _assistant_refuse(400, "assistant_bad_filter", str(exc))
# ⭐ OWNER I16 — the tenant handle rides into the row wall here too, so one stored rule means
# the same thing in the Analyst's answer as it does on the grid (see
# `perm_scope._enrich_for_wall`).
@@ -900,16 +891,6 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
# must not make a schema description load stored cells to enrich an empty row set.
if mode in ("schema", "query_schema"):
permitted_rows = []
- elif builtin_scope:
- # The grid already applied the member's row wall before masking its operands.
- permitted_rows = rows
- if session.admin:
- # Retain the Assistant's explicit admin grant, which the interactive grid bypasses.
- allowed = perm_scope.assistant_apply_row_scope(
- builtin_scope["rows"], session.user, key, builtin_scope["row_fields"],
- st=session.runtime)
- allowed_pids = {row.get("pid") for row in allowed}
- permitted_rows = [row for row in permitted_rows if row.get("pid") in allowed_pids]
else:
# C16: with no grant there is no row wall, but a declared recipient list still binds
# every reader, administrators included (S68-T57).
@@ -920,23 +901,13 @@ def assistant_read_scope(session: Session, database, fields=None, filters=None,
defn=_audience_defn))
visible = (perm_scope.assistant_visible_fields(canonical_fields, session.user, key)
if grant is not None else list(canonical_fields))
- hidden = perm_scope.hidden_keys(session.user, key, canonical_fields, st=session.runtime)
- visible = [field for field in visible if field.get("key") not in hidden]
if members:
hidden = set(access["hidden"])
- member_rows = builtin_scope.get("rows", permitted_rows)
- member_fields = builtin_scope.get("fields", canonical_fields)
for member in members:
- hidden.update(perm_scope.hidden_keys(member, key, member_fields, st=session.runtime))
+ hidden.update(perm_scope.hidden_keys(member, key, canonical_fields, st=session.runtime))
if mode not in ("schema", "query_schema"):
- member_rows = perm_scope.apply_row_scope(
- member_rows, member, key, builtin_scope.get("row_fields", canonical_fields),
- st=session.runtime)
- if builtin_scope and mode not in ("schema", "query_schema"):
- allowed_pids = {row.get("pid") for row in member_rows}
- permitted_rows = [row for row in permitted_rows if row.get("pid") in allowed_pids]
- elif not builtin_scope:
- permitted_rows = member_rows
+ permitted_rows = perm_scope.apply_row_scope(
+ permitted_rows, member, key, canonical_fields, st=session.runtime)
visible = [field for field in visible if field.get("key") not in hidden]
selected_keys = _assistant_requested_fields(fields, visible)
try:
@@ -1409,16 +1380,16 @@ def require_session(request: Request, response: Response) -> Session:
raise err(401, "no_session", "sign in to continue")
claims = aios_session.read(raw)
if not claims:
- raise err(401, "invalid_session", "your session has expired. Sign in again")
+ raise err(401, "invalid_session", "Your session ended. Sign in again.")
user = _user_for(claims)
if not user:
- raise err(401, "invalid_session", "your session has expired. Sign in again")
+ raise err(401, "invalid_session", "Your session ended. Sign in again.")
try:
rt = runtime.get_runtime(claims["t"])
except KeyError:
# An unknown tenant slug is a 401, not a 404: the cookie is not a valid identity for this
# deployment, and confirming which slugs exist would answer a question we were not asked.
- raise err(401, "invalid_session", "your session has expired. Sign in again")
+ raise err(401, "invalid_session", "Your session ended. Sign in again.")
fresh, _ = aios_session.mint(claims["t"], user["username"], int(user.get("epoch") or 0),
absolute_expiry=claims["x"])
aios_session.set_cookie(response, request, fresh)
@@ -1463,7 +1434,7 @@ def require_changes_session(request: Request, response: Response) -> Session | N
raw = request.cookies.get(aios_session.COOKIE_NAME)
claims = aios_session.read(raw) if raw else None
if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
- raise err(401, "invalid_session", "your session has expired. Sign in again")
+ raise err(401, "invalid_session", "Your session ended. Sign in again.")
return None
diff --git a/api/external_activity.py b/api/external_activity.py
index f355c870b71fa19448ef696cccfd39ba809a8b2f..e342478ef10fe2440256053f06eb8edec6f497a8 100644
--- a/api/external_activity.py
+++ b/api/external_activity.py
@@ -26,11 +26,15 @@ def _record(session, database, outcome, code):
label = next((row.get("label") for row in rows if row.get("id") == key_id), "")
except external_access.ExternalAccessError:
pass
- return audit.record("external.query", session.tenant, session.uname, {
+ detail = {
"key_id": key_id, "key_label": _text(label), "database": _text(database),
"outcome": outcome, "code": _text(code),
"via": _text(claims.get("external_via") or "api"),
- })
+ }
+ if getattr(session.runtime, "preview_only", False):
+ session.runtime.deferred_audits.append(detail)
+ return None
+ return audit.record("external.query", session.tenant, session.uname, detail)
def record_ok(session, database):
diff --git a/api/external_openapi.py b/api/external_openapi.py
index a4d5c28fa9dc6521b092363f654d1a2a7802cbef..fc6a1623065900738713a9ee0657a4da1ee3a9cd 100644
--- a/api/external_openapi.py
+++ b/api/external_openapi.py
@@ -37,6 +37,8 @@ def _record_name(database):
def _field_schema(field, source_kind):
+ if field.get("type") == "multiselect":
+ return {"type": ["string", "array", "null"], "items": {"type": "string"}}
kind = _JSON_TYPE.get(field.get("type"), "string")
types = [kind]
# Materialised table writes retain numeric cells as strings; reads preserve those bytes.
diff --git a/api/loopy_file_tools.py b/api/loopy_file_tools.py
index ab8303f855cd53d6c7e439d089d321285efc1758..09be3ce2fef4cf00cb50fc7d012ca4d9e9c8f6b4 100644
--- a/api/loopy_file_tools.py
+++ b/api/loopy_file_tools.py
@@ -20,8 +20,8 @@ def current_door(session=None):
return door
-def read_all(session, database, *, fields=None, filters=None, sorts=None):
- """Discover permitted fields and read every cursor page without a row cap."""
+def read_all(session, database, *, fields=None, filters=None, sorts=None, max_rows=None):
+ """Read every permitted cursor page, refusing exports above their declared file limit."""
import agent_runtime
from deps import err
@@ -36,15 +36,17 @@ def read_all(session, database, *, fields=None, filters=None, sorts=None):
raise err(400, "assistant_unknown_field", "Every requested field must be readable in this database.")
selected = list(dict.fromkeys(fields))
if not selected:
- raise ValueError("A PDF needs at least one readable field.")
+ raise ValueError("A file needs at least one readable field.")
payload = {"database": database, "limit": 500}
+ if max_rows is not None:
+ payload["aggregates"] = [{"fn": "count"}]
if fields is not None:
payload["fields"] = selected
if filters is not None:
payload["filters"] = copy.deepcopy(filters)
if sorts is not None:
payload["sorts"] = copy.deepcopy(sorts)
- records, seen = [], set()
+ records, seen, expected = [], set(), None
while True:
result = agent_runtime._dispatch(session, "query_database", payload)
rows, page = result.get("records"), result.get("page")
@@ -55,6 +57,27 @@ def read_all(session, database, *, fields=None, filters=None, sorts=None):
page_keys = [field.get("key") for field in result.get("fields", []) if isinstance(field, dict)]
if page_keys != [key for key in by_key if key in selected]:
raise err(409, "query_cursor_stale", "The readable fields changed. Ask again to read the complete list.")
+ if "offset" in page and (type(page["offset"]) is not int or page["offset"] != len(records)):
+ raise ValueError("The database skipped rows. Read the complete result again. No file was stored.")
+ counts = []
+ for container in (result, page):
+ for key in ("total", "total_count", "total_rows"):
+ if key in container:
+ counts.append(container[key])
+ aggregates = [item for item in result.get("aggregates", []) if isinstance(item, dict)
+ and item.get("fn") == "count" and item.get("field") is None]
+ if max_rows is not None and len(aggregates) != 1:
+ raise ValueError("The server did not supply its row count. Read the complete result again. No file was stored.")
+ counts.extend(item.get("value") for item in aggregates)
+ for count in counts:
+ if type(count) is not int or count < 0 or expected is not None and count != expected:
+ raise ValueError("The server count changed. Read the complete result again. No file was stored.")
+ expected = count
+ if max_rows is not None and max(len(records) + len(rows), expected or 0) > max_rows:
+ raise ValueError(f"Excel export exceeds the {max_rows:,}-data-row file limit. Filter the database and ask again. No rows were exported.")
+ if max_rows is not None:
+ from loopy_xlsx import check_size
+ check_size(max(len(records) + len(rows), expected or 0) + 1, len(selected))
records.extend({"pid": copy.deepcopy(row.get("pid")),
**{key: copy.deepcopy(row.get(key)) for key in selected}} for row in rows)
if not page["has_more"]:
@@ -66,8 +89,11 @@ def read_all(session, database, *, fields=None, filters=None, sorts=None):
raise ValueError("The database did not advance its readable cursor.")
seen.add(cursor)
payload = {**payload, "cursor": cursor}
+ if expected is not None and len(records) != expected:
+ raise ValueError("The server count differs from the rows read. Read the complete result again. No file was stored.")
return {"database": database, "label": schema.get("label") or database,
- "fields": [copy.deepcopy(by_key[key]) for key in selected], "records": records}
+ "fields": [copy.deepcopy(by_key[key]) for key in selected], "records": records,
+ "total": len(records)}
def _secure_link(link):
@@ -108,6 +134,7 @@ def make_pdf(session, args):
data = loopy_pdf.render_table(title, result["fields"], result["records"])
saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
mime="application/pdf", door=door,
+ sources=[args["database"]], amazon=args["database"].startswith("ut_amzn_"),
tool_call={"name": "make_pdf", "args": copy.deepcopy(args)})
link = (assistant_files.capability_url(session.runtime, saved["id"])
if door == "whatsapp" else saved["link"])
@@ -124,4 +151,210 @@ def _schema():
"required": ["database"], "additionalProperties": False}
-TOOLS = [{"name": "make_pdf", "schema": _schema(), "fn": make_pdf, "effect": "read"}]
+def _provenance(session, sources):
+ from deps import assistant_source_status
+
+ sources = list(dict.fromkeys(sources))
+ status = assistant_source_status(session, sources) if sources else {}
+ for source in sources:
+ row = status.get(source)
+ if not isinstance(row, dict) or row.get("permitted") is not True or row.get("answerable") is not True:
+ if isinstance(row, dict) and row.get("permitted") is True and row.get("reason"):
+ raise ValueError(str(row["reason"]) + ". Restore source availability and ask again. No file was stored.")
+ raise ValueError("An export source is unknown or unreadable. Restore source access or remove that binding and ask again.")
+ return sources, any(source.startswith("ut_amzn_") for source in sources)
+
+
+def _sheet_sources(value):
+ """Collect database provenance from permitted cells, bindings and source metadata."""
+ found = []
+ if isinstance(value, dict):
+ if "database" in value:
+ key = value["database"]
+ if not isinstance(key, str) or not key.strip():
+ raise ValueError("A Sheet source is unknown. Repair its binding and ask again.")
+ found.append(key)
+ for member in value.values():
+ found.extend(_sheet_sources(member))
+ elif isinstance(value, list):
+ for member in value:
+ found.extend(_sheet_sources(member))
+ return found
+
+
+def read_sheet_values(session, target, *, first_only=False):
+ """Read projected Sheet values through the caller's existing permission wall."""
+ import agent_runtime
+ from routes_sheet import read_sheet
+
+ book = read_sheet(target, tabs="meta", session=session)["workbook"]
+ tabs = []
+ selected = book.get("sheets") or []
+ if first_only:
+ selected = selected[:1]
+ for tab in selected:
+ result = agent_runtime._dispatch(session, "sheet_read_cells", {"workbook_id": target, "tab": tab["id"]})
+ if result.get("id") != book.get("id") or result.get("rev") != book.get("rev"):
+ raise ValueError("The workbook changed during export. Read the workbook again. No file was stored.")
+ if "cellCount" in tab and (type(tab["cellCount"]) is not int
+ or tab["cellCount"] != len(result["tab"].get("cells") or {})):
+ raise ValueError("The Sheet cell count differs from the cells read. Read the complete workbook again. No file was stored.")
+ tabs.append(result["tab"])
+ return book, tabs
+
+
+def make_xlsx(session, args):
+ """Export a complete database result or the caller's permitted Sheet workbook values."""
+ import assistant_files
+ import loopy_xlsx
+ from routes_query import _no_dashes
+
+ if session.tenant != assistant_files.assistant_log._tenant_of(session.runtime):
+ raise ValueError("The export session does not belong to this workspace. Sign in again.")
+ allowed = {"database", "fields", "filters", "sorts", "workbook_id", "title"}
+ if not isinstance(args, dict) or set(args) - allowed or ("database" in args) == ("workbook_id" in args):
+ raise ValueError("Choose one database or workbook_id to make an Excel file.")
+ target = args.get("database", args.get("workbook_id"))
+ if not isinstance(target, str) or not target.strip():
+ raise ValueError("An Excel file needs a database or workbook_id.")
+ if "title" in args and (not isinstance(args["title"], str) or not args["title"].strip()):
+ raise ValueError("An Excel file needs a title.")
+ door = current_door(session)
+ _secure_link(_links().app_link("#/assistant"))
+ if "database" in args:
+ sources, amazon = _provenance(session, [target])
+ result = read_all(session, target, fields=args.get("fields"), filters=args.get("filters"),
+ sorts=args.get("sorts"), max_rows=loopy_xlsx.MAX_ROWS - 1)
+ title = _no_dashes(args.get("title") or result["label"]).strip()[:200]
+ data = loopy_xlsx.render_table(title, result["fields"], result["records"], expected_count=result["total"])
+ count = result["total"]
+ else:
+ if set(args) & {"fields", "filters", "sorts"}:
+ raise ValueError("A Sheet export uses workbook_id and title. Database filters apply only to a database export.")
+ book, tabs = read_sheet_values(session, target)
+ sources, amazon = _provenance(session, _sheet_sources(tabs) + _sheet_sources(book.get("dataOrigins", [])))
+ title = _no_dashes(args.get("title") or book.get("name") or "Sheet workbook").strip()[:200]
+ data = loopy_xlsx.render_workbook(title, tabs)
+ count = None
+ # Recheck source access after a potentially long export, before storing bytes.
+ sources, amazon = _provenance(session, sources)
+ if amazon and door == "whatsapp":
+ raise ValueError("Amazon files cannot use a public download link. Export and download the file in the app instead. No file was stored.")
+ saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
+ mime=loopy_xlsx.MIME, door=door, sources=sources, amazon=amazon,
+ tool_call={"name": "make_xlsx", "args": copy.deepcopy(args)})
+ link = assistant_files.capability_url(session.runtime, saved["id"]) if door == "whatsapp" else saved["link"]
+ return {"ok": True, "fileId": saved["id"], "file_id": saved["file_id"],
+ "mime": saved["mime"], "bytes": saved["bytes"], "link": _secure_link(link),
+ "sources": sources, "amazon": amazon, "row_count": count}
+
+
+def _xlsx_schema():
+ schema = _schema()
+ schema["description"] = "Make an Excel file when asked, or for a table over 10 rows. Export every matching database row or a Sheet workbook's permitted values, with a file link."
+ schema["properties"]["workbook_id"] = {"type": "string", "minLength": 1}
+ schema.pop("required")
+ schema["oneOf"] = [{"required": ["database"]}, {"required": ["workbook_id"]}]
+ return schema
+
+
+def make_image(session, args):
+ """Make an image of a permitted table, labelled series, or first Sheet screen."""
+ import assistant_files
+ import loopy_image
+
+ if session.tenant != assistant_files.assistant_log._tenant_of(session.runtime):
+ raise ValueError("The image session does not belong to this workspace. Sign in again.")
+ common = {"kind", "title"}
+ allowed = common | {"database", "fields", "filters", "sorts", "workbook_id",
+ "label_field", "value_field", "series", "series_label"}
+ if not isinstance(args, dict) or set(args) - allowed or args.get("kind") not in ("table", "bar", "line", "sheet"):
+ raise ValueError("Choose table, bar, line, or sheet as the image kind and use its source arguments.")
+ if "title" in args and (not isinstance(args["title"], str) or not args["title"].strip()):
+ raise ValueError("An image needs a nonempty title. Add a short title and ask again.")
+ kind = args["kind"]
+ if kind == "sheet":
+ permitted, required = common | {"workbook_id"}, {"workbook_id"}
+ elif kind == "table":
+ permitted, required = common | {"database", "fields", "filters", "sorts"}, {"database"}
+ elif "database" in args:
+ permitted = common | {"database", "filters", "sorts", "label_field", "value_field", "series_label"}
+ required = {"database", "label_field", "value_field"}
+ else:
+ permitted, required = common | {"series", "series_label"}, {"series", "series_label"}
+ if set(args) - permitted or not required <= set(args):
+ raise ValueError("The image source arguments do not match its kind. Choose one database, Sheet, or labelled series and ask again.")
+ for key in (required - {"series"}) | ({"series_label"} if "series_label" in args else set()):
+ if not isinstance(args[key], str) or not args[key].strip():
+ raise ValueError(f"Image {key} must be nonempty text. Correct the source arguments and ask again.")
+ door = current_door(session)
+ _secure_link(_links().app_link("#/assistant"))
+ sources, amazon = [], False
+ count, columns = None, None
+ if kind == "sheet":
+ book, tabs = read_sheet_values(session, args["workbook_id"], first_only=True)
+ if not tabs:
+ raise ValueError("The Sheet has no readable tabs. Add a tab and ask again.")
+ sources, amazon = _provenance(session, _sheet_sources(tabs) + _sheet_sources(book.get("dataOrigins", [])))
+ title = args.get("title") or book.get("name") or "Sheet"
+ data = loopy_image.render_sheet(title, tabs[0])
+ labels, values, count, columns = loopy_image.sheet_values(tabs[0])
+ shown_rows, shown_columns = len(values), len(labels)
+ elif "database" in args:
+ sources, amazon = _provenance(session, [args["database"]])
+ fields = args.get("fields") if kind == "table" else [args["label_field"], args["value_field"]]
+ result = read_all(session, args["database"], fields=fields,
+ filters=args.get("filters"), sorts=args.get("sorts"))
+ title = args.get("title") or result["label"]
+ count = result["total"]
+ if kind == "table":
+ data = loopy_image.render_table(title, result["fields"], result["records"], expected_count=count)
+ columns = shown_columns = len(result["fields"])
+ shown_rows = min(count, loopy_image.MAX_ROWS)
+ else:
+ series = [{"label": row.get(args["label_field"]), "value": row.get(args["value_field"])} for row in result["records"]]
+ value_label = next(field.get("label") or field["key"] for field in result["fields"] if field["key"] == args["value_field"])
+ data = loopy_image.render_chart(title, series, kind=kind, series_label=args.get("series_label") or value_label)
+ shown_rows, shown_columns = count, None
+ else:
+ title = args.get("title") or "Chart"
+ data = loopy_image.render_chart(title, args["series"], kind=kind, series_label=args["series_label"])
+ count = shown_rows = len(args["series"])
+ shown_columns = None
+ sources, amazon = _provenance(session, sources)
+ if amazon and door == "whatsapp":
+ raise ValueError("Amazon images cannot use a public link. Export the image in the app instead. No file was stored.")
+ saved = assistant_files.save(session.runtime, session.uname, title=title, data=data,
+ mime=loopy_image.MIME, door=door, sources=sources, amazon=amazon,
+ tool_call={"name": "make_image", "args": copy.deepcopy(args)})
+ return {"ok": True, "fileId": saved["id"], "file_id": saved["file_id"],
+ "mime": saved["mime"], "bytes": saved["bytes"], "link": _secure_link(saved["link"]),
+ "sources": sources, "amazon": amazon, "row_count": count,
+ "column_count": columns, "shown_rows": shown_rows, "shown_columns": shown_columns}
+
+
+def _image_schema():
+ schema = _schema()
+ schema["description"] = "Make a PNG of a readable table, a bar or line chart, or a Sheet's first screen. Charts are images. A new Sheet uses its link plus this image. A table over 10 rows also needs make_xlsx. Wide images preserve cell widths."
+ schema["properties"].update({
+ "kind": {"type": "string", "enum": ["table", "bar", "line", "sheet"]},
+ "workbook_id": {"type": "string", "minLength": 1},
+ "label_field": {"type": "string", "minLength": 1},
+ "value_field": {"type": "string", "minLength": 1},
+ "series_label": {"type": "string", "minLength": 1},
+ "series": {"type": "array", "minItems": 1, "maxItems": 30,
+ "items": {"type": "object", "properties": {
+ "label": {"type": "string", "minLength": 1}, "value": {"type": "number"}},
+ "required": ["label", "value"], "additionalProperties": False}}})
+ schema["required"] = ["kind"]
+ schema["oneOf"] = [
+ {"properties": {"kind": {"const": "table"}}, "required": ["database"]},
+ {"properties": {"kind": {"const": "sheet"}}, "required": ["workbook_id"]},
+ {"properties": {"kind": {"enum": ["bar", "line"]}}, "required": ["database", "label_field", "value_field"]},
+ {"properties": {"kind": {"enum": ["bar", "line"]}}, "required": ["series", "series_label"]}]
+ return schema
+
+
+TOOLS = [{"name": "make_pdf", "schema": _schema(), "fn": make_pdf, "effect": "read"},
+ {"name": "make_xlsx", "schema": _xlsx_schema(), "fn": make_xlsx, "effect": "read"},
+ {"name": "make_image", "schema": _image_schema(), "fn": make_image, "effect": "read"}]
diff --git a/api/loopy_image.py b/api/loopy_image.py
new file mode 100644
index 0000000000000000000000000000000000000000..61becb12c7826cd5b47bfabb3ab06370b9b033b5
--- /dev/null
+++ b/api/loopy_image.py
@@ -0,0 +1,272 @@
+"""Draw authorized values as PNG files with Inter and no browser."""
+from collections.abc import Mapping
+from decimal import Decimal
+from io import BytesIO
+import math
+import os
+from pathlib import Path
+import re
+import unicodedata
+
+MIME = "image/png"
+MAX_ROWS = 30
+MAX_COLUMNS = 10
+MAX_BYTES = 20 * 1024 * 1024
+FONT_PATH = (Path(os.environ.get("RI_DIR") or Path(__file__).resolve().parents[2] / "platform")
+ / "static/fonts/Inter-var.woff2")
+PURPLE = "#5433CC"
+INK = "#202124"
+MUTED = "#656970"
+RULE = "#E5E7EB"
+_ADDRESS = re.compile(r"([A-Z]{1,3})([1-9][0-9]*)\Z")
+_NUMBER = re.compile(r"[($+\-\u00a3\u20ac]*\d[\d,]*(?:\.\d+)?[%)]*\Z")
+
+
+def _text(value):
+ if value is None:
+ return ""
+ if isinstance(value, bool):
+ return "Yes" if value else "No"
+ if isinstance(value, (float, Decimal)) and not math.isfinite(value):
+ raise ValueError("An image number is not finite. Correct the value and ask again.")
+ if not isinstance(value, (str, int, float, Decimal)):
+ raise ValueError("An image cell has an unsupported value. Use text or finite numbers and ask again.")
+ text = str(value).replace("\u2014", "-").replace("\u2013", "-")
+ if len(text) > 32_767:
+ raise ValueError("Image text exceeds the cell limit. Shorten the label and ask again.")
+ for char in text:
+ code = ord(char)
+ if char in "\n\r\t":
+ continue
+ if (unicodedata.category(char).startswith("C") or code >= 0x2500
+ or 0x250 <= code < 0x2000):
+ raise ValueError("Image text needs Latin characters without emoji. Replace unsupported characters and ask again.")
+ return " ".join(text.split())
+
+
+def _label(value):
+ text = _text(value)
+ return text[:1] + text[1:].lower() if text.isupper() else text
+
+
+def _numeric(value):
+ return (isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
+ or isinstance(value, str) and bool(_NUMBER.fullmatch(value.strip())))
+
+
+def _fonts():
+ from PIL import ImageFont
+
+ try:
+ return ImageFont.truetype(str(FONT_PATH), 17), ImageFont.truetype(str(FONT_PATH), 23)
+ except OSError as exc:
+ raise ValueError("The Inter image font is missing or unreadable. Include the font and its OFL licence in deployment assets.") from exc
+
+
+def _fit(draw, text, font, width):
+ if draw.textlength(text, font=font) <= width:
+ return text
+ low, high = 0, len(text)
+ while low < high:
+ middle = (low + high + 1) // 2
+ if draw.textlength(text[:middle] + "...", font=font) <= width:
+ low = middle
+ else:
+ high = middle - 1
+ return text[:low] + "..."
+
+
+def _png(image, description):
+ from PIL.PngImagePlugin import PngInfo
+
+ info = PngInfo()
+ info.add_text("Description", description)
+ output = BytesIO()
+ image.save(output, format="PNG", pnginfo=info)
+ data = output.getvalue()
+ if len(data) > MAX_BYTES:
+ raise ValueError("The image exceeds the 20 MiB limit. Select fewer fields and ask again.")
+ return data
+
+
+def table_values(columns, rows, *, expected_count=None):
+ """Prepare at most 30 rows while preserving the complete source count."""
+ if not isinstance(rows, (list, tuple)) or not isinstance(columns, (list, tuple)) or not 1 <= len(columns) <= 30:
+ raise ValueError("An image table needs 1 to 30 columns and a row list. Select readable fields and ask again.")
+ if expected_count is not None and (type(expected_count) is not int or expected_count != len(rows)):
+ raise ValueError("The image source count differs from the rows read. Read the complete result and ask again.")
+ fields = [dict(column) if isinstance(column, Mapping) else {"key": column} for column in columns]
+ if any(not isinstance(field.get("key"), str) or not field["key"] for field in fields):
+ raise ValueError("An image column needs a field key. Choose readable fields and ask again.")
+ labels = [_label(field.get("label") or field["key"]) for field in fields]
+ prepared = []
+ for row in rows[:MAX_ROWS]:
+ if isinstance(row, Mapping):
+ values = [row.get(field["key"]) for field in fields]
+ elif isinstance(row, (list, tuple)) and len(row) == len(fields):
+ values = row
+ else:
+ raise ValueError("An image row does not match its columns. Correct the source and ask again.")
+ prepared.append([(_text(value), _numeric(value)) for value in values])
+ return labels, prepared, len(rows)
+
+
+def _draw_table(title, labels, rows, footer, *, row_numbers=False):
+ from PIL import Image, ImageDraw
+
+ font, heading = _fonts()
+ measure = ImageDraw.Draw(Image.new("RGB", (1, 1)))
+ widths = []
+ for index, label in enumerate(labels):
+ longest = max([measure.textlength(label, font=font),
+ *(measure.textlength(row[index][0], font=font) for row in rows)])
+ widths.append(max(100, min(230, math.ceil(longest) + 24)))
+ gutter = 42 if row_numbers else 0
+ widths[-1] += max(0, 390 - (sum(widths) + 32 + gutter))
+ width = sum(widths) + 32 + gutter
+ height = 132 + 38 * len(rows)
+ image = Image.new("RGB", (width, height), "white")
+ draw = ImageDraw.Draw(image)
+ title = _label(title)
+ if not title:
+ raise ValueError("An image needs a title. Add a short title and ask again.")
+ draw.text((16, 18), _fit(draw, title, heading, width - 32), font=heading, fill=INK)
+ x = 16 + gutter
+ for label, cell_width in zip(labels, widths):
+ draw.text((x + 12, 70), _fit(draw, label, font, cell_width - 24), font=font, fill=MUTED, anchor="lm")
+ x += cell_width
+ draw.line((16, 89, width - 16, 89), fill=RULE)
+ for index, row in enumerate(rows):
+ y, x = 108 + 38 * index, 16 + gutter
+ if row_numbers:
+ draw.text((16 + gutter - 10, y), str(index + 1), font=font, fill=MUTED, anchor="rm")
+ for (text, numeric), cell_width in zip(row, widths):
+ fitted = _fit(draw, text, font, cell_width - 24)
+ draw.text((x + cell_width - 12 if numeric else x + 12, y), fitted,
+ font=font, fill=INK, anchor="rm" if numeric else "lm", features=["tnum"])
+ x += cell_width
+ draw.line((16, y + 19, width - 16, y + 19), fill=RULE)
+ draw.text((16, height - 24), _fit(draw, footer, font, width - 32), font=font, fill=MUTED, anchor="lm")
+ return _png(image, footer)
+
+
+def render_table(title, columns, rows, *, expected_count=None):
+ """Draw a full-width table with right-aligned numbers and an accurate cut line."""
+ labels, values, total = table_values(columns, rows, expected_count=expected_count)
+ footer = f"Showing {len(values)} of {total} rows" if total > MAX_ROWS else f"{total} rows"
+ return _draw_table(title, labels, values, footer)
+
+
+def sheet_values(tab):
+ """Read the first screen of an already authorized, projected Sheet tab."""
+ if not isinstance(tab, Mapping) or not isinstance(tab.get("cells", {}), Mapping):
+ raise ValueError("The Sheet has no readable cells. Read its permitted values and ask again.")
+ values, extent_row, extent_col = {}, 0, 0
+ for address, cell in tab.get("cells", {}).items():
+ match = _ADDRESS.fullmatch(address) if isinstance(address, str) else None
+ if not match or not isinstance(cell, Mapping):
+ raise ValueError("A Sheet cell is invalid. Repair its address and ask again.")
+ col = 0
+ for char in match[1]:
+ col = col * 26 + ord(char) - 64
+ row = int(match[2])
+ extent_row, extent_col = max(extent_row, row), max(extent_col, col)
+ if row > MAX_ROWS or col > MAX_COLUMNS:
+ continue
+ binding = cell.get("binding") or {}
+ if isinstance(binding, Mapping) and (binding.get("mode") == "view" or binding.get("kind") == "view"):
+ raise ValueError("A placed View has no safe image cell value. Export its readable database instead.")
+ if cell.get("refusal") or cell.get("state") in ("refused", "stale"):
+ raise ValueError("A Sheet value needs refresh or permission. Refresh its readable sources and ask again.")
+ if cell.get("kind") in ("bound", "formula") and "value" not in cell:
+ raise ValueError("A Sheet calculation has no authorized value. Refresh the Sheet and ask again.")
+ value = None if cell.get("kind") == "empty" else cell.get("value", cell.get("text"))
+ _text(value)
+ display = cell.get("display", value) if value is not None else None
+ values[row, col] = (_text(display), _numeric(value))
+ rows, cols = min(MAX_ROWS, max(1, extent_row)), min(MAX_COLUMNS, max(1, extent_col))
+ return ([chr(65 + index) for index in range(cols)],
+ [[values.get((row, col), ("", False)) for col in range(1, cols + 1)] for row in range(1, rows + 1)],
+ extent_row, extent_col)
+
+
+def render_sheet(title, tab):
+ """Draw the first 30 rows and 10 columns without shrinking readable cells."""
+ labels, values, rows, cols = sheet_values(tab)
+ footer = (f"Showing {len(values)} of {rows} rows, {len(labels)} of {cols} columns"
+ if rows else "No populated cells. Limit: 30 rows, 10 columns")
+ return _draw_table(title, labels, values, footer, row_numbers=True)
+
+
+def chart_values(series):
+ if not isinstance(series, (list, tuple)) or not 1 <= len(series) <= MAX_ROWS:
+ raise ValueError("A chart needs 1 to 30 labelled points. Filter or aggregate the series and ask again.")
+ points = []
+ for point in series:
+ if not isinstance(point, Mapping) or set(point) != {"label", "value"}:
+ raise ValueError("Each chart point needs label and value. Correct the series and ask again.")
+ label, value = point["label"], point["value"]
+ if not isinstance(label, str) or not _text(label) or isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
+ raise ValueError("A chart point needs a text label and a number. Correct the series and ask again.")
+ try:
+ value = float(value)
+ except (OverflowError, ValueError) as exc:
+ raise ValueError("A chart number is outside the supported range. Use finite numbers and ask again.") from exc
+ if not math.isfinite(value) or abs(value) > 1e100:
+ raise ValueError("A chart number is outside the supported range. Use finite numbers below 1e100 and ask again.")
+ points.append((_text(label), value))
+ return points
+
+
+def render_chart(title, series, *, kind="bar", series_label="Series"):
+ """Draw a labelled purple series on one axis, including negative and zero values."""
+ points = chart_values(series)
+ if kind not in ("bar", "line") or not isinstance(series_label, str) or not _text(series_label):
+ raise ValueError("A chart needs bar or line and a series label. Correct the chart arguments and ask again.")
+ from PIL import Image, ImageDraw
+
+ font, heading = _fonts()
+ width, height = max(390, 96 + 72 * len(points)), 410
+ image = Image.new("RGB", (width, height), "white")
+ draw = ImageDraw.Draw(image)
+ title = _label(title)
+ if not title:
+ raise ValueError("An image needs a title. Add a short title and ask again.")
+ draw.text((16, 18), _fit(draw, title, heading, width - 32), font=heading, fill=INK)
+ draw.line((16, 67, 34, 67), fill=PURPLE, width=4)
+ draw.text((42, 67), _fit(draw, _label(series_label), font, width - 58), font=font, fill=INK, anchor="lm")
+ low, high = min(0, *(value for _, value in points)), max(0, *(value for _, value in points))
+ if low == high:
+ low, high = -1, 1
+ else:
+ span = high - low
+ low, high = low - span * .12, high + span * .12
+ ticks = [low + (high - low) * index / 4 for index in range(5)]
+ tick_labels = [format(value, ".3g") for value in ticks]
+ left = max(66, math.ceil(max(draw.textlength(label, font=font) for label in tick_labels)) + 26)
+ top, bottom, right = 102, 310, width - 20
+ def y(value):
+ return bottom - (value - low) / (high - low) * (bottom - top)
+ for tick, label in zip(ticks, tick_labels):
+ draw.line((left, y(tick), right, y(tick)), fill=RULE)
+ draw.text((left - 10, y(tick)), label, font=font, fill=MUTED, anchor="rm", features=["tnum"])
+ zero = y(0)
+ draw.line((left, top, left, bottom), fill=MUTED)
+ draw.line((left, zero, right, zero), fill=MUTED)
+ step = (right - left) / len(points)
+ positions = []
+ for index, (label, value) in enumerate(points):
+ x, py = left + (index + .5) * step, y(value)
+ positions.append((x, py))
+ if kind == "bar":
+ draw.rectangle((x - step * .28, min(zero, py), x + step * .28, max(zero, py)), fill=PURPLE)
+ draw.text((x, bottom + 24), _fit(draw, label, font, step - 8), font=font, fill=INK, anchor="mm")
+ draw.text((x, py - 13 if value >= 0 else py + 15), format(value, ".4g"), font=font, fill=INK, anchor="mm", features=["tnum"])
+ if kind == "line":
+ if len(positions) > 1:
+ draw.line(positions, fill=PURPLE, width=3)
+ for x, py in positions:
+ draw.ellipse((x - 4, py - 4, x + 4, py + 4), fill=PURPLE)
+ footer = f"{len(points)} labelled points"
+ draw.text((16, height - 24), footer, font=font, fill=MUTED, anchor="lm")
+ return _png(image, footer)
diff --git a/api/loopy_links.py b/api/loopy_links.py
index e23042207fb3d13f0611951d8a4ca64860ea5972..726aeade64feddeec9d8805f200748776781b03c 100644
--- a/api/loopy_links.py
+++ b/api/loopy_links.py
@@ -44,6 +44,60 @@ def artifact_link(item_id: str) -> str | None:
return app_link("#/artifacts?item=" + quote(str(item_id), safe=""))
+_SHARE_TOKEN = re.compile(r"[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+")
+
+
+def shared_artifact_link(token) -> str | None:
+ """Build the signed read-only page link `{base}/a/` (C7, R85)."""
+ base = public_base()
+ if base is None or not isinstance(token, str) or _SHARE_TOKEN.fullmatch(token) is None:
+ return None
+ return base + "/a/" + token
+
+
+NO_LINK_NOTE = "Links are not set up on this server yet, so this has no link."
+
+
+def _value(value) -> str | None:
+ """Encode one route value as a query value, or None when it is empty."""
+ text = "" if value is None or isinstance(value, bool) else str(value).strip()
+ return quote(text, safe="") if text else None
+
+
+def _route(path: str, *pairs, optional=()) -> str | None:
+ """Build an absolute link when every required value is present."""
+ values = [(name, _value(value)) for name, value in pairs]
+ if any(encoded is None for _, encoded in values):
+ return None
+ values += [(name, encoded) for name, encoded in ((n, _value(v)) for n, v in optional) if encoded]
+ return app_link(path + "?" + "&".join(f"{name}={encoded}" for name, encoded in values))
+
+
+def sheet_link(workbook_id, tab=None) -> str | None:
+ """Link to a Sheet workbook, matching the client sheetAddressHash."""
+ return _route("#/sheet", ("wb", workbook_id), optional=(("tab", tab),))
+
+
+def view_link(database, view_id) -> str | None:
+ """Link to a saved View, matching the client dataAddressHash."""
+ return _route("#/data", ("database", database), ("view", view_id))
+
+
+def application_link(app_id, database) -> str | None:
+ """Link to an App, matching the client appPathHash (the database is required)."""
+ return _route("#/app", ("database", database), ("application", app_id))
+
+
+def records_link(database, view_id=None) -> str | None:
+ """Link to a database record list, optionally opened on one View."""
+ return _route("#/data", ("database", database), optional=(("view", view_id),))
+
+
+def query_link(view_id) -> str | None:
+ """Link to a saved Query answer."""
+ return _route("#/query", ("view", view_id))
+
+
def absolutize_text(text: str) -> str:
"""Expand standalone app fragments while preserving existing absolute URLs."""
base = public_base()
diff --git a/api/loopy_skill_tools.py b/api/loopy_skill_tools.py
index 78ac5b3ae8e70ef57f0d79f2049fac32e45bb24e..2f697a2de4f39619cf7e86297fac735f504da691 100644
--- a/api/loopy_skill_tools.py
+++ b/api/loopy_skill_tools.py
@@ -1,4 +1,4 @@
-"""Read-only Assistant tools for the current caller's code-held procedures."""
+"""Assistant tools for the caller's code-held procedures and saved tools."""
def skill_list(session, args):
@@ -18,7 +18,110 @@ def skill_read(session, args):
return read_skill(session, args["key"].strip())
+def database_notes(session, args):
+ from loopy_skills import database_notes as notes
+
+ if (not isinstance(args, dict) or set(args) != {"database"}
+ or not isinstance(args["database"], str) or not args["database"].strip()):
+ raise ValueError("Choose a database key from the database list.")
+ return notes(session, args["database"].strip())
+
+
+def _tool_name(args, *keys):
+ if not isinstance(args, dict) or set(args) - set(keys) or not isinstance(args.get("name"), str):
+ raise ValueError("Choose a saved tool name from tool_list.")
+ return args["name"].strip()
+
+
+def _refusal(fn):
+ """Return a store refusal as a tool result, so the model can tell the user why."""
+ from loopy_tool_store import ToolRefusal
+
+ try:
+ return fn()
+ except ToolRefusal as exc:
+ return {"ok": False, "error": str(exc)}
+
+
+def tool_save(session, args):
+ import routes_query
+ from loopy_tool_store import save
+
+ if not isinstance(args, dict):
+ raise ValueError("Give the tool a name, a title and its steps.")
+ door = routes_query._AGENT_DOOR.get()
+ return _refusal(lambda: {"ok": True, "saved": save(session, args, door=door),
+ "message": "Saved for you. Ask to share it if the workspace should use it."})
+
+
+def tool_list(session, args):
+ from loopy_tool_store import pending_shares, visible
+
+ if not isinstance(args, dict) or args:
+ raise ValueError("List saved tools without arguments.")
+ mine, shared = visible(session)
+ return {"personal": mine, "workspace": shared, "shareRequests": pending_shares(session)}
+
+
+def tool_run(session, args):
+ import routes_query
+ from loopy_tool_store import run
+
+ name = _tool_name(args, "name")
+ turn = routes_query._AGENT_TURN.get() or {}
+ return _refusal(lambda: run(session, name, door=routes_query._AGENT_DOOR.get(), handle=turn.get("handle")))
+
+
+def tool_share(session, args):
+ from loopy_tool_store import request_share
+
+ name = _tool_name(args, "name")
+ return _refusal(lambda: request_share(session, name))
+
+
+def tool_share_decide(session, args):
+ from loopy_tool_store import decide_share
+
+ if (not isinstance(args, dict) or set(args) != {"request", "decision"}
+ or not isinstance(args["request"], str) or args["decision"] not in ("yes", "no")):
+ raise ValueError("Give the share request id and the Administrator's yes or no.")
+ return _refusal(lambda: decide_share(session, args["request"].strip(), args["decision"] == "yes"))
+
+
+_STEP = {"type": "object", "properties": {
+ "tool": {"type": "string", "minLength": 1,
+ "description": "An existing read tool, for example query_database for a query recipe."},
+ "args": {"type": "object", "description": "The arguments for that tool, as you would call it."}},
+ "required": ["tool", "args"], "additionalProperties": False}
+_NAME = {"type": "string", "pattern": "^[a-z0-9_]{1,40}$"}
+
TOOLS = [
+ {"name": "tool_save", "effect": "write", "fn": tool_save,
+ "schema": {"type": "object",
+ "description": ("Save a named tool for the user: the read steps and query recipes of an answer. "
+ "Use it when the user asks to save an answer as a tool. It runs no code."),
+ "properties": {"name": _NAME, "title": {"type": "string", "maxLength": 80},
+ "description": {"type": "string", "maxLength": 300},
+ "steps": {"type": "array", "minItems": 1, "maxItems": 12, "items": _STEP}},
+ "required": ["name", "title", "steps"], "additionalProperties": False}},
+ {"name": "tool_list", "effect": "read", "fn": tool_list,
+ "schema": {"type": "object",
+ "description": "List your saved tools, the workspace tools you can use, and share requests for an Administrator.",
+ "properties": {}, "additionalProperties": False}},
+ {"name": "tool_run", "effect": "read", "fn": tool_run,
+ "schema": {"type": "object",
+ "description": "Run a saved tool by name and return each step's result. Use it when a question matches a saved tool.",
+ "properties": {"name": _NAME}, "required": ["name"], "additionalProperties": False}},
+ {"name": "tool_share", "effect": "write", "fn": tool_share,
+ "schema": {"type": "object",
+ "description": "Ask to share one of your saved tools with the workspace. An Administrator must say yes.",
+ "properties": {"name": _NAME}, "required": ["name"], "additionalProperties": False}},
+ {"name": "tool_share_decide", "effect": "write", "fn": tool_share_decide,
+ "schema": {"type": "object",
+ "description": "Record an Administrator's yes or no to a share request. Ask the user first.",
+ "properties": {"request": {"type": "string", "minLength": 1},
+ "decision": {"type": "string", "enum": ["yes", "no"]}},
+ "required": ["request", "decision"], "additionalProperties": False}},
{"name": "skill_list", "effect": "read", "fn": skill_list,
"schema": {"type": "object", "description": "List the connector and app skills you can read in this workspace.",
"properties": {}, "additionalProperties": False}},
@@ -26,4 +129,9 @@ TOOLS = [
"schema": {"type": "object", "description": "Read the steps for a skill from your current skill list.",
"properties": {"key": {"type": "string", "minLength": 1}},
"required": ["key"], "additionalProperties": False}},
+ {"name": "database_notes", "effect": "read", "fn": database_notes,
+ "schema": {"type": "object",
+ "description": "Read what one row is, the key fields, joins, scope rules and known traps for a database before you query it.",
+ "properties": {"database": {"type": "string", "minLength": 1}},
+ "required": ["database"], "additionalProperties": False}},
]
diff --git a/api/loopy_skills.py b/api/loopy_skills.py
index a24f9cb8d4edaf0929450027b5e29e434b5dffcb..bbd48c5408c62fe88f302c62bcf4a63b44ab1a34 100644
--- a/api/loopy_skills.py
+++ b/api/loopy_skills.py
@@ -97,6 +97,98 @@ def list_skills(session):
for record in SKILLS if record["applies_when"](session)]
+#: Skill key to its knowledge pack file in platform/model/knowledge. A new source adds one row.
+KNOWLEDGE_PACKS = {"odoo": "odoo.yml", "amazon": "amazon.yml"}
+_PACK_CACHE = {}
+#: A connection-namespaced key is ``, as odoo_relational.CONNECTION_SEP.
+_CONNECTION_SEP = "__"
+
+
+def knowledge_dir():
+ """Return platform/model/knowledge, found beside the `core` package in every layout."""
+ from pathlib import Path
+
+ import core
+
+ # `core` is a namespace package: it has a __path__ and no __file__.
+ dirs = [Path(p).resolve().parent / "model" / "knowledge" for p in core.__path__]
+ return next((d for d in dirs if d.is_dir()), dirs[0])
+
+
+def load_pack(skill_key):
+ """Return one source's parsed knowledge pack, read once per process, or None if unmapped."""
+ name = KNOWLEDGE_PACKS.get(skill_key)
+ if name is None:
+ return None
+ if skill_key not in _PACK_CACHE:
+ import yaml
+
+ with open(knowledge_dir() / name, encoding="utf-8") as handle:
+ _PACK_CACHE[skill_key] = yaml.safe_load(handle)
+ return _PACK_CACHE[skill_key]
+
+
+def pack_base_key(pack, key):
+ """Return the pack's entry key for a database key, its generated prefix, or None."""
+ databases = pack.get("databases") or {}
+ prefix = (pack.get("generated_tables") or {}).get("prefix")
+ base, sep, cid = key.rpartition(_CONNECTION_SEP)
+ for candidate in ((key, base) if sep and cid else (key,)):
+ if candidate in databases:
+ return candidate
+ if prefix and candidate.startswith(prefix):
+ return prefix
+ return None
+
+
+def _openable(session, keys):
+ """Return the subset of database keys this caller may read now."""
+ from deps import assistant_source_status
+
+ status = assistant_source_status(session, list(keys) if keys is not None else None)
+ return {key for key, value in status.items()
+ if (keys is None or key in keys) and value.get("permitted") and _opens(session, key)}
+
+
+def pack_for(pack, openable):
+ """Return the pack's scope, pack traps and only the entries an openable key maps to."""
+ entries, generated = {}, None
+ prefix = (pack.get("generated_tables") or {}).get("prefix")
+ for key in sorted(openable):
+ base = pack_base_key(pack, key)
+ if base is None:
+ continue
+ if base == prefix:
+ generated = pack["generated_tables"]
+ else:
+ entries[base] = pack["databases"][base]
+ knowledge = {"scope": pack.get("scope") or {}, "traps": list(pack.get("traps") or ()),
+ "databases": entries}
+ if generated is not None:
+ knowledge["generated_tables"] = generated
+ return knowledge
+
+
+def database_notes(session, database):
+ """Return one database's notes with its source's scope and traps, if the caller can open it."""
+ from deps import err
+
+ for skill_key in KNOWLEDGE_PACKS:
+ pack = load_pack(skill_key)
+ base = pack_base_key(pack, database)
+ if base is None:
+ continue
+ if not (_connected(session, pack.get("connector") or skill_key)
+ and database in _openable(session, [database])):
+ break
+ knowledge = pack_for(pack, {database})
+ notes = knowledge["databases"].get(base) or knowledge.get("generated_tables")
+ return {"source": skill_key, "database": database, "notes": notes,
+ "scope": knowledge["scope"], "traps": knowledge["traps"]}
+ raise err(404, "database_notes_unavailable",
+ "Notes for that database are not available for your current permissions and connections.")
+
+
def read_skill(session, key):
"""Recheck access and return an exact procedure with only installed tool names."""
import agent_tools
@@ -113,10 +205,24 @@ def read_skill(session, key):
steps = list(record["steps"])
if not tools:
steps = ["This skill's tools are not available in this build. Try again after they are installed."]
- return {"key": record["key"], "title": record["title"], "steps": steps, "tools": tools}
+ result = {"key": record["key"], "title": record["title"], "steps": steps, "tools": tools}
+ pack = load_pack(key)
+ if pack is not None:
+ result["knowledge"] = pack_for(pack, _openable(session, None))
+ return result
+
+
+#: The prompt_index sentence that sends the agent to a source's notes first.
+NOTES_SENTENCE = ("Before you query a source's database, read its notes with database_notes "
+ "or that source's skill.")
def prompt_index(session):
"""Return the permissioned one-line skill index for the system prompt."""
labels = [f"{record['key']} ({record['title']})" for record in list_skills(session)]
- return "Skills you can read: " + (", ".join(labels) if labels else "none") + "."
+ index = "Skills you can read: " + (", ".join(labels) if labels else "none") + "."
+ index = index + " " + NOTES_SENTENCE if labels else index
+ from loopy_tool_store import prompt_lines
+
+ tools = prompt_lines(session)
+ return index + "\n" + tools if tools else index
diff --git a/api/loopy_tool_store.py b/api/loopy_tool_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..eca5cd1e58e461da7f9d162efaba9c3c5962e808
--- /dev/null
+++ b/api/loopy_tool_store.py
@@ -0,0 +1,351 @@
+"""Saved Assistant tools: named read-only steps, kept per user and shared on an Administrator's yes (R88).
+
+A saved tool runs no code. Each step is an existing read tool call with its arguments, and a query
+recipe is a `query_database` step. Every step runs as the caller, through `agent_runtime.execute`.
+Tool creation and the share inbox have no screen (R81): both live in the chat.
+"""
+import copy
+import json
+import re
+import secrets
+from datetime import datetime, timezone
+
+#: One per-tenant document: `{"users": {username: {name: tool}}, "workspace": {name: tool}}`.
+STORE_KEY = "loopy_saved_tools"
+#: Share requests reuse the harness proposal record under this reserved id. No agent has it, so
+#: the harness routes refuse it with 404 at `agent_wall`.
+SHARE_AGENT = "loopy:tools"
+SHARE_KIND = "tool_share"
+NAME_RE = re.compile(r"[a-z0-9_]{1,40}")
+MAX_STEPS = 12
+MAX_ARGS_BYTES = 8 * 1024
+MAX_TITLE = 80
+MAX_DESCRIPTION = 300
+MAX_USER_TOOLS = 50
+MAX_WORKSPACE_TOOLS = 100
+MAX_STEP_RESULT_CHARS = 3000
+#: Read tools that are not a data read: they mint links or touch the tool store itself.
+_NOT_SAVEABLE = {"confirm_change", "connector_setup_link"}
+
+
+class ToolRefusal(ValueError):
+ """A saved tool request the store refuses, with a plain sentence for the user."""
+
+
+def _now():
+ from core import write_execution
+ return write_execution.utcnow().isoformat(timespec="seconds")
+
+
+def _is_admin(session):
+ import core.perms as perms
+
+ return bool(perms.is_admin(session.user))
+
+
+def _doc(runtime):
+ raw = runtime.get(STORE_KEY) or {}
+ raw = raw if isinstance(raw, dict) else {}
+ users = raw.get("users") if isinstance(raw.get("users"), dict) else {}
+ workspace = raw.get("workspace") if isinstance(raw.get("workspace"), dict) else {}
+ return {"users": users, "workspace": workspace}
+
+
+def _available_tools():
+ import agent_tools
+ from core import external_tools
+
+ agent_tools.load_modules()
+ return set(external_tools.TOOLS) | set(agent_tools.registered())
+
+
+def step_databases(value, found=None):
+ """Every `database` string named anywhere in a step's arguments."""
+ found = set() if found is None else found
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if key == "database" and isinstance(item, str) and item.strip():
+ found.add(item.strip())
+ else:
+ step_databases(item, found)
+ elif isinstance(value, list):
+ for item in value:
+ step_databases(item, found)
+ return found
+
+
+def unreadable(session, databases):
+ """The databases in this set that the caller cannot read now."""
+ if not databases:
+ return set()
+ from loopy_skills import _openable
+
+ return set(databases) - _openable(session, sorted(databases))
+
+
+def _check_step(step, available):
+ """Return one clean step, or raise ToolRefusal for a step a saved tool may not hold."""
+ import agent_tools
+
+ if not isinstance(step, dict) or set(step) - {"tool", "args"} or not isinstance(step.get("tool"), str):
+ raise ToolRefusal("Each step needs a tool name and its arguments.")
+ name, args = step["tool"].strip(), step.get("args") if step.get("args") is not None else {}
+ if not isinstance(args, dict):
+ raise ToolRefusal(f"The arguments for step {name} must be an object.")
+ if name in _NOT_SAVEABLE or name.startswith("tool_"):
+ raise ToolRefusal(f"A saved tool cannot use {name}.")
+ if name not in available:
+ raise ToolRefusal(f"There is no tool called {name}.")
+ if agent_tools.classify(name, args) != "read":
+ raise ToolRefusal(f"A saved tool only reads. The step {name} would change or remove data.")
+ try:
+ size = len(json.dumps(args, allow_nan=False, ensure_ascii=False).encode("utf-8"))
+ except (TypeError, ValueError):
+ raise ToolRefusal(f"The arguments for step {name} must be plain values.")
+ if size > MAX_ARGS_BYTES:
+ raise ToolRefusal(f"The arguments for step {name} are over {MAX_ARGS_BYTES // 1024} KB.")
+ return {"tool": name, "args": copy.deepcopy(args)}
+
+
+def clean(session, raw):
+ """Validate a tool from the model. Databases come from the steps, never from the model."""
+ if not isinstance(raw, dict):
+ raise ToolRefusal("A saved tool needs a name, a title and its steps.")
+ name = str(raw.get("name") or "").strip()
+ if not NAME_RE.fullmatch(name):
+ raise ToolRefusal("A tool name uses 1 to 40 lowercase letters, digits or underscores.")
+ title = " ".join(str(raw.get("title") or "").split())[:MAX_TITLE] or name.replace("_", " ")
+ description = " ".join(str(raw.get("description") or "").split())[:MAX_DESCRIPTION]
+ steps = raw.get("steps")
+ if not isinstance(steps, list) or not 1 <= len(steps) <= MAX_STEPS:
+ raise ToolRefusal(f"A saved tool has 1 to {MAX_STEPS} steps.")
+ available = _available_tools()
+ steps = [_check_step(step, available) for step in steps]
+ databases = set()
+ for step in steps:
+ step_databases(step["args"], databases)
+ blocked = unreadable(session, databases)
+ if blocked:
+ raise ToolRefusal("You cannot read " + ", ".join(sorted(blocked)) + ", so a tool cannot use it.")
+ return {"name": name, "title": title, "description": description, "steps": steps,
+ "databases": sorted(databases)}
+
+
+def public(tool, scope):
+ return {"name": tool["name"], "title": tool.get("title") or "", "description": tool.get("description") or "",
+ "scope": scope, "owner": tool.get("owner") or "", "version": int(tool.get("version") or 1),
+ "databases": list(tool.get("databases") or ()), "steps": copy.deepcopy(tool.get("steps") or []),
+ **({"approvedBy": tool["approvedBy"]} if tool.get("approvedBy") else {})}
+
+
+def _put(tools, tool, cap, **extra):
+ """Store one tool in a name map in place, bumping the version of an existing name."""
+ prior = tools.get(tool["name"]) if isinstance(tools.get(tool["name"]), dict) else None
+ if prior is None and len(tools) >= cap:
+ raise ToolRefusal(f"There are already {cap} saved tools here. Remove one before you add another.")
+ now = _now()
+ stored = {**copy.deepcopy(tool), **extra, "version": int((prior or {}).get("version") or 0) + 1,
+ "createdAt": (prior or {}).get("createdAt") or now, "updatedAt": now}
+ tools[tool["name"]] = stored
+ return stored
+
+
+def _execute_steps(session, steps, *, door, handle=None):
+ """Run read steps as the caller and return `(results, error)`; error names the first failed step."""
+ import agent_runtime
+
+ turn = {"toolCalls": [], "pendingDelete": None, "artifacts": [], "handle": handle}
+ results, error = [], None
+ for number, step in enumerate(steps, 1):
+ result = agent_runtime.execute(session, step["tool"], step["args"], door=door, turn=turn)
+ if isinstance(result, dict) and result.get("stopped"):
+ return None, "stopped"
+ ok = bool(turn["toolCalls"][-1].get("ok"))
+ if not ok and error is None:
+ reason = result.get("error") if isinstance(result, dict) else None
+ error = f"Step {number} ({step['tool']}) failed: {reason or 'the tool refused it'}"
+ text = json.dumps(result, default=str, ensure_ascii=False)
+ if len(text) > MAX_STEP_RESULT_CHARS:
+ result = {"truncated": True, "text": text[:MAX_STEP_RESULT_CHARS]}
+ results.append({"tool": step["tool"], "args": copy.deepcopy(step["args"]), "ok": ok, "result": result})
+ return results, error
+
+
+def save(session, raw, *, door="app"):
+ """Try the steps as the caller, then save the tool for the caller at once. The same name is a new version."""
+ tool = clean(session, raw)
+ _results, error = _execute_steps(session, tool["steps"], door=door)
+ if error:
+ raise ToolRefusal(f"{error.rstrip('.')}. The tool was not saved. Fix that step and save again.")
+ saved = {}
+
+ def update(current):
+ saved.clear()
+ doc = _doc_from(current)
+ mine = dict(doc["users"].get(session.uname) or {})
+ saved.update(_put(mine, tool, MAX_USER_TOOLS, owner=session.uname))
+ doc["users"][session.uname] = mine
+ return doc
+
+ session.runtime.update(STORE_KEY, update, flush="sync")
+ return public(saved, "personal")
+
+
+def _doc_from(current):
+ raw = copy.deepcopy(current) if isinstance(current, dict) else {}
+ return {"users": dict(raw.get("users") or {}), "workspace": dict(raw.get("workspace") or {})}
+
+
+def find(session, name):
+ """The caller's own tool by name, else a workspace tool, with its scope, or (None, None)."""
+ doc = _doc(session.runtime)
+ mine = (doc["users"].get(session.uname) or {}).get(name)
+ if isinstance(mine, dict):
+ return mine, "personal"
+ shared = doc["workspace"].get(name)
+ if isinstance(shared, dict):
+ return shared, "workspace"
+ return None, None
+
+
+def visible(session):
+ """The caller's tools and the workspace tools whose databases the caller can read."""
+ doc = _doc(session.runtime)
+ mine = [public(tool, "personal") for _n, tool in sorted((doc["users"].get(session.uname) or {}).items())
+ if isinstance(tool, dict)]
+ shared = [tool for _n, tool in sorted(doc["workspace"].items()) if isinstance(tool, dict)]
+ blocked = unreadable(session, {db for tool in shared for db in tool.get("databases") or ()})
+ shared = [public(tool, "workspace") for tool in shared if not blocked & set(tool.get("databases") or ())]
+ return mine, shared
+
+
+def run(session, name, *, door, handle=None):
+ """Run each step as the caller. Refuse the whole tool if any database is unreadable."""
+ tool, scope = find(session, name)
+ if tool is None:
+ raise ToolRefusal(f"You have no saved tool called {name}.")
+ available = _available_tools()
+ steps = [_check_step(step, available) for step in tool.get("steps") or ()]
+ databases = set()
+ for step in steps:
+ step_databases(step["args"], databases)
+ blocked = unreadable(session, databases)
+ if blocked:
+ raise ToolRefusal(f"You cannot read {', '.join(sorted(blocked))}, so the tool {name} cannot run for you.")
+ results, error = _execute_steps(session, steps, door=door, handle=handle)
+ if error == "stopped":
+ return {"ok": False, "stopped": True}
+ out = {"name": name, "title": tool.get("title") or "", "scope": scope,
+ "version": int(tool.get("version") or 1), "steps": results}
+ # A failed step makes the whole run fail, so the model reports the cause and invents no number.
+ return {"ok": False, "error": error.rstrip(".") + ". Report this to the user.", **out} if error else out
+
+
+def _share_rows(runtime):
+ import routes_agent_harness as harness
+
+ return {pid: row for pid, row in harness._proposal_rows(runtime, SHARE_AGENT).items()
+ if isinstance(row, dict) and row.get("kind") == SHARE_KIND}
+
+
+def pending_shares(session):
+ """Share requests that wait for an Administrator's yes. Empty for a member."""
+ if not _is_admin(session):
+ return []
+ rows = [row for row in _share_rows(session.runtime).values() if row.get("status") in {"pending", "approving"}]
+ rows.sort(key=lambda row: str(row.get("created") or ""))
+ return [{"request": row["id"], "tool": (row.get("tool") or {}).get("name") or "",
+ "title": (row.get("tool") or {}).get("title") or "", "requestedBy": row.get("requestedBy") or "",
+ "databases": list((row.get("tool") or {}).get("databases") or ()),
+ "steps": copy.deepcopy((row.get("tool") or {}).get("steps") or [])} for row in rows]
+
+
+def publish(runtime, tool, *, requested_by, approved_by):
+ """Copy a tool to the workspace with who asked and who said yes."""
+ published = {}
+
+ def update(current):
+ published.clear()
+ doc = _doc_from(current)
+ shared = dict(doc["workspace"])
+ published.update(_put(shared, tool, MAX_WORKSPACE_TOOLS, owner=requested_by,
+ approvedBy=approved_by, approvedAt=_now()))
+ doc["workspace"] = shared
+ return doc
+
+ runtime.update(STORE_KEY, update, flush="sync")
+ return public(published, "workspace")
+
+
+def request_share(session, name):
+ """An Administrator shares at once. A member's request waits for an Administrator's yes."""
+ import routes_agent_harness as harness
+
+ doc = _doc(session.runtime)
+ tool = (doc["users"].get(session.uname) or {}).get(name)
+ if not isinstance(tool, dict):
+ raise ToolRefusal(f"You have no saved tool called {name} to share.")
+ snapshot = clean(session, tool)
+ if _is_admin(session):
+ return {"shared": True, "tool": publish(session.runtime, snapshot, requested_by=session.uname,
+ approved_by=session.uname)}
+ for row in _share_rows(session.runtime).values():
+ if (row.get("status") in {"pending", "approving"} and row.get("requestedBy") == session.uname
+ and (row.get("tool") or {}).get("name") == name):
+ return {"shared": False, "request": row["id"],
+ "message": "This tool already waits for an Administrator's yes."}
+ from core import write_execution
+ row = {"id": "ts_" + write_execution.new_id()[:16], "agent": SHARE_AGENT, "kind": SHARE_KIND,
+ "path": "tools/" + name, "summary": snapshot["title"], "tool": snapshot, "status": "pending",
+ "requestedBy": session.uname, "created": _now()}
+ try:
+ harness._store_proposal(session.runtime, SHARE_AGENT, row)
+ except ValueError:
+ raise ToolRefusal("Too many share requests are waiting. Ask an Administrator to decide them first.")
+ return {"shared": False, "request": row["id"],
+ "message": "An Administrator must say yes in the chat before the workspace can use this tool."}
+
+
+def decide_share(session, request_id, approve):
+ """An Administrator's yes copies the tool to the workspace. A no rejects the request."""
+ import routes_agent_harness as harness
+
+ if not _is_admin(session):
+ raise ToolRefusal("Only an Administrator can decide a share request.")
+ row = _share_rows(session.runtime).get(str(request_id))
+ if row is None:
+ raise ToolRefusal("There is no share request with that id.")
+ if not approve:
+ rejected = harness._set_proposal_status(session.runtime, SHARE_AGENT, request_id, "pending", {
+ "status": "rejected", "rejectedBy": session.uname, "rejectedAt": _now()})
+ if not rejected:
+ raise ToolRefusal("That share request no longer waits for a decision.")
+ return {"shared": False, "request": request_id, "status": "rejected"}
+ if row.get("status") == "pending":
+ row = harness._set_proposal_status(session.runtime, SHARE_AGENT, request_id, "pending",
+ {"status": "approving", "approvedBy": session.uname}) or {}
+ if row.get("status") != "approving":
+ raise ToolRefusal("That share request no longer waits for a decision.")
+ tool = publish(session.runtime, row["tool"], requested_by=row.get("requestedBy") or "",
+ approved_by=row.get("approvedBy") or session.uname)
+ harness._set_proposal_status(session.runtime, SHARE_AGENT, request_id, "approving",
+ {"status": "approved", "approvedAt": _now()})
+ return {"shared": True, "request": request_id, "status": "approved", "tool": tool}
+
+
+def prompt_lines(session):
+ """At most two short system prompt lines: saved tool names, and an Administrator's share inbox."""
+ lines = []
+ try:
+ mine, shared = visible(session)
+ names = [f"{tool['name']} ({tool['title']})" for tool in [*mine, *shared][:12]]
+ if names:
+ lines.append(("Saved tools: " + ", ".join(names))[:400] + ". Use tool_run when a question matches one.")
+ waiting = pending_shares(session)[:6]
+ if waiting:
+ asks = [f"{row['request']} ({row['tool']} from {row['requestedBy']})" for row in waiting]
+ lines.append(("Share requests waiting for your yes: " + ", ".join(asks))[:400]
+ + ". Ask the user before you call tool_share_decide.")
+ except Exception: # noqa: BLE001
+ return ""
+ return "\n".join(lines)
diff --git a/api/loopy_xlsx.py b/api/loopy_xlsx.py
new file mode 100644
index 0000000000000000000000000000000000000000..055d8c8c01a528ef83308617fb6b97bd448b61b0
--- /dev/null
+++ b/api/loopy_xlsx.py
@@ -0,0 +1,141 @@
+"""Render authorized table and Sheet values as Excel workbooks without formulas."""
+from collections.abc import Mapping
+from datetime import date, datetime, timezone
+from decimal import Decimal
+from io import BytesIO
+import json
+import math
+import re
+
+MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+MAX_ROWS = 100_000
+MAX_CELLS = 1_000_000
+MAX_BYTES = 20 * 1024 * 1024
+_ADDRESS = re.compile(r"([A-Z]{1,3})([1-9][0-9]*)\Z")
+_ILLEGAL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
+
+
+def check_size(rows, columns, *, cells=None):
+ if rows > MAX_ROWS or columns > 16_384 or (cells if cells is not None else rows * columns) > MAX_CELLS:
+ raise ValueError(
+ f"Excel export exceeds the file limit ({MAX_ROWS:,} rows, {MAX_CELLS:,} cells, "
+ "16,384 columns). Filter the database or export smaller workbooks. No rows were exported.")
+
+
+def _value(value, field=None):
+ # Formula-shaped source strings remain unchanged, even in a date column.
+ if isinstance(value, str) and value.startswith(("=", "+", "-", "@")):
+ if len(value) > 32_767 or _ILLEGAL.search(value):
+ raise ValueError("A cell exceeds Excel's text limits. Shorten or clean that cell and ask again. No text was cut.")
+ return value
+ kind = (field or {}).get("type")
+ if isinstance(value, str) and value and kind in ("date", "datetime"):
+ try:
+ value = (date.fromisoformat(value) if kind == "date"
+ else datetime.fromisoformat(value.replace("Z", "+00:00")))
+ except ValueError as exc:
+ raise ValueError("A date could not be exported. Correct its value and ask again.") from exc
+ if isinstance(value, datetime) and value.tzinfo is not None:
+ value = value.astimezone(timezone.utc).replace(tzinfo=None)
+ if isinstance(value, Decimal):
+ value = float(value)
+ if isinstance(value, float) and not math.isfinite(value):
+ raise ValueError("A number is not finite. Correct its value and ask again.")
+ if isinstance(value, (dict, list, tuple)):
+ value = json.dumps(value, ensure_ascii=False, allow_nan=False)
+ if value is not None and not isinstance(value, (str, int, float, bool, date, datetime)):
+ raise ValueError("A cell has an unsupported value. Correct it and ask again.")
+ if isinstance(value, str) and (len(value) > 32_767 or _ILLEGAL.search(value)):
+ raise ValueError("A cell exceeds Excel's text limits. Shorten or clean that cell and ask again. No text was cut.")
+ return value
+
+
+def _cell(worksheet, value, field=None):
+ from openpyxl.cell import WriteOnlyCell
+
+ cell = WriteOnlyCell(worksheet, value=_value(value, field))
+ if isinstance(cell.value, str):
+ cell.data_type = "s"
+ return cell
+
+
+def _output(book):
+ output = BytesIO()
+ book.save(output)
+ data = output.getvalue()
+ if len(data) > MAX_BYTES:
+ raise ValueError("Excel export exceeds the 20 MiB file limit. Select fewer fields or filter the rows and ask again. No file was stored.")
+ return data
+
+
+def render_table(title, columns, rows, *, expected_count=None):
+ """Write a header and every row, preserving typed values and literal strings."""
+ from openpyxl import Workbook
+
+ if expected_count is not None and (type(expected_count) is not int or expected_count != len(rows)):
+ raise ValueError("The server count differs from the rows read. Read the complete result again. No file was stored.")
+ if not columns:
+ raise ValueError("An Excel table needs at least one readable column.")
+ check_size(len(rows) + 1, len(columns))
+ fields = [column if isinstance(column, Mapping) else {"key": column, "label": column} for column in columns]
+ prepared = []
+ for row in rows:
+ values = [row.get(field["key"]) for field in fields] if isinstance(row, Mapping) else list(row)
+ if len(values) != len(fields):
+ raise ValueError("An Excel row must match its columns. Read the complete result again.")
+ prepared.append([_value(value, field) for value, field in zip(values, fields)])
+ labels = [_value(field.get("label") or field["key"]) for field in fields]
+ book = Workbook(write_only=True)
+ book.properties.title = title
+ tab = book.create_sheet("Data")
+ tab.freeze_panes = "A2"
+ tab.append([_cell(tab, value) for value in labels])
+ for values in prepared:
+ tab.append([_cell(tab, value) for value in values])
+ return _output(book)
+
+
+def render_workbook(title, tabs):
+ """Write permitted Sheet values at their original addresses, without formulas or bindings."""
+ from openpyxl import Workbook
+
+ if not tabs:
+ raise ValueError("The Sheet workbook has no readable tabs.")
+ prepared, total_rows, total_cells, names = [], 0, 0, set()
+ for tab in tabs:
+ name = tab.get("name")
+ if (not isinstance(name, str) or not name or len(name) > 31
+ or re.search(r"[\\/*?:\[\]]", name) or name.lower() in names):
+ raise ValueError("A Sheet tab name is not valid in Excel. Rename the tab and ask again.")
+ names.add(name.lower())
+ cells, max_row, max_col = {}, 0, 0
+ for address, cell in (tab.get("cells") or {}).items():
+ match = _ADDRESS.fullmatch(address) if isinstance(address, str) else None
+ if not match or not isinstance(cell, dict):
+ raise ValueError("A Sheet cell is invalid. Repair the workbook and ask again.")
+ col = 0
+ for char in match[1]:
+ col = col * 26 + ord(char) - 64
+ row = int(match[2])
+ check_size(row, col)
+ binding = cell.get("binding") or {}
+ if isinstance(binding, dict) and (binding.get("mode") == "view" or binding.get("kind") == "view"):
+ raise ValueError("A placed View cannot be exported as a cached cell. Export its database through the query tool and ask again.")
+ if cell.get("refusal") or cell.get("state") in ("refused", "stale"):
+ raise ValueError("A Sheet value needs refresh or permission. Refresh the workbook with readable sources and ask again.")
+ if cell.get("kind") in ("bound", "formula") and "value" not in cell:
+ raise ValueError("A Sheet calculation has no value. Refresh the workbook and ask again.")
+ value = None if cell.get("kind") == "empty" else cell.get("value", cell.get("text"))
+ cells[(row, col)] = _value(value)
+ max_row, max_col = max(max_row, row), max(max_col, col)
+ total_rows += max_row
+ total_cells += max_row * max_col
+ check_size(total_rows, max_col, cells=total_cells)
+ prepared.append((name, cells, max_row, max_col))
+ book = Workbook(write_only=True)
+ book.properties.title = title
+ for name, cells, rows, cols in prepared:
+ tab = book.create_sheet(name)
+ for row in range(1, rows + 1):
+ tab.append([_cell(tab, cells.get((row, col))) for col in range(1, cols + 1)])
+ return _output(book)
diff --git a/api/main.py b/api/main.py
index 4d367a037a7741739f0c5235e52cabe3b67350b7..6abf09c81fbe17582816ac8d455aa21ff2c578e3 100644
--- a/api/main.py
+++ b/api/main.py
@@ -489,6 +489,8 @@ app.include_router(routes_query.router) # R1 / C5 — E's router, A's line
# ⚠ `verify_api::section_w23_mounts` asserts this path in `app.openapi()["paths"]`, so its four
# EXPECTED reds should now go GREEN. A red here after this line means the mount broke, not the gate.
app.include_router(routes_publish.router) # R5 / C2 — C's router, A's line (the publish door)
+import routes_shared_artifact
+app.include_router(routes_shared_artifact.router)
# ⛔ NOT BEHIND `module_gate("product_data")`, WHICH IS THE WHOLE REASON IT IS A SECOND ASSET DOOR.
# `routes_assets.py` gates EVERY one of its routes on that module, so a connector logo served from
# there would 403 for any account without the product-data grant — i.e. the Connectors directory
diff --git a/api/meta_relational.py b/api/meta_relational.py
index 5b50b447e3acf9635b403f52e5d76b84d32f718f..7371126564fd80e178ff1e6a58169e17f979bed9 100644
--- a/api/meta_relational.py
+++ b/api/meta_relational.py
@@ -116,7 +116,7 @@ _MONEY = {"spend", "social_spend", "cpc", "cpm", "cpp", "amount_spent", "balance
def _label(col):
- return col.replace("_", " ").strip().capitalize()
+ return connector_spec._label(col)
def _ftype(col, duck_type):
diff --git a/api/model_router.py b/api/model_router.py
index f3d5e369342232b52cd6ff3ffb94babdc89bc07a..a3e5167bf88dfa9639c6ca0ab1f58825b0d5bbb9 100644
--- a/api/model_router.py
+++ b/api/model_router.py
@@ -1,24 +1,11 @@
-"""Route automatic turns only to models approved for their measured kind."""
+"""Classify an Assistant turn for its audit kind. Provider choice lives in `providers.llm_chain`."""
from __future__ import annotations
-import json
-import math
import re
-import threading
-from pathlib import Path
-
-import providers
-
-RECEIPT_PATH = Path(__file__).resolve().parents[2] / "platform/evals/router_receipt.json"
-MEASURED_KINDS = {"total", "list", "view"}
-OPEN_PROVIDERS = {"groq", "cerebras", "openrouter"}
-PASS_MARGIN = 5
-_RECEIPT_LOCK = threading.Lock()
-_receipt_cache = None
def classify_turn(question, dock=None):
- """Classify explicit read intents and keep writes or unknown intents on Claude."""
+ """Name a turn total, list, view, write or other from its question and dock."""
if dock is not None:
if not isinstance(dock, dict) or dock.get("surface") not in {"data", "sheet", "automation", "field"}:
return "other"
@@ -44,76 +31,3 @@ def classify_turn(question, dock=None):
and re.search(r"\b(?:total|sum|average|count|how many|how much|revenue|margin|return rate|what share|balance|expense)\b", text)):
return "total"
return "other"
-
-
-def load_receipt():
- """Cache receipt bytes until their file identity or timestamps change."""
- global _receipt_cache
- path = Path(RECEIPT_PATH)
- with _RECEIPT_LOCK:
- try:
- stat = path.stat()
- signature = (str(path), stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_ctime_ns, stat.st_size)
- except OSError:
- signature = (str(path), None)
- if _receipt_cache is None or _receipt_cache[0] != signature:
- try:
- receipt = json.loads(path.read_text(encoding="utf-8")) if signature[-1] is not None else None
- except (OSError, ValueError, UnicodeError):
- receipt = None
- _receipt_cache = (signature, receipt if isinstance(receipt, dict) else None)
- return _receipt_cache[1]
-
-
-def _score(value):
- if type(value) not in (int, float):
- return False
- try:
- return math.isfinite(value) and 0 <= value <= 100
- except OverflowError:
- return False
-
-
-def provider_order(kind, receipt):
- """Allow only the scored open pin followed by Anthropic, or Anthropic alone."""
- fallback = ["anthropic"]
- if not isinstance(kind, str) or kind not in MEASURED_KINDS or not isinstance(receipt, dict):
- return fallback
- if type(receipt.get("schema")) is not int or receipt["schema"] != 1 or receipt.get("margin") != PASS_MARGIN:
- return fallback
- kinds = receipt.get("kinds")
- row = kinds.get(kind) if isinstance(kinds, dict) else None
- if not isinstance(row, dict) or row.get("status") != "measured" or row.get("passed") is not True:
- return fallback
- open_score, claude_score = row.get("openScore"), row.get("claudeScore")
- if not _score(open_score) or not _score(claude_score) or open_score < claude_score - PASS_MARGIN:
- return fallback
- name, model = row.get("provider"), row.get("model")
- if not isinstance(name, str) or name not in OPEN_PROVIDERS or not isinstance(model, str) or not model:
- return fallback
- pin = providers.LLM_PROVIDERS.get(name)
- if pin is None or pin.model != model or row.get("route") != name:
- return fallback
- reference = receipt.get("reference")
- claude = providers.LLM_PROVIDERS.get("anthropic")
- if (not isinstance(reference, dict) or claude is None or reference.get("provider") != "anthropic"
- or reference.get("model") != claude.model or reference.get("status") != "measured"):
- return fallback
- ref_kinds = reference.get("kinds")
- ref = ref_kinds.get(kind) if isinstance(ref_kinds, dict) else None
- if (not isinstance(ref, dict) or ref.get("provider") != "anthropic" or ref.get("model") != claude.model
- or ref.get("status") != "measured" or not _score(ref.get("score")) or ref["score"] != claude_score):
- return fallback
- candidates = receipt.get("candidates")
- if not isinstance(candidates, list):
- return fallback
- for candidate in candidates:
- if not isinstance(candidate, dict) or (candidate.get("provider"), candidate.get("model")) != (name, model):
- continue
- measured = candidate.get("kinds")
- measured = measured.get(kind) if isinstance(measured, dict) else None
- if (isinstance(measured, dict) and (measured.get("provider"), measured.get("model")) == (name, model)
- and measured.get("status") == "measured" and _score(measured.get("score"))
- and measured["score"] == open_score):
- return [name, "anthropic"]
- return fallback
diff --git a/api/odoo_purchasing.py b/api/odoo_purchasing.py
index da9db5c89f28263dbfb5f5eac14549724f2b2195..5b476ef51b02ceaf331bb5fbd349d9422ad20b31 100644
--- a/api/odoo_purchasing.py
+++ b/api/odoo_purchasing.py
@@ -38,6 +38,89 @@ def _date(value):
return str(value or "")[:10]
+def _int(value):
+ return int(value or 0)
+
+
+def _html(value):
+ import html
+ import re
+ return " ".join(html.unescape(re.sub(r"<[^>]*>", " ", str(value or ""))).split())
+
+
+_CASTS = {"text": _text, "html": _html, "date": _date, "num": _number, "int": _int}
+
+
+def _af(key, label, ftype, odoo, ref, how="text", agg=None):
+ """One audited column (S72-T43, R107). Same shape as `odoo_relational._af`."""
+ return {"key": key, "label": label, "type": ftype, "odoo": odoo, "ref": ref, "how": how,
+ "agg": agg, "desc": None}
+
+
+#: S72-T43 / R107: the audited Odoo fields, read only, hidden by default.
+AUDIT_FIELDS = {
+ ORDERS_KEY: (
+ _af("created_on", "Created on", "date", "purchase.order.create_date", "po.create_date",
+ "date"),
+ _af("expected_arrival", "Expected arrival", "date", "purchase.order.date_planned",
+ "po.date_planned", "date"),
+ _af("arrived_on", "Arrived on", "date", "purchase.order.effective_date",
+ "po.effective_date", "date"),
+ _af("procurement_group", "Procurement group", "text", "purchase.order.group_id",
+ "po.group_name"),
+ _af("bill_count", "Bill count", "int", "purchase.order.invoice_count",
+ "po.invoice_count", "int"),
+ _af("billing_status", "Billing status", "text", "purchase.order.invoice_status",
+ "po.invoice_status"),
+ _af("terms", "Terms and conditions", "text", "purchase.order.notes", "po.notes", "html"),
+ _af("vendor_reference", "Vendor reference", "text", "purchase.order.partner_ref",
+ "po.partner_ref"),
+ _af("payment_terms", "Payment terms", "text", "purchase.order.payment_term_id",
+ "po.payment_term_name"),
+ _af("deliver_to", "Deliver to", "text", "purchase.order.picking_type_id",
+ "po.picking_type_name"),
+ _af("receipt_status", "Receipt status", "text", "purchase.order.receipt_status",
+ "po.receipt_status"),
+ _af("buyer", "Buyer", "text", "purchase.order.user_id", "po.user_name"),
+ ),
+ LINES_KEY: (
+ _af("created_on", "Created on", "date", "purchase.order.line.create_date",
+ "pol.create_date", "date"),
+ _af("description", "Description", "text", "purchase.order.line.name", "pol.name"),
+ _af("price_total", "Total with tax", "currency", "purchase.order.line.price_total",
+ "pol.price_total", "num", "sum"),
+ _af("packaging", "Packaging", "text", "purchase.order.line.product_packaging_id",
+ "pol.product_packaging_name"),
+ _af("packaging_qty", "Packaging quantity", "int",
+ "purchase.order.line.product_packaging_qty", "pol.product_packaging_qty", "num",
+ "sum"),
+ _af("billed_qty", "Billed quantity", "int", "purchase.order.line.qty_invoiced",
+ "pol.qty_invoiced", "num", "sum"),
+ _af("received_qty_method", "Received quantity method", "text",
+ "purchase.order.line.qty_received_method", "pol.qty_received_method"),
+ _af("qty_to_bill", "Quantity to bill", "int", "purchase.order.line.qty_to_invoice",
+ "pol.qty_to_invoice", "num", "sum"),
+ _af("total_billed", "Total billed", "currency", "purchase.order.line.total_invoiced",
+ "pol.total_invoiced", "num", "sum"),
+ ),
+}
+
+
+def _audit_presets(key):
+ out = []
+ for entry in AUDIT_FIELDS[key]:
+ field = {"key": entry["key"], "label": entry["label"], "type": entry["type"],
+ "default": False}
+ if entry["agg"]:
+ field["agg"] = entry["agg"]
+ out.append(field)
+ return out
+
+
+def _audit_cols(key):
+ return {entry["key"]: (entry["ref"], _CASTS[entry["how"]]) for entry in AUDIT_FIELDS[key]}
+
+
def _fields(items):
return [{"source": "overlay", "default": True,
"automation": {"flowId": "odoo_relational", "preset": True}, **field} for field in items]
@@ -56,7 +139,7 @@ def order_fields():
{"key": "currency", "label": "Currency", "type": "text"},
{"key": "amount_untaxed", "label": "Untaxed amount", "type": "currency", "agg": "sum"},
{"key": "amount_total", "label": "Total amount", "type": "currency", "agg": "sum"},
- ])
+ ] + _audit_presets(ORDERS_KEY))
def line_fields():
@@ -83,7 +166,7 @@ def line_fields():
{"key": "price_unit", "label": "Unit price", "type": "currency"},
{"key": "price_subtotal", "label": "Untaxed amount", "type": "currency", "agg": "sum"},
{"key": "planned_date", "label": "Planned date", "type": "date"},
- ])
+ ] + _audit_presets(LINES_KEY))
def source_specs():
@@ -98,7 +181,8 @@ def source_specs():
"where": CONFIRMED, "id": "po.id",
"cols": {**common, "odoo_id": ("po.id", _id), "order_date": ("po.date_order", _date),
"amount_untaxed": ("po.amount_untaxed", _number),
- "amount_total": ("po.amount_total", _number)},
+ "amount_total": ("po.amount_total", _number),
+ **_audit_cols(ORDERS_KEY)},
},
LINES_KEY: {
"from_sql": "(purchase_order_line pol JOIN purchase_order po ON po.id = pol.order_id "
@@ -112,7 +196,8 @@ def source_specs():
"standard_price": ("pp.standard_price", _number), "category": ("pp.categ_name", _text),
"qty": ("pol.product_uom_qty", _number), "purchase_qty": ("pol.product_qty", _number),
"received_qty": ("pol.qty_received", _number), "price_unit": ("pol.price_unit", _number),
- "price_subtotal": ("pol.price_subtotal", _number), "planned_date": ("pol.date_planned", _date)},
+ "price_subtotal": ("pol.price_subtotal", _number), "planned_date": ("pol.date_planned", _date),
+ **_audit_cols(LINES_KEY)},
},
}
@@ -186,3 +271,46 @@ def validate(client, cur=None, month="2026-06"):
and abs(totals[ORDERS_KEY][0] - totals[LINES_KEY][1]) <= 0.01,
"observation": plane})
return checks
+
+
+def validate_audit_totals(client, cur, start, end, id_window=None, keys=None):
+ """S72-T43: each audited purchasing total ties to an Odoo read_group sum.
+ `odoo_relational.validate` calls it, so this module's own `validate` keeps its five legs.
+
+ `start`/`end` bound the confirmation date, end exclusive. `id_window` (lo, hi) narrows both
+ sides to one id range. Without a cursor the leg reads Odoo rows, never the mirror.
+ """
+ checks = []
+ plane = "mirror" if cur is not None else "live_rows"
+ for key, model in ((ORDERS_KEY, "purchase.order"), (LINES_KEY, "purchase.order.line")):
+ sums = [e for e in AUDIT_FIELDS[key] if e["agg"] == "sum"]
+ if not sums or (keys is not None and key not in keys):
+ continue
+ prefix = "order_id." if key == LINES_KEY else ""
+ domain = [(prefix + "state", "in", ["purchase", "done"]),
+ (prefix + "date_approve", ">=", start), (prefix + "date_approve", "<", end)]
+ spec = source_specs()[key]
+ where, params = spec["where"] + " AND po.date_approve >= ? AND po.date_approve < ?", [start, end]
+ if id_window:
+ domain += [("id", ">=", id_window[0]), ("id", "<=", id_window[1])]
+ where += f" AND {spec['id']} >= ? AND {spec['id']} <= ?"
+ params += list(id_window)
+ for entry in sums:
+ field = entry["odoo"].rpartition(".")[2]
+ name = "audit total " + key + " " + entry["key"]
+ try:
+ if cur is None:
+ _count, total = _row_totals(client, model, domain, field)
+ else:
+ total = float(cur.execute(
+ "SELECT COALESCE(SUM(" + spec["cols"][entry["key"]][0] + "), 0) FROM "
+ + spec["from_sql"] + " WHERE " + where, params).fetchone()[0])
+ groups = client.read_group(model, domain, [field + ":sum"], ["create_uid"],
+ lazy=False)
+ summary = math.fsum(float(row.get(field) or 0) for row in groups)
+ checks.append({"check": name, "observation": plane,
+ "ok": math.isfinite(total) and abs(total - summary) <= 0.01})
+ except Exception as exc: # noqa: BLE001
+ checks.append({"check": name, "ok": False, "error_type": type(exc).__name__,
+ "observation": plane})
+ return checks
diff --git a/api/odoo_relational.py b/api/odoo_relational.py
index 3ee74c33f5ce405663f5b279755fa4877453ee0f..ab4998796cb1adf65af42806fbb57f030c36ae3b 100644
--- a/api/odoo_relational.py
+++ b/api/odoo_relational.py
@@ -179,6 +179,592 @@ def _refreshed_field():
"default": False, "description": "When this row was last reconciled against Odoo."}
+# ═════════════════════════════════════════════════════════════════════════════════════════════
+# S72-T43 / R107: THE AUDITED ODOO FIELDS ("All filled fields, you strike").
+# ═════════════════════════════════════════════════════════════════════════════════════════════
+# One entry per added column, from the `add` rows of `platform/model/audit/field-audit.md`.
+# An entry is read only: a preset over a mirror column, never a write path to Odoo.
+# Three layers carry a field: the mirror entity (`AUDIT_MIRROR_ADDITIONS`, amended into
+# `harness.datastore.ENTITIES`), the grid projection (`merge_audit_cols`) and the preset here.
+
+def _af(key, label, ftype, odoo, ref, how="text", agg=None, desc=None):
+ """One audited column: preset key and label, Odoo `model.field`, mirror `alias.column`."""
+ return {"key": key, "label": label, "type": ftype, "odoo": odoo, "ref": ref, "how": how,
+ "agg": agg, "desc": desc}
+
+
+def _audit_text(value):
+ return "" if value is None else str(value)
+
+
+def _audit_html(value):
+ import html as _html
+ import re as _re
+ return " ".join(_html.unescape(_re.sub(r"<[^>]*>", " ", str(value or ""))).split())
+
+
+def _audit_number(value):
+ return float(value or 0.0)
+
+
+def _audit_int(value):
+ return int(value or 0)
+
+
+def _audit_flag(value):
+ return "1" if value else ""
+
+
+def _audit_pct(value):
+ return "" if value is None else round(float(value), 2)
+
+
+_AUDIT_CASTS = {"text": _audit_text, "html": _audit_html, "date": lambda v: _as_date(v),
+ "num": _audit_number, "int": _audit_int, "flag": _audit_flag, "pct": _audit_pct,
+ "agent_sum": _audit_number, "agent_names": _audit_text,
+ "agent_first": lambda v: _as_date(v), "agent_all": _audit_flag,
+ "m2m_names": _audit_text}
+
+#: Commission lines fold onto their invoice. `am` is the invoices grid's own alias.
+_AUDIT_AGENT_SQL = {
+ "agent_sum": "(SELECT SUM(x.{c}) FROM account_invoice_line_agent x WHERE x.invoice_id = am.id)",
+ "agent_names": ("(SELECT string_agg(DISTINCT x.{c}, ', ' ORDER BY x.{c}) "
+ "FROM account_invoice_line_agent x WHERE x.invoice_id = am.id)"),
+ "agent_first": "(SELECT min(x.{c}) FROM account_invoice_line_agent x WHERE x.invoice_id = am.id)",
+ "agent_all": ("(SELECT bool_and(COALESCE(x.{c}, FALSE)) FROM account_invoice_line_agent x "
+ "WHERE x.invoice_id = am.id)"),
+}
+
+_INVOICE_AUDIT = (
+ _af("amount_total", "Total", "currency", "account.move.amount_total", "am.amount_total",
+ "num", "sum"),
+ _af("amount_total_signed", "Total signed", "currency", "account.move.amount_total_signed",
+ "am.amount_total_signed", "num", "sum"),
+ _af("amount_total_currency", "Total in document currency", "currency",
+ "account.move.amount_total_in_currency_signed", "am.amount_total_in_currency_signed",
+ "num", "sum"),
+ _af("untaxed_amount", "Untaxed amount", "currency", "account.move.amount_untaxed",
+ "am.amount_untaxed", "num", "sum", "Unsigned. A refund shows as a positive amount."),
+ _af("commercial_partner", "Commercial entity", "text",
+ "account.move.commercial_partner_id", "am.commercial_partner_name"),
+ _af("commission_total", "Commission total", "currency", "account.move.commission_total",
+ "am.commission_total", "num", "sum"),
+ _af("created_on", "Created on", "date", "account.move.create_date", "am.create_date", "date"),
+ _af("accounting_date", "Accounting date", "date", "account.move.date", "am.date", "date"),
+ _af("payment_terms", "Payment terms", "text", "account.move.invoice_payment_term_id",
+ "am.invoice_payment_term_name"),
+ _af("salesperson", "Salesperson", "text", "account.move.invoice_user_id",
+ "am.invoice_user_name"),
+ _af("sent", "Sent", "checkbox", "account.move.is_move_sent", "am.is_move_sent", "flag"),
+ _af("journal", "Journal", "text", "account.move.journal_id", "am.journal_name"),
+ _af("terms", "Terms and conditions", "text", "account.move.narration", "am.narration", "html"),
+ _af("delivery_address", "Delivery address", "text", "account.move.partner_shipping_id",
+ "am.partner_shipping_name"),
+ _af("payment_reference", "Payment reference", "text", "account.move.payment_reference",
+ "am.payment_reference"),
+ _af("reference", "Reference", "text", "account.move.ref", "am.ref"),
+ _af("sales_team", "Sales team", "text", "account.move.team_id", "am.team_name"),
+ _af("commission_amount", "Agent commission", "currency",
+ "account.invoice.line.agent.amount", "ail.amount", "agent_sum", "sum",
+ "The sum of this invoice's agent commission lines."),
+ _af("commission_plan", "Commission plan", "text",
+ "account.invoice.line.agent.commission_id", "ail.commission_name", "agent_names"),
+ _af("commission_recorded_on", "Commission recorded on", "date",
+ "account.invoice.line.agent.create_date", "ail.create_date", "agent_first"),
+ _af("commission_settled", "Commission settled", "checkbox",
+ "account.invoice.line.agent.settled", "ail.settled", "agent_all",
+ "Ticked when every agent line on this invoice is settled."),
+)
+
+#: Bills read `account_move` unaliased. The sales-only fields stay on invoices.
+_BILL_AUDIT = tuple(
+ {**entry, "ref": entry["ref"].split(".", 1)[1]} for entry in _INVOICE_AUDIT
+ if entry["key"] in ("amount_total", "amount_total_signed", "amount_total_currency",
+ "untaxed_amount", "commercial_partner", "created_on", "accounting_date",
+ "payment_terms", "journal", "terms", "payment_reference", "reference"))
+
+_GL_LINE_AUDIT = (
+ _af("account_root", "Account root", "text", "account.move.line.account_root_id",
+ "aml.account_root_name"),
+ _af("amount_currency", "Amount in currency", "currency", "account.move.line.amount_currency",
+ "aml.amount_currency", "num", "sum"),
+ _af("created_on", "Created on", "date", "account.move.line.create_date", "aml.create_date",
+ "date"),
+ _af("due_date", "Due date", "date", "account.move.line.date_maturity", "aml.date_maturity",
+ "date"),
+ _af("reconcile_match", "Reconcile match", "text", "account.move.line.full_reconcile_id",
+ "aml.full_reconcile_name"),
+ _af("journal", "Journal", "text", "account.move.line.journal_id", "aml.journal_name"),
+ _af("matching_number", "Matching number", "text", "account.move.line.matching_number",
+ "aml.matching_number"),
+ _af("label", "Label", "text", "account.move.line.name", "aml.name"),
+ _af("payment", "Payment", "text", "account.move.line.payment_id", "aml.payment_name"),
+ _af("price_subtotal", "Subtotal", "currency", "account.move.line.price_subtotal",
+ "aml.price_subtotal", "num", "sum"),
+ _af("price_total", "Total", "currency", "account.move.line.price_total", "aml.price_total",
+ "num", "sum"),
+ _af("price_unit", "Unit price", "currency", "account.move.line.price_unit",
+ "aml.price_unit", "num"),
+ _af("uom", "Unit of measure", "text", "account.move.line.product_uom_id",
+ "aml.product_uom_name"),
+ _af("quantity", "Quantity", "int", "account.move.line.quantity", "aml.quantity", "num", "sum"),
+ _af("reconciled", "Reconciled", "checkbox", "account.move.line.reconciled", "aml.reconciled",
+ "flag"),
+ _af("reference", "Reference", "text", "account.move.line.ref", "aml.ref"),
+)
+
+_ACCOUNT_AUDIT = (
+ _af("created_on", "Created on", "date", "account.account.create_date", "create_date", "date"),
+ _af("deprecated", "Deprecated", "checkbox", "account.account.deprecated", "deprecated",
+ "flag"),
+ _af("carry_forward", "Balance carried forward", "checkbox",
+ "account.account.include_initial_balance", "include_initial_balance", "flag"),
+ _af("internal_group", "Internal group", "text", "account.account.internal_group",
+ "internal_group"),
+ _af("allows_reconcile", "Allows reconciliation", "checkbox", "account.account.reconcile",
+ "reconcile", "flag"),
+ _af("account_root", "Account root", "text", "account.account.root_id", "root_name"),
+)
+
+_ORDER_AUDIT = (
+ _af("amount_total", "Total", "currency", "sale.order.amount_total", "amount_total", "num",
+ "sum"),
+ _af("delivery_method", "Delivery method", "text", "sale.order.carrier_id", "carrier_name"),
+ _af("commission_total", "Commission total", "currency", "sale.order.commission_total",
+ "commission_total", "num", "sum"),
+ _af("created_on", "Created on", "date", "sale.order.create_date", "create_date", "date"),
+ _af("delivered_on", "Delivered on", "date", "sale.order.effective_date", "effective_date",
+ "date"),
+ _af("margin", "Margin $", "currency", "sale.order.margin", "margin", "num", "sum"),
+ _af("margin_percent", "Margin %", "pct", "sale.order.margin_percent", "margin_percent",
+ "pct"),
+ _af("terms", "Terms and conditions", "text", "sale.order.note", "note", "html"),
+ _af("online_payment_basis", "Online payment basis", "text",
+ "sale.order.online_payment_based_on", "online_payment_based_on"),
+ _af("invoice_address", "Invoice address", "text", "sale.order.partner_invoice_id",
+ "partner_invoice_name"),
+ _af("delivery_address", "Delivery address", "text", "sale.order.partner_shipping_id",
+ "partner_shipping_name"),
+ _af("payment_terms", "Payment terms", "text", "sale.order.payment_term_id",
+ "payment_term_name"),
+ _af("shipping_policy", "Shipping policy", "text", "sale.order.picking_policy",
+ "picking_policy"),
+ _af("procurement_group", "Procurement group", "text", "sale.order.procurement_group_id",
+ "procurement_group_name"),
+ _af("recompute_delivery", "Recompute delivery cost", "checkbox",
+ "sale.order.recompute_delivery_price", "recompute_delivery_price", "flag"),
+ _af("online_signature", "Online signature", "checkbox", "sale.order.require_signature",
+ "require_signature", "flag"),
+ _af("salesperson", "Salesperson", "text", "sale.order.user_id", "user_name"),
+ _af("warehouse", "Warehouse", "text", "sale.order.warehouse_id", "warehouse_name"),
+)
+
+_ORDER_LINE_AUDIT = (
+ _af("commission_free", "Commission free", "checkbox", "sale.order.line.commission_free",
+ "sol.commission_free", "flag"),
+ _af("created_on", "Created on", "date", "sale.order.line.create_date", "sol.create_date",
+ "date"),
+ _af("lead_days", "Lead time days", "int", "sale.order.line.customer_lead",
+ "sol.customer_lead", "num"),
+ _af("invoice_status", "Invoice status", "text", "sale.order.line.invoice_status",
+ "sol.invoice_status"),
+ _af("delivery_line", "Delivery line", "checkbox", "sale.order.line.is_delivery",
+ "sol.is_delivery", "flag"),
+ _af("margin_percent", "Margin %", "pct", "sale.order.line.margin_percent",
+ "sol.margin_percent", "pct"),
+ _af("description", "Description", "text", "sale.order.line.name", "sol.name"),
+ _af("packaging_price", "Packaging price", "currency", "sale.order.line.packaging_price",
+ "sol.packaging_price", "num"),
+ _af("price_reduce", "Discounted unit price", "currency", "sale.order.line.price_reduce",
+ "sol.price_reduce", "num"),
+ _af("price_reduce_taxexcl", "Discounted unit price before tax", "currency",
+ "sale.order.line.price_reduce_taxexcl", "sol.price_reduce_taxexcl", "num"),
+ _af("price_reduce_taxinc", "Discounted unit price with tax", "currency",
+ "sale.order.line.price_reduce_taxinc", "sol.price_reduce_taxinc", "num"),
+ _af("price_total", "Line total with tax", "currency", "sale.order.line.price_total",
+ "sol.price_total", "num", "sum"),
+ _af("price_unit", "Unit price", "currency", "sale.order.line.price_unit", "sol.price_unit",
+ "num"),
+ _af("packaging", "Packaging", "text", "sale.order.line.product_packaging_id",
+ "sol.product_packaging_name"),
+ _af("packaging_qty", "Packaging quantity", "int", "sale.order.line.product_packaging_qty",
+ "sol.product_packaging_qty", "num", "sum"),
+ _af("uom", "Unit of measure", "text", "sale.order.line.product_uom", "sol.product_uom_name"),
+ _af("qty_delivered", "Delivered quantity", "int", "sale.order.line.qty_delivered",
+ "sol.qty_delivered", "num", "sum"),
+ _af("delivered_qty_method", "Delivered quantity method", "text",
+ "sale.order.line.qty_delivered_method", "sol.qty_delivered_method"),
+ _af("qty_invoiced", "Invoiced quantity", "int", "sale.order.line.qty_invoiced",
+ "sol.qty_invoiced", "num", "sum"),
+ _af("qty_to_invoice", "Quantity to invoice", "int", "sale.order.line.qty_to_invoice",
+ "sol.qty_to_invoice", "num", "sum"),
+ _af("salesperson", "Salesperson", "text", "sale.order.line.salesman_id",
+ "sol.salesman_name"),
+ _af("untaxed_invoiced", "Untaxed invoiced", "currency",
+ "sale.order.line.untaxed_amount_invoiced", "sol.untaxed_amount_invoiced", "num", "sum"),
+ _af("untaxed_to_invoice", "Untaxed to invoice", "currency",
+ "sale.order.line.untaxed_amount_to_invoice", "sol.untaxed_amount_to_invoice", "num",
+ "sum"),
+ _af("untaxed_to_invoice_credit", "Untaxed to invoice for credit limit", "currency",
+ "sale.order.line.untaxed_amount_to_invoice_credit_limit",
+ "sol.untaxed_amount_to_invoice_credit_limit", "num", "sum"),
+)
+
+_VENDOR_AUDIT = (
+ _af("notes", "Notes", "text", "res.partner.comment", "p.comment", "html"),
+ _af("company_name", "Company name", "text", "res.partner.commercial_company_name",
+ "p.commercial_company_name"),
+ _af("commercial_partner", "Commercial entity", "text", "res.partner.commercial_partner_id",
+ "p.commercial_partner_name"),
+ _af("customer_rank", "Customer rank", "int", "res.partner.customer_rank", "p.customer_rank",
+ "int"),
+ _af("dba", "Doing business as", "text", "res.partner.dba_id", "p.dba_name"),
+ _af("invoice_age_limit", "Invoice age limit on", "checkbox",
+ "res.partner.enable_max_invoice_age", "p.enable_max_invoice_age", "flag"),
+ _af("reminders", "Reminders", "text", "res.partner.followup_reminder_type",
+ "p.followup_reminder_type"),
+ _af("is_company", "Company", "checkbox", "res.partner.is_company", "p.is_company", "flag"),
+ _af("max_invoice_age", "Max invoice age", "int", "res.partner.max_invoice_age",
+ "p.max_invoice_age", "int"),
+ _af("online_payment", "Online payment", "checkbox", "res.partner.online_payment",
+ "p.online_payment", "flag"),
+ _af("parent_company", "Related company", "text", "res.partner.parent_id", "p.parent_name"),
+ _af("sales_warning", "Sales warning", "text", "res.partner.sale_warn", "p.sale_warn"),
+ _af("supplier_rank", "Supplier rank", "int", "res.partner.supplier_rank", "p.supplier_rank",
+ "int"),
+ _af("sales_team", "Sales team", "text", "res.partner.team_id", "p.team_name"),
+ _af("address_type", "Address type", "text", "res.partner.type", "p.type"),
+ _af("timezone", "Timezone", "text", "res.partner.tz", "p.tz"),
+ _af("hubspot_company_id", "HubSpot company ID", "text", "res.partner.x_hubspot_company_id",
+ "p.x_hubspot_company_id"),
+)
+
+_SHIPMENT_AUDIT = (
+ _af("delivery_barcodes", "Delivery barcodes", "text",
+ "stock.picking.antsroute_delivery_barcodes", "sp.antsroute_delivery_barcodes"),
+ _af("delivery_comment", "Delivery comment", "text",
+ "stock.picking.antsroute_delivery_comment", "sp.antsroute_delivery_comment"),
+ _af("delivered_on", "Delivered on", "date", "stock.picking.antsroute_delivery_date",
+ "sp.antsroute_delivery_date", "date"),
+ _af("driver", "Driver", "text", "stock.picking.antsroute_delivery_driver",
+ "sp.antsroute_delivery_driver"),
+ _af("delivery_result", "Delivery status", "text", "stock.picking.antsroute_delivery_status",
+ "sp.antsroute_delivery_status"),
+ _af("vehicle_plate", "Vehicle plate", "text",
+ "stock.picking.antsroute_delivery_vehicle_plate", "sp.antsroute_delivery_vehicle_plate"),
+ _af("delivery_photos", "Delivery photos", "int", "stock.picking.antsroute_nb_delivery_photo",
+ "sp.antsroute_nb_delivery_photo", "int"),
+ _af("shipping_value", "Shipping value", "currency", "stock.picking.antsroute_shipping_value",
+ "sp.antsroute_shipping_value", "num", "sum"),
+ _af("backorder_of", "Backorder of", "text", "stock.picking.backorder_id",
+ "sp.backorder_name"),
+ _af("carrier", "Carrier", "text", "stock.picking.carrier_id", "sp.carrier_name"),
+ _af("created_on", "Created on", "date", "stock.picking.create_date", "sp.create_date", "date"),
+ _af("currency", "Currency", "text", "stock.picking.currency_id", "sp.currency_name"),
+ _af("picking_date", "Picking date", "date", "stock.picking.date", "sp.date", "date"),
+ _af("deadline", "Deadline", "date", "stock.picking.date_deadline", "sp.date_deadline", "date"),
+ _af("procurement_group", "Procurement group", "text", "stock.picking.group_id",
+ "sp.group_name"),
+ _af("locked", "Locked", "checkbox", "stock.picking.is_locked", "sp.is_locked", "flag"),
+ _af("destination_location", "Destination location", "text", "stock.picking.location_dest_id",
+ "sp.location_dest_name"),
+ _af("source_location", "Source location", "text", "stock.picking.location_id",
+ "sp.location_name"),
+ _af("shipping_policy", "Shipping policy", "text", "stock.picking.move_type", "sp.move_type"),
+ _af("operation_type", "Operation type", "text", "stock.picking.picking_type_id",
+ "sp.picking_type_name"),
+ _af("priority", "Priority", "text", "stock.picking.priority", "sp.priority"),
+ _af("sent_to_carrier", "Sent to carrier", "date", "stock.picking.sent_to_carrier",
+ "sp.sent_to_carrier", "date"),
+ _af("uses_antsroute", "Uses AntsRoute", "checkbox", "stock.picking.use_antsroute",
+ "sp.use_antsroute", "flag"),
+ _af("responsible", "Responsible", "text", "stock.picking.user_id", "sp.user_name"),
+)
+
+_STOCK_MOVE_AUDIT = (
+ _af("created_on", "Created on", "date", "stock.move.create_date", "sm.create_date", "date"),
+ _af("deadline", "Deadline", "date", "stock.move.date_deadline", "sm.date_deadline", "date"),
+ _af("picking_description", "Picking description", "text", "stock.move.description_picking",
+ "sm.description_picking"),
+ _af("fulfillment_status", "Fulfillment status", "text", "stock.move.fulfillment_status_id",
+ "sm.fulfillment_status_name"),
+ _af("procurement_group", "Procurement group", "text", "stock.move.group_id", "sm.group_name"),
+ _af("inventory_adjustment", "Inventory adjustment", "checkbox", "stock.move.is_inventory",
+ "sm.is_inventory", "flag"),
+ _af("source_document", "Source document", "text", "stock.move.origin", "sm.origin"),
+ _af("destination_address", "Destination address", "text", "stock.move.partner_id",
+ "sm.partner_name"),
+ _af("operation_type", "Operation type", "text", "stock.move.picking_type_id",
+ "sm.picking_type_name"),
+ _af("priority", "Priority", "text", "stock.move.priority", "sm.priority"),
+ _af("supply_method", "Supply method", "text", "stock.move.procure_method",
+ "sm.procure_method"),
+ _af("packaging", "Packaging", "text", "stock.move.product_packaging_id",
+ "sm.product_packaging_name"),
+ _af("real_qty", "Quantity in product units", "int", "stock.move.product_qty",
+ "sm.product_qty", "num", "sum"),
+ _af("demand_qty", "Demand", "int", "stock.move.product_uom_qty", "sm.product_uom_qty", "num",
+ "sum"),
+ _af("propagate_cancel", "Propagate cancel", "checkbox", "stock.move.propagate_cancel",
+ "sm.propagate_cancel", "flag"),
+ _af("reference", "Reference", "text", "stock.move.reference", "sm.reference"),
+ _af("reserve_on", "Reserve on", "date", "stock.move.reservation_date", "sm.reservation_date",
+ "date"),
+ _af("stock_rule", "Stock rule", "text", "stock.move.rule_id", "sm.rule_name"),
+ _af("sale_line", "Sale line", "text", "stock.move.sale_line_id", "sm.sale_line_name"),
+ _af("warehouse", "Warehouse", "text", "stock.move.warehouse_id", "sm.warehouse_name"),
+)
+
+_STOCK_VALUATION_AUDIT = (
+ _af("journal_entry", "Journal entry", "text", "stock.valuation.layer.account_move_id",
+ "svl.account_move_name"),
+ _af("description", "Description", "text", "stock.valuation.layer.description",
+ "svl.description"),
+ _af("unit_cost", "Unit value", "currency", "stock.valuation.layer.unit_cost",
+ "svl.unit_cost", "num"),
+)
+
+#: `stock.location` has no database of its own. A quant names one location, so its fields land
+#: here through the grid's `sl` join.
+_STOCK_QUANT_AUDIT = (
+ _af("created_on", "Created on", "date", "stock.quant.create_date", "sq.create_date", "date"),
+ _af("incoming_date", "Incoming date", "date", "stock.quant.in_date", "sq.in_date", "date"),
+ _af("count_date", "Scheduled count date", "date", "stock.quant.inventory_date",
+ "sq.inventory_date", "date"),
+ _af("count_difference", "Count difference", "int", "stock.quant.inventory_diff_quantity",
+ "sq.inventory_diff_quantity", "num", "sum"),
+ _af("package", "Package", "text", "stock.quant.package_id", "sq.package_name"),
+ _af("warehouse", "Warehouse", "text", "stock.quant.warehouse_id", "sq.warehouse_name"),
+ _af("custom_warehouse", "Custom warehouse", "text", "stock.quant.x_warehouse_id",
+ "sq.x_warehouse_name"),
+ _af("location_active", "Location active", "checkbox", "stock.location.active", "sl.active",
+ "flag"),
+ _af("location_barcode", "Location barcode", "text", "stock.location.barcode", "sl.barcode"),
+ _af("location_company", "Location company", "text", "stock.location.company_id",
+ "sl.company_name"),
+ _af("location_created_on", "Location created on", "date", "stock.location.create_date",
+ "sl.create_date", "date"),
+ _af("location_last_count", "Location last counted", "date",
+ "stock.location.last_inventory_date", "sl.last_inventory_date", "date"),
+ _af("parent_location", "Parent location", "text", "stock.location.location_id",
+ "sl.location_name"),
+ _af("location_name", "Location short name", "text", "stock.location.name", "sl.name"),
+ _af("location_warehouse", "Location warehouse", "text", "stock.location.warehouse_id",
+ "sl.warehouse_name"),
+)
+
+#: Grid key -> audited columns. Purchasing declares its own in `odoo_purchasing`.
+AUDIT_FIELDS = {
+ INVOICES_KEY: _INVOICE_AUDIT, BILLS_KEY: _BILL_AUDIT, GL_LINES_KEY: _GL_LINE_AUDIT,
+ ACCOUNTS_KEY: _ACCOUNT_AUDIT, ORDERS_KEY: _ORDER_AUDIT, ORDER_LINES_KEY: _ORDER_LINE_AUDIT,
+ VENDORS_KEY: _VENDOR_AUDIT, SHIPMENTS_KEY: _SHIPMENT_AUDIT,
+ STOCK_MOVES_KEY: _STOCK_MOVE_AUDIT, STOCK_VALUATION_KEY: _STOCK_VALUATION_AUDIT,
+ STOCK_QUANT_KEY: _STOCK_QUANT_AUDIT,
+}
+AUDIT_M2M_TABLES = {
+ 'account.account.tag_ids': 'account_account_tag',
+ 'sale.order.fulfillment_status_ids': 'fulfillment_status',
+ 'stock.picking.fulfillment_status_ids': 'fulfillment_status',
+}
+for _key, _entry in (
+ (ACCOUNTS_KEY, _af('account_tags', 'Account tags', 'text', 'account.account.tag_ids',
+ 'tag_ids', 'm2m_names')),
+ (ORDERS_KEY, _af('fulfillment_statuses', 'Fulfillment statuses', 'text',
+ 'sale.order.fulfillment_status_ids', 'so.fulfillment_status_ids', 'm2m_names')),
+ (SHIPMENTS_KEY, _af('fulfillment_statuses', 'Fulfillment statuses', 'text',
+ 'stock.picking.fulfillment_status_ids', 'sp.fulfillment_status_ids', 'm2m_names')),
+):
+ AUDIT_FIELDS[_key] += (_entry,)
+
+#: Audit add rows that no database shows yet, with the cause. Standing rule 1: reported.
+AUDIT_NOT_LANDED = {}
+
+#: Odoo model -> mirror entity, for the audited columns.
+AUDIT_ENTITY = {
+ "account.move": "account_move", "account.move.line": "account_move_line",
+ "account.invoice.line.agent": "account_invoice_line_agent",
+ "account.account": "account_account", "sale.order": "sale_order",
+ "sale.order.line": "sale_order_line", "res.partner": "res_partner",
+ "stock.picking": "stock_picking", "stock.move": "stock_move",
+ "stock.location": "stock_location", "stock.valuation.layer": "stock_valuation_layer",
+ "stock.quant": "stock_quant", "purchase.order": "purchase_order",
+ "purchase.order.line": "purchase_order_line",
+}
+
+
+def _audit_entries(key=None):
+ """Every audited entry, relational and purchasing, optionally for one grid key."""
+ from odoo_purchasing import AUDIT_FIELDS as purchasing
+ table = {**AUDIT_FIELDS, **purchasing}
+ if key is not None:
+ return tuple(table.get(base_table_key(key), ()))
+ return table
+
+
+def _audit_split(odoo):
+ """`model.field` -> (model, field). The field never holds a dot."""
+ model, _, field = odoo.rpartition(".")
+ return model, field
+
+
+def audit_fields(key):
+ """The audited presets one grid adds. Hidden by default, one click away in the picker."""
+ out = []
+ for entry in _audit_entries(key):
+ field = {"key": entry["key"], "label": entry["label"], "type": entry["type"],
+ "source": "overlay", "default": False}
+ if entry.get("agg"):
+ field["agg"] = entry["agg"]
+ if entry.get("desc"):
+ field["description"] = entry["desc"]
+ out.append(_preset(field))
+ return out
+
+
+def audit_projection(entry):
+ """(sql, cast, dependency) for one entry. `dependency` is (alias or table, column) for a
+ computed expression, which `_degrade` cannot check, and None for a bare column."""
+ how, ref = entry["how"], entry["ref"]
+ alias, _, col = ref.rpartition(".")
+ cast = _AUDIT_CASTS[how]
+ if how == 'm2m_names':
+ table = AUDIT_M2M_TABLES[entry['odoo']]
+ # A missing linked name makes the cell unknown; neither IDs nor a partial set
+ # pretend to be a complete name list. Empty relations naturally stay blank.
+ sql = (f"(SELECT CASE WHEN count(*) = count(NULLIF(trim(n.name), '')) "
+ f"THEN string_agg(DISTINCT n.name, ', ' ORDER BY n.name) ELSE NULL END "
+ f"FROM json_each({ref}) j LEFT JOIN {table} n "
+ f"ON n.id = TRY_CAST(j.value AS BIGINT))")
+ return sql, cast, (alias, col)
+ if how in _AUDIT_AGENT_SQL:
+ return _AUDIT_AGENT_SQL[how].format(c=col), cast, ("account_invoice_line_agent", col)
+ if how == "pct":
+ return f"ROUND({ref} * 100, 2)", cast, (alias, col)
+ return ref, cast, None
+
+
+def merge_audit_cols(sources):
+ """GRID_SOURCES with the audited columns merged in. Pure: input specs are not mutated.
+
+ A computed column also gains an `optional` entry, so a mirror that lacks its column serves
+ a blank cell rather than a Binder error. Idempotent: a merged spec merges to itself.
+ """
+ out = dict(sources or {})
+ for key, spec in list(out.items()):
+ entries = _audit_entries(key) if isinstance(spec, dict) and "cols" in spec else ()
+ if not entries:
+ continue
+ aliases = dict(spec.get("tables") or {})
+ if spec.get("table"):
+ aliases.setdefault("", spec["table"])
+ cols = dict(spec["cols"])
+ optional = list(spec.get("optional") or ())
+ for entry in entries:
+ if entry["key"] in cols:
+ continue
+ sql, cast, dep = audit_projection(entry)
+ cols[entry["key"]] = (sql, cast)
+ if dep is not None:
+ need = (aliases.get(dep[0], dep[0]), dep[1])
+ needs = (need,)
+ if entry['how'] == 'm2m_names':
+ table = AUDIT_M2M_TABLES[entry['odoo']]
+ needs += ((table, 'id'), (table, 'name'))
+ for requirement in needs:
+ degrade = {"absent": (requirement,),
+ "without": {"cols": {entry["key"]: ("NULL", cast)}}}
+ if degrade not in optional:
+ optional.append(degrade)
+ merged = {**spec, "cols": cols}
+ if optional:
+ merged["optional"] = tuple(optional)
+ out[key] = merged
+ return out
+
+
+#: Materialised grids read their audited columns beside their reader's own SQL.
+#: key -> (FROM, alias, id column, WHERE). The WHERE matches the reader's population.
+def _audit_materialised(key):
+ return {
+ VENDORS_KEY: ("res_partner p", "p", "p.id",
+ f"p.id IN (SELECT partner_id FROM account_move WHERE {_VENDOR_DOCS} "
+ "AND partner_id IS NOT NULL)"),
+ BILLS_KEY: ("account_move", "", "id", f"{_VENDOR_DOCS} AND partner_id IS NOT NULL"),
+ ACCOUNTS_KEY: ("account_account", "", "id", ""),
+ }.get(key)
+
+
+def _audit_enrich(cur, key, rows):
+ """Add the audited columns to a materialised reader's rows. A column the mirror lacks reads
+ blank. No query runs when the mirror has none of them."""
+ shape = _audit_materialised(key)
+ entries = _audit_entries(key)
+ if not shape or not entries or not rows:
+ return rows
+ frm, alias, id_col, where = shape
+ have = columns(cur, frm.split()[0])
+ exprs, present = [], False
+ for entry in entries:
+ sql, cast, _dep = audit_projection(entry)
+ col = entry["ref"].rpartition(".")[2]
+ naming = AUDIT_M2M_TABLES.get(entry['odoo'])
+ if col.lower() in have and (not naming or {'id', 'name'} <= columns(cur, naming)):
+ exprs.append(sql)
+ present = True
+ else:
+ exprs.append("NULL")
+ values = {}
+ if present:
+ sql = (f"SELECT {id_col} AS audit_row_id, {', '.join(exprs)} FROM {frm}"
+ + (f" WHERE {where}" if where else ""))
+ values = {str(r[0]): r[1:] for r in cur.execute(sql).fetchall()}
+ for row in rows:
+ got = values.get(str(row.get("_id")), (None,) * len(entries))
+ for entry, value in zip(entries, got):
+ row[entry["key"]] = _AUDIT_CASTS[entry["how"]](value)
+ return rows
+
+
+def audit_mirror_types():
+ """{"bool"|"int"|"numeric": sorted Odoo field names} the mirror must type."""
+ kinds = {"flag": "bool", "agent_all": "bool", "int": "int", "num": "numeric",
+ "pct": "numeric", "agent_sum": "numeric"}
+ out = {"bool": set(), "int": set(), "numeric": set()}
+ for entries in _audit_entries().values():
+ for entry in entries:
+ kind = kinds.get(entry["how"])
+ if kind:
+ out[kind].add(_audit_split(entry["odoo"])[1])
+ return {kind: sorted(names) for kind, names in out.items()}
+
+
+def audit_mirror_additions():
+ """{entity: [Odoo field, ...]} in declaration order: the fields the audited columns read."""
+ out = {}
+ for entries in _audit_entries().values():
+ for entry in entries:
+ if entry['how'] == 'm2m_names':
+ continue
+ model, field = _audit_split(entry["odoo"])
+ names = out.setdefault(AUDIT_ENTITY[model], [])
+ if field not in names:
+ names.append(field)
+ return out
+
+
+def audit_mirror_entity(entity, base):
+ """`base` (a `datastore.ENTITIES` spec) with the audited fields declared and backfilled."""
+ spec = {**base, "fields": list(base["fields"])}
+ added = [f for f in audit_mirror_additions().get(entity, ()) if f not in spec["fields"]]
+ if not added:
+ return dict(base)
+ tail = ["write_date"] if "write_date" in spec["fields"] else []
+ spec["fields"] = [f for f in spec["fields"] if f != "write_date"] + added + tail
+ backfill = list(base.get("backfill_fields") or [])
+ spec["backfill_fields"] = backfill + [f for f in added if f not in backfill]
+ return spec
+
+
def shipment_fields():
"""Outgoing pickings, with elapsed delivery time measured at actual completion."""
return [_preset({"source": "overlay", **field}) for field in (
@@ -204,7 +790,7 @@ def shipment_fields():
"default": True, "description": "Elapsed days from the sale order date to the actual "
"shipment completion. Blank when either date is missing."},
_refreshed_field(),
- )]
+ )] + audit_fields(SHIPMENTS_KEY)
def agent_fields():
@@ -276,7 +862,7 @@ def account_fields():
"description": "Ticked for the expense family - the same predicate the semantic layer's "
"gl_lines topic uses, so this column and that topic cannot disagree."},
_refreshed_field(),
- )]
+ )] + audit_fields(ACCOUNTS_KEY)
def vendor_fields():
@@ -325,7 +911,7 @@ def vendor_fields():
{"key": "bills", "label": "Bills", "type": "link", "source": "overlay", "default": True,
"link": {"table": BILLS_KEY, "on": VENDOR_JOIN_KEY, "from": VENDOR_JOIN_KEY}},
_refreshed_field(),
- )]
+ )] + audit_fields(VENDORS_KEY)
def bill_fields():
@@ -363,7 +949,7 @@ def bill_fields():
"default": False,
"link": {"table": VENDORS_KEY, "on": VENDOR_JOIN_KEY, "from": VENDOR_JOIN_KEY}},
_refreshed_field(),
- )]
+ )] + audit_fields(BILLS_KEY)
def invoice_fields():
@@ -510,7 +1096,7 @@ def invoice_fields():
"default": False,
"link": {"table": ORDERS_KEY, "on": "order_no", "from": "origin_order"}},
_refreshed_field(),
- )]
+ )] + audit_fields(INVOICES_KEY)
def order_fields():
@@ -553,7 +1139,7 @@ def order_fields():
"default": True,
"link": {"table": INVOICES_KEY, "on": "origin_order", "from": "order_no"}},
_refreshed_field(),
- )]
+ )] + audit_fields(ORDERS_KEY)
# ═════════════════════════════════════════════════════════════════════════════════════════════
@@ -652,7 +1238,7 @@ def order_line_fields():
{"key": "state", "label": "State", "type": "select", "source": "overlay",
"default": False, "options": ["sale", "done"]},
_scope_field(),
- )]
+ )] + audit_fields(ORDER_LINES_KEY)
def gl_line_fields():
@@ -719,7 +1305,7 @@ def gl_line_fields():
{"key": "parent_state", "label": "Entry state", "type": "select", "source": "overlay",
"default": True, "options": ["draft", "posted", "cancel"]},
_scope_field(),
- )]
+ )] + audit_fields(GL_LINES_KEY)
def _stock_product_fields():
@@ -757,7 +1343,7 @@ def stock_move_fields():
{"key": "picking_id", "label": "Odoo picking id", "type": "int", "default": False}]
+ _stock_location_fields("source_location", "Source location")
+ _stock_location_fields("destination_location", "Destination location")
- )]
+ )] + audit_fields(STOCK_MOVES_KEY)
def stock_valuation_fields():
@@ -771,7 +1357,7 @@ def stock_valuation_fields():
{"key": "stock_move_id", "label": "Odoo stock move id", "type": "int", "default": False}]
+ _stock_location_fields("source_location", "Source location")
+ _stock_location_fields("destination_location", "Destination location")
- )]
+ )] + audit_fields(STOCK_VALUATION_KEY)
def stock_quant_fields():
@@ -782,7 +1368,7 @@ def stock_quant_fields():
+ [{"key": "qty", "label": "On hand", "type": "int", "agg": "sum", "default": True},
{"key": "reserved_qty", "label": "Reserved quantity", "type": "int",
"agg": "sum", "default": True}]
- )]
+ )] + audit_fields(STOCK_QUANT_KEY)
def product_fields():
@@ -1809,7 +2395,7 @@ def read_accounts(cur):
"account_type": t,
"is_expense": "1" if t in ("expense", "expense_depreciation") else "",
})
- return out
+ return _audit_enrich(cur, ACCOUNTS_KEY, out)
_VENDOR_DOCS = "state = 'posted' AND move_type IN ('in_invoice','in_refund')"
@@ -1841,7 +2427,7 @@ def read_bills(cur):
"payment_state": str(pay or ""),
"move_type": str(mtype or ""),
})
- return out
+ return _audit_enrich(cur, BILLS_KEY, out)
def read_vendors(cur):
@@ -1896,7 +2482,7 @@ def read_vendors(cur):
"city": str(city or ""),
"zip": str(zipc or ""),
})
- return out
+ return _audit_enrich(cur, VENDORS_KEY, out)
def customers_from(invoice_rows):
@@ -3419,7 +4005,8 @@ def stock_source_specs():
**_stock_location_cols("source_location", "sl", "sm.location_id"),
**_stock_location_cols("destination_location", "sd", "sm.location_dest_id"),
}
- return {
+ # S72-T43: the audited columns merge here, so the stock bindings and presets stay equal.
+ return merge_audit_cols({
STOCK_MOVES_KEY: {
"from_sql": "(stock_move sm LEFT JOIN product_product pp ON pp.id = sm.product_id"
+ locations + ")",
@@ -3450,7 +4037,7 @@ def stock_source_specs():
"reserved_qty": ("sq.reserved_quantity", _stock_number)},
"optional": ({**no_ancestry, "without": {"cols": {"location_fba": blank_fba}}},),
},
- }
+ })
def _stock_period(date_from, date_to, field):
@@ -3562,6 +4149,93 @@ def validate_wholesale_summary(client, cur):
'error_type': type(exc).__name__}]
+_POSTED_OUT = [("state", "=", "posted"), ("move_type", "in", ["out_invoice", "out_refund"]),
+ ("partner_id", "!=", False)]
+_POSTED_IN = [("state", "=", "posted"), ("move_type", "in", ["in_invoice", "in_refund"]),
+ ("partner_id", "!=", False)]
+
+#: S72-T43 total legs: grid key -> (model, population domain, Odoo date field, mirror date SQL,
+#: datetime?). The date bounds both sides to the validation period. Quants are a snapshot.
+_AUDIT_TOTAL_SCOPE = {
+ INVOICES_KEY: ("account.move", _POSTED_OUT, "invoice_date", "am.invoice_date", False),
+ BILLS_KEY: ("account.move", _POSTED_IN, "invoice_date", "invoice_date", False),
+ ORDERS_KEY: ("sale.order", [("state", "in", ["sale", "done"]), ("partner_id", "!=", False)],
+ "date_order", "date_order", True),
+ ORDER_LINES_KEY: ("sale.order.line", [("order_id.state", "in", ["sale", "done"]),
+ ("order_id.partner_id", "!=", False)],
+ "order_id.date_order", "so.date_order", True),
+ GL_LINES_KEY: ("account.move.line", [], "date", "aml.date", False),
+ SHIPMENTS_KEY: ("stock.picking", [("picking_type_code", "=", "outgoing")],
+ "scheduled_date", "sp.scheduled_date", True),
+ STOCK_MOVES_KEY: ("stock.move", [], "date", "sm.date", True),
+ STOCK_QUANT_KEY: ("stock.quant", [("location_id.usage", "=", "internal")], None, None, False),
+}
+
+#: A total read from a child model reaches the grid's population through this many2one.
+_AUDIT_PARENT = {"account.invoice.line.agent": "invoice_id"}
+
+
+def validate_audit_totals(client, cur, date_from="2025-07-01", date_to="2026-06-30",
+ id_window=None, keys=None):
+ """S72-T43 / rule 8: every audited total ties its mirror sum to an Odoo read_group sum.
+
+ `id_window` (lo, hi) narrows both sides to one id range of the grid's own row id, and `keys`
+ to some grids. Needs the mirror: without a cursor it returns no legs. Output carries no totals.
+ """
+ import math
+ if cur is None:
+ return []
+ import routes_odoo_tables as door
+ checks = []
+ for key, (model, domain, odoo_date, sql_date, stamp) in _AUDIT_TOTAL_SCOPE.items():
+ if keys is not None and key not in keys:
+ continue
+ sums = [entry for entry in AUDIT_FIELDS[key] if entry.get("agg") == "sum"]
+ lo, hi = ((date_from + " 00:00:00", date_to + " 23:59:59") if stamp
+ else (date_from, date_to))
+ for entry in sums:
+ name = "audit total " + key + " " + entry["key"]
+ try:
+ spec = door._source_for(cur, key)
+ if not spec:
+ raise Refused("the mirror has no binding for " + key)
+ expr = (spec["cols"].get(entry["key"]) or audit_projection(entry))[0]
+ terms, params = [spec.get("where") or ""], []
+ if odoo_date:
+ terms.append(f"{sql_date} >= ? AND {sql_date} <= ?")
+ params += [lo, hi]
+ if id_window:
+ terms.append(f"{spec['id']} >= ? AND {spec['id']} <= ?")
+ params += list(id_window)
+ where = " AND ".join("(" + t + ")" for t in terms if t)
+ total = cur.execute(
+ f"SELECT COALESCE(SUM({expr}), 0) FROM {spec.get('from_sql') or spec['table']}"
+ + (f" WHERE {where}" if where else ""), params).fetchone()[0]
+ odoo_domain = list(domain) + ([(odoo_date, ">=", lo), (odoo_date, "<=", hi)]
+ if odoo_date else [])
+ odoo_domain += ([("id", ">=", id_window[0]), ("id", "<=", id_window[1])]
+ if id_window else [])
+ child, field = _audit_split(entry["odoo"])
+ if child != model:
+ parent = _AUDIT_PARENT[child]
+ odoo_domain = [(parent if f == "id" else parent + "." + f, op, value)
+ for f, op, value in odoo_domain]
+ groups = client.read_group(child, odoo_domain, [field + ":sum"], ["create_uid"],
+ lazy=False)
+ summary = math.fsum(float(row.get(field) or 0.0) for row in groups)
+ total = float(total or 0.0)
+ error = abs(total - summary) / abs(summary) if summary else None
+ checks.append({"check": name, "observation": "mirror", "relative_error": error,
+ "ok": math.isfinite(total) and abs(total - summary) <= 0.01})
+ except Exception as exc: # noqa: BLE001
+ checks.append({"check": name, "ok": False, "error_type": type(exc).__name__,
+ "observation": "mirror"})
+ from odoo_purchasing import validate_audit_totals as purchasing_totals
+ end = (_dt.date.fromisoformat(date_to) + _dt.timedelta(days=1)).isoformat()
+ checks.extend(purchasing_totals(client, cur, date_from, end, id_window=id_window, keys=keys))
+ return checks
+
+
def validate(client, cur=None, date_from="2025-07-01", date_to="2026-06-30"):
"""Read-only stock reconciliation, using the caller's own Odoo client and optional mirror.
@@ -3665,6 +4339,7 @@ def validate(client, cur=None, date_from="2025-07-01", date_to="2026-06-30"):
"error_type": type(exc).__name__, "observation": plane})
checks.extend(validate_customer_rollups(client, cur))
checks.extend(validate_wholesale_summary(client, cur))
+ checks.extend(validate_audit_totals(client, cur, date_from, date_to))
return checks
diff --git a/api/provider_limits.py b/api/provider_limits.py
index a6f10b328a6a750c8a571b9c9c33113d0104881a..10d4d76514b6cdecc466edde6a68c7db11f63425 100644
--- a/api/provider_limits.py
+++ b/api/provider_limits.py
@@ -3,7 +3,8 @@ import time
RETRY_WAITS = (20, 40, 60)
RESUMED_MESSAGE = "Loopy was paused by a provider limit and picked this up again."
-PAUSED_MESSAGE = "Loopy is paused because the model provider is limiting requests. Try again in a few minutes."
+#: The C2 `provider_limited` sentence: a limited provider pauses the turn and it resumes.
+PAUSED_MESSAGE = "The model is busy. Your answer resumes shortly."
class RetryStopped(Exception):
diff --git a/api/providers.py b/api/providers.py
index 9d00d15104e6990c999b63197318c4c26f67b17d..7889956a051c99e2e5a7e5fbb2a8552220db65d7 100644
--- a/api/providers.py
+++ b/api/providers.py
@@ -376,6 +376,13 @@ class LlmProvider:
#: which is a different body, a different auth header and a different result shape.
wire: str
caps: dict = field(default_factory=dict)
+ #: Env var that overrides `model`, read at call time. Blank or unset uses `model`.
+ model_env: str = ""
+
+ def current_model(self) -> str:
+ """The model id a call sends and an audit names: `model_env` when set, else `model`."""
+ override = (os.environ.get(self.model_env) or "").strip() if self.model_env else ""
+ return override or self.model
def configured(self) -> bool:
return bool((os.environ.get(self.env) or "").strip())
@@ -385,10 +392,10 @@ class LlmProvider:
return bool(cap and cap.capable and self.configured())
-#: ⭐ ORDER IS THE LADDER, AND ANTHROPIC IS FIRST BECAUSE OF R4. `routes_query`'s old comment put
-#: cerebras first *"because this path needs tool calling and cerebras carries this account's
-#: tool-capable model"* — R4 replaces that premise: Anthropic is the tool-calling path that always
-#: works, and the others are the cheap seats it falls through to.
+#: The cheapest OpenRouter model that reached 17 of 26 on the assistant eval (S72-T21).
+OPENROUTER_DEFAULT_MODEL = "z-ai/glm-4.7-flash"
+
+#: Every declared provider. Only the names in `LLM_DEFAULT_ORDER` are ever called (R116).
LLM_PROVIDERS: dict[str, LlmProvider] = {
"anthropic": LlmProvider(
name="anthropic", label="Anthropic", env="ANTHROPIC_API_KEY",
@@ -461,7 +468,7 @@ LLM_PROVIDERS: dict[str, LlmProvider] = {
"openrouter": LlmProvider(
name="openrouter", label="OpenRouter", env="OPENROUTER_API_KEY",
url="https://openrouter.ai/api/v1/chat/completions",
- model="openai/gpt-4o-mini", wire="openai",
+ model=OPENROUTER_DEFAULT_MODEL, model_env="AIOS_OPENROUTER_MODEL", wire="openai",
caps={
# ⭐ MEASURED 2026-08-19, W37-T39 (was "DECLARED, not measured"): HTTP 200 with a typed
# `tool_calls` block. So on the OpenAI wire BOTH reachable rungs tool-call cleanly, and
@@ -473,7 +480,8 @@ LLM_PROVIDERS: dict[str, LlmProvider] = {
}),
}
-LLM_DEFAULT_ORDER = ("anthropic", "cerebras", "groq", "openrouter")
+#: Every Assistant turn goes through OpenRouter and no other provider is called (R116).
+LLM_DEFAULT_ORDER = ("openrouter",)
def mark_no_credit(name, seconds=None):
@@ -515,12 +523,11 @@ def llm_chain(capability="llm_tool_calling"):
turn cannot be spent discovering it (the `chain()` rule, one layer up).
2. `no_credit()` — R4's skip. A provider that told us its balance is empty is passed over
until the memo expires.
- 3. the ORDER itself, overridable with `AIOS_LLM_ORDER` (`anthropic,groq`) so a deployment
- can be moved off a vendor without a release — the same clause `AIOS_PROVIDER_ORDER`
- carries for the scraping side.
+ 3. the ORDER itself. `AIOS_LLM_ORDER` may reorder or drop names in `LLM_DEFAULT_ORDER`
+ and never adds one, so an env value cannot bring a retired provider back (R116).
"""
raw = (os.environ.get("AIOS_LLM_ORDER") or "").strip()
- names = [x.strip() for x in raw.split(",") if x.strip()] or list(LLM_DEFAULT_ORDER)
+ names = [x.strip() for x in raw.split(",") if x.strip() in LLM_DEFAULT_ORDER] or list(LLM_DEFAULT_ORDER)
return [LLM_PROVIDERS[n] for n in names
if n in LLM_PROVIDERS and LLM_PROVIDERS[n].can(capability) and not no_credit(n)]
@@ -754,7 +761,7 @@ def llm_status(capability="llm_tool_calling"):
p = LLM_PROVIDERS[name]
cap = p.caps.get(capability)
rows.append({
- "provider": p.name, "label": p.label, "model": p.model, "wire": p.wire,
+ "provider": p.name, "label": p.label, "model": p.current_model(), "wire": p.wire,
"configured": p.configured(),
"toolCalling": bool((p.caps.get("llm_tool_calling") or Capability(False)).capable),
"jsonMode": bool((p.caps.get("llm_json_mode") or Capability(False)).capable),
diff --git a/api/routes_admin.py b/api/routes_admin.py
index d0459f2697c0bbf1c275308ce4ec0d9abe73e7b2..8681e33b46ca1625c0c803e5b48d43e7aa0e898a 100644
--- a/api/routes_admin.py
+++ b/api/routes_admin.py
@@ -2436,6 +2436,155 @@ def _sync_database_shares(session, uname, before, after):
raise err(409, "shares_changed", "Database sharing changed. Save access again.") from exc
+def _set_database_request_share(session, key, entries, held, snapshot):
+ """Keep share provenance and metadata behind a fresh synchronous CAS."""
+ import copy
+ from core import shares
+
+ class BoundStore:
+ def get(self, name):
+ return session.runtime.get(name, fresh=True)
+
+ def update(self, name, fn, flush='async'):
+ def guarded(data):
+ current = (data.get('database') or {}).get(key)
+ if current != snapshot:
+ raise shares.GrantsChanged('Database sharing changed during approval.')
+ before = copy.deepcopy(current or {})
+ result = fn(data)
+ after = (result.get('database') or {}).get(key)
+ if after is not None:
+ prior_rows = {row['user']: row for row in before.get('entries') or ()}
+ after['entries'] = [{**prior_rows.get(row['user'], {}), **row}
+ for row in after['entries']]
+ result['database'][key] = {**before, **after}
+ return result
+ return session.runtime.update(name, guarded, flush='sync')
+
+ return shares.set_grants('database', key, entries, st=BoundStore(),
+ granter=session.uname, expect=held['entries'])
+
+
+def grant_database_access(session, username, database, role):
+ """Grant one supported database role with account CAS and guarded share compensation."""
+ import copy
+ from core import perm_scope, shares, user_tables
+
+ admin_gate(session)
+ uname = str(username or '').strip().lower()
+ key = str(database or '').strip()
+ is_table = key.startswith(user_tables.KEY_PREFIX)
+ if role not in ('view', 'edit') or (not is_table and role != 'view'):
+ raise err(409, 'unsupported_role', 'This database supports only viewing access.')
+ tenant = str(session.runtime.tenant.slug).strip().lower()
+ if _tenant_of(session.user) != tenant:
+ raise err(403, 'forbidden', 'Database access could not be granted.')
+ # Read the account store strictly rather than the directory's fail-silent projection.
+ reg = store.get('users', fresh=True)
+ actor, rec = (reg or {}).get(session.uname), (reg or {}).get(uname)
+ if (not isinstance(actor, dict) or actor.get('role') != 'admin'
+ or not actor.get('active', True) or _tenant_of(actor) != tenant):
+ raise err(403, 'forbidden', 'Database access could not be granted.')
+ if (not isinstance(rec, dict) or not rec.get('active', True) or _tenant_of(rec) != tenant):
+ raise err(404, 'no_such_user', 'That account is not active in this workspace.')
+ if uname == session.uname:
+ raise err(400, 'self_perms', 'Ask another administrator to change your access.')
+ governed = {m['key'] for m in _perm_modules(session)}
+ if key not in governed:
+ raise err(404, 'no_database', 'That database is not available in this workspace.')
+ principal = users._public(uname, rec)
+ if perm_scope.may_read(principal, key, st=session.runtime) and (
+ role == 'view' or user_tables.may_edit_database(key, uname, False, st=session.runtime)):
+ return {'username': uname, 'database': key, 'role': role}
+ expected = users.database_access_state(rec)
+ prior = copy.deepcopy((rec.get('perms') or {}).get(key))
+ candidate = dict(prior or {}, access=True)
+ cleaned = _clean_perms({key: candidate}, governed_keys=governed,
+ session=session, stored=rec.get('perms'))
+ folded = _fold_legacy_scope(rec, cleaned)
+ _guard_bu_widening(rec, folded, False)
+ # Validation may prune retired fields. This click changes access, so retain stored walls.
+ if folded[key].get('filter') != cleaned[key].get('filter'):
+ candidate['filter'] = folded[key]['filter']
+
+ bucket = (session.runtime.get(shares.SHARES_KEY, fresh=True) or {}) if is_table else {}
+ held = shares.grants('database', key, st=user_tables.lend(
+ session.runtime, **{shares.SHARES_KEY: bucket})) if is_table else None
+ snapshot = copy.deepcopy((bucket.get('database') or {}).get(key)) if is_table else None
+ if is_table and role == 'view':
+ definition = user_tables.get_one(key, session.runtime) or {}
+ if uname in (held['owner'], definition.get('createdBy')):
+ raise err(409, 'unsupported_role', 'An administrator must review the database owner access.')
+ proposed = None
+ if held is not None:
+ proposed = copy.deepcopy(held['entries'])
+ for row in proposed:
+ if row['user'] == uname:
+ row['role'] = role
+ break
+ else:
+ proposed.append({'user': uname, 'role': role, 'by': session.uname})
+
+ def compensate_share():
+ if held is None or proposed == held['entries']:
+ return
+ bucket_now = session.runtime.get(shares.SHARES_KEY, fresh=True) or {}
+ current = shares.grants('database', key, st=user_tables.lend(
+ session.runtime, **{shares.SHARES_KEY: bucket_now}))
+ ours = [row for row in proposed if row['user'] == uname]
+ target = [row for row in current['entries'] if row['user'] == uname]
+ old = [row for row in held['entries'] if row['user'] == uname]
+ if target == old:
+ return
+ if target != ours:
+ raise err(409, 'compensation_conflict', 'Database sharing changed. Ask an administrator to review access.')
+ restored = [item for row in current['entries']
+ for item in (old if row['user'] == uname else [row])]
+ # Keep other principals' fresh grants. Never restore an old whole share list.
+ _set_database_request_share(session, key, restored, current,
+ copy.deepcopy((bucket_now.get('database') or {}).get(key)))
+
+ account_attempted = False
+ result = None
+ try:
+ if held is not None and proposed != held['entries']:
+ # Sharing comes first so an enabled view request cannot inherit an old edit grant.
+ _set_database_request_share(session, key, proposed, held, snapshot)
+ account_attempted = True
+ result = users.set_database_access(uname, key, candidate, actor=session.uname,
+ tenant=tenant, expect=expected,
+ legacy_filter=(candidate.get('filter') if
+ folded[key].get('filter') != cleaned[key].get('filter') else None))
+ if result.get('status') != 'updated':
+ code = result.get('status')
+ raise err(409 if code == 'conflict' else 403, 'permissions_changed',
+ 'Account access changed. Request access again.')
+ if held is not None:
+ current = shares.grants('database', key, st=session.runtime)
+ if ([row for row in current['entries'] if row['user'] == uname]
+ != [row for row in proposed if row['user'] == uname]):
+ raise shares.GrantsChanged('Database sharing changed during approval.')
+ except Exception:
+ # A store can report failure after committing. Undo only our exact account transition.
+ try:
+ if account_attempted and (result is None or result.get('status') == 'updated'):
+ fresh = store.get('users', fresh=True) or {}
+ current = fresh.get(uname) or {}
+ intended = copy.deepcopy(expected)
+ intended['perms'] = dict(expected.get('perms') or {}, **{key: candidate})
+ if ((current.get('perms') or {}).get(key) == candidate and intended != expected):
+ restored = users.set_database_access(
+ uname, key, prior, actor=session.uname, tenant=tenant,
+ expect=users.database_access_state(current), restore=expected)
+ if restored.get('status') != 'updated':
+ raise err(409, 'compensation_conflict',
+ 'Account access changed. Ask an administrator to review access.')
+ finally:
+ compensate_share()
+ raise
+ return {'username': uname, 'database': key, 'role': role}
+
+
@router.put("/admin/users/{username}/perms")
def put_perms(username: str, body: dict = Body(default=None),
session: Session = Depends(admin_gate)):
diff --git a/api/routes_applications.py b/api/routes_applications.py
index 5f94659633671e871d3a51ba9efe85fbd68d4e57..83bac654d78016b132e6e675cf392d55436948da 100644
--- a/api/routes_applications.py
+++ b/api/routes_applications.py
@@ -134,10 +134,10 @@ def reconcile_finance_fact(fact_key: str, bu: str | None = None,
@nav_router.get("/nav/applications")
def list_nav_applications(session: Session = Depends(require_session)):
- """Every Application this session may open, in ONE generic navigation shape (R6).
+ """The App home: stored Applications this session owns or was shared (R102).
- Finance's six arrive here as seeded Application records rather than as new template kinds,
- so the App module reaches them by the same path Routing and Catalog ride.
+ No code projection rides here. A stored Finance copy is listed while this session's wall
+ admits its permission key.
"""
if not session.runtime.available():
raise err(503, "store_unavailable", "the tenant store is unavailable")
diff --git a/api/routes_assets.py b/api/routes_assets.py
index c51bb922bc50a971a3dcc8ec58f9ff3b35b5aed8..5c0c7cd364d24b4eebb9c3a2ac587a00216f92b1 100644
--- a/api/routes_assets.py
+++ b/api/routes_assets.py
@@ -82,6 +82,27 @@ def application_access_context(session, databases, *, strict=False):
return allowed, records
+def _session_wall(session):
+ """The `routes_applications._may_open` session wall, as a one-argument predicate."""
+ from routes_applications import _may_open
+ return lambda key: _may_open(session, key)
+
+
+def finance_access(session, application_id):
+ """True for a stored Finance copy this session's wall admits; False for any other App.
+
+ A Finance copy binds no database, so the database wall does not apply to it. One the wall
+ refuses is hidden from the App home, so its doors answer "does not exist".
+ """
+ app = applications.load(session.runtime)["applications"].get(application_id)
+ if not applications._is_finance(app):
+ return False
+ key = applications._finance_permission(app)
+ if not key or not _session_wall(session)(key):
+ raise applications.ApplicationError("application does not exist")
+ return True
+
+
def _application_databases(runtime, application_id=None):
doc = applications.load(runtime)
if application_id:
@@ -104,7 +125,8 @@ def application_index(database: str = "", type: str = "", starred: bool | None =
_application_error(exc)
return {"applications": applications.list_apps(
session.runtime, session.uname, session.admin, database=database or None,
- kind=type or None, starred=starred, allowed_databases=allowed)}
+ kind=type or None, starred=starred, allowed_databases=allowed,
+ may_open=_session_wall(session))}
@router.post("/applications", status_code=201)
@@ -126,6 +148,10 @@ def create_application(body: dict = Body(default=None),
def update_application(application_id: str, body: dict = Body(default=None),
session: Session = Depends(require_session)):
try:
+ if finance_access(session, application_id):
+ return {"application": applications.mutate(
+ session.runtime, application_id, session.uname, session.admin, body,
+ allowed_databases=set())}
current = _application_databases(session.runtime, application_id)
if not current:
raise applications.ApplicationError("application does not exist")
@@ -149,6 +175,10 @@ def update_application(application_id: str, body: dict = Body(default=None),
def duplicate_application(application_id: str,
session: Session = Depends(require_session)):
try:
+ if finance_access(session, application_id):
+ return {"application": applications.duplicate(
+ session.runtime, application_id, session.tenant, session.uname, session.admin,
+ allowed_databases=set())}
current = _application_databases(session.runtime, application_id)
if not current:
raise applications.ApplicationError("application does not exist")
@@ -164,29 +194,18 @@ def duplicate_application(application_id: str,
def delete_application(application_id: str, body: dict = Body(default=None),
session: Session = Depends(require_session)):
try:
- current = _application_databases(session.runtime, application_id)
- allowed, _ = application_access_context(session, current)
- if not allowed:
- raise applications.ApplicationError("application does not exist")
- confirm_name = (body or {}).get("confirmName")
-
- class NameConfirmedDelete:
- """Keep confirmation inside the registry's existing atomic update and permission gate."""
-
- def update(self, key, delete):
- def confirmed(raw):
- # The registry validates access and copies the document before removing the App.
- # A refusal below never reaches persistence, even if its name changed mid-request.
- deleted = delete(raw)
- app = raw["applications"][application_id]
- if not isinstance(confirm_name, str) or confirm_name != app.get("name"):
- raise applications.ApplicationError("enter the exact App name to confirm deletion")
- return deleted
-
- return session.runtime.update(key, confirmed)
-
- return applications.delete(NameConfirmedDelete(), application_id, session.uname, session.admin,
- allowed_databases=allowed)
+ # A Finance copy binds no database: only its owner and the session wall gate it.
+ if finance_access(session, application_id):
+ allowed = set()
+ else:
+ current = _application_databases(session.runtime, application_id)
+ allowed, _ = application_access_context(session, current)
+ if not allowed:
+ raise applications.ApplicationError("application does not exist")
+ # The name check runs inside the registry's atomic update, after its permission gate.
+ return applications.delete(session.runtime, application_id, session.uname, session.admin,
+ allowed_databases=allowed,
+ confirm_name=(body or {}).get("confirmName"))
except (applications.ApplicationError, PermissionError) as exc:
_application_error(exc)
diff --git a/api/routes_assistant_memory.py b/api/routes_assistant_memory.py
index 8cc5be5586b00ac6418209fb145928dbe6fae2f3..b372cd1baf632ed6002411f96f1f421fa6417213 100644
--- a/api/routes_assistant_memory.py
+++ b/api/routes_assistant_memory.py
@@ -3,6 +3,16 @@ from fastapi import APIRouter, Depends
from deps import Session, err, module_gate, require_session
import assistant_memory
+from core import external_access
+
+
+def _active(session):
+ if session.tenant != session.runtime.key:
+ raise err(403, "forbidden", "This account is unavailable in this workspace.")
+ try:
+ return external_access.resolve_active_user(session.uname, session.tenant)
+ except external_access.ExternalAccessError as exc:
+ raise err(403, "forbidden", "This account is unavailable in this workspace.") from exc
router = APIRouter(prefix="/api/v1/assistant", dependencies=[Depends(module_gate("analyst"))])
@@ -12,10 +22,14 @@ def erase_memory(id: str, session: Session = Depends(require_session)):
"""Return the same refusal for a missing id and another user's id."""
if not session.runtime.available():
raise err(503, "store_unavailable", "The tenant store is unavailable.")
+ _active(session)
deleted = assistant_memory.forget(session.runtime, session.uname, id)
- if not deleted and session.admin:
- deleted = assistant_memory.forget_company(session.runtime, {
- "tenant": session.tenant, "username": session.uname}, id)
+ if not deleted:
+ try:
+ deleted = assistant_memory.forget_company(session.runtime, {
+ "tenant": session.tenant, "username": session.uname}, id)
+ except external_access.ExternalAccessError as exc:
+ raise err(403, "forbidden", "This account is unavailable in this workspace.") from exc
if not deleted:
raise err(404, "assistant_memory_not_found", "That memory entry was not found.")
return {"deleted": True}
@@ -23,7 +37,8 @@ def erase_memory(id: str, session: Session = Depends(require_session)):
@router.post("/memory/{id}/promote")
def promote_memory(id: str, session: Session = Depends(require_session)):
- if not session.admin:
+ from core import perms
+ if not perms.is_admin(_active(session)):
raise err(403, "forbidden", "Only an Administrator can share a company fact.")
if not session.runtime.available():
raise err(503, "store_unavailable", "The tenant store is unavailable.")
@@ -32,6 +47,8 @@ def promote_memory(id: str, session: Session = Depends(require_session)):
"tenant": session.tenant, "username": session.uname}, id)
except PermissionError as exc:
raise err(403, "forbidden", str(exc)) from exc
+ except external_access.ExternalAccessError as exc:
+ raise err(403, "forbidden", "This account is unavailable in this workspace.") from exc
except ValueError as exc:
raise err(409, "assistant_memory_source_unproven", str(exc)) from exc
if entry is None:
diff --git a/api/routes_connectors.py b/api/routes_connectors.py
index 6518fbd3ed90cc1d057a4b450a838089827ffaa3..5a04c20b057e64f177aa15422005b97d2b03e11e 100644
--- a/api/routes_connectors.py
+++ b/api/routes_connectors.py
@@ -2684,6 +2684,53 @@ def odoo_status(connection_id: str = None, session: Session = Depends(require_se
"receipt": receipt}
+def _daily_completed_sync(rt, connector_key):
+ """Read completed mirror markers; never create a mirror or contact a provider."""
+ if connector_key == "amazon_sp":
+ import connectors_amazon as cx
+ try:
+ states = cx.sync_state(rt, rt.key)
+ except cx.AmazonStatusSafetyError as refused:
+ states = dict(getattr(refused, "safe_status", None) or {})
+ except Exception:
+ return None, False
+ if not isinstance(states, dict):
+ return None, False
+ rows = [row for row in states.values() if isinstance(row, dict) and not row.get("declared")]
+ stamps = [_sync_stamp(row.get("lastSuccess")) for row in rows]
+ stamps = [stamp for stamp in stamps if stamp]
+ if stamps:
+ return max(stamps, key=datetime.fromisoformat), True
+ # This is the existing reader's explicit unreadable-mirror outcome, not a never-run fact.
+ unknown = any(str(row.get("unknownCause") or "").startswith(
+ "This container has no readable sync status.") for row in rows)
+ return None, bool(rows) and not unknown
+ if connector_key == "meta_ads":
+ from pathlib import Path
+ from harness import datastore
+ import duckdb
+
+ def read(cursor):
+ row = cursor.execute("SELECT phase, updated_at FROM _sync_state WHERE entity = ?",
+ ["meta"]).fetchone()
+ if row is None or row[0] != "done":
+ return None, True
+ stamp = _sync_stamp(row[1])
+ return stamp, stamp is not None
+
+ try:
+ path = Path(getattr(rt, "datastore_path", None) or datastore.path_for(rt.key))
+ if not path.is_file():
+ return None, False
+ if path.resolve() == Path(datastore.DB_PATH).resolve():
+ return read(datastore.ro_cursor())
+ with duckdb.connect(str(path), read_only=True) as cursor:
+ return read(cursor)
+ except Exception:
+ return None, False
+ return None, False
+
+
@router.get("/connectors/{connector_key}/sync")
def connector_sync_status(connector_key: str, connection_id: str = None,
session: Session = Depends(require_session)):
@@ -2693,7 +2740,12 @@ def connector_sync_status(connector_key: str, connection_id: str = None,
f"{connector_key} is not registered for connector sync")
row = (connector_sync.job_summary(_connection_jobs(session.runtime, connector_key, connection_id))
or connector_sync.read(session.runtime, connector_key, connection_id))
- return _sync_payload(connector_key, connection_id, row)
+ answer = _sync_payload(connector_key, connection_id, row)
+ if connector_key in ("amazon_sp", "meta_ads"):
+ completed, known = _daily_completed_sync(session.runtime, connector_key)
+ answer.update(schedule="daily", lastCompletedAt=completed,
+ lastCompletedKnown=known, canSync=bool(session.admin))
+ return _safe_connector_status(connector_key, answer)
@router.post("/connectors/{connector_key}/sync/now")
diff --git a/api/routes_customers.py b/api/routes_customers.py
index e8eb853b11351a68306eabb4dd95cbf8682dc38c..2ea414a90018a3c26afc4dcbe0d176405f173d36 100644
--- a/api/routes_customers.py
+++ b/api/routes_customers.py
@@ -193,7 +193,6 @@ def _pool_for(rt, team_id, agent):
import routes_keychain
key = ("pool", team_id, agent)
-
if routes_keychain.odoo_paused(rt):
hit = rt.pool_cache.get(key)
if hit:
@@ -206,6 +205,12 @@ def _pool_for(rt, team_id, agent):
"this data source is paused and no snapshot exists for your scope. "
"An admin can resume it under Settings → Connectors")
+ hit = rt.pool_cache.get(key)
+ if hit and not cl.pool_has_audit(hit[1]):
+ # New columns refresh an active source. A frozen snapshot remains the last read of
+ # this exact scope; newly declared attributes stay unknown until the source resumes.
+ rt.pool_cache.pop(key, None)
+
def _build():
# ⚠ THE SCOPE GOES INTO THE BUILDER. `pool(agent_name, team_id)` is the same reconciled
# builder the Streamlit page uses — passing the scope here is what makes the isolation a
@@ -517,6 +522,7 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
with_rows: bool = True, needed=None):
"""C2: one wall- and revision-scoped memo for customer, product and stored envelopes."""
global grid_assembly_shared
+ import aios_grid
rt = session.runtime
needed = None if needed is None else frozenset(str(key) for key in needed)
if build is None:
@@ -539,7 +545,9 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
separators=(",", ":"), default=str),
_wall_stamp(session, table_key) if memoable else None, pool_stamp(),
("full" if needed is None else ("columns", tuple(sorted(needed))))
- if with_rows else "fields")
+ if with_rows else "fields",
+ hashlib.sha256(json.dumps(aios_grid.FIELDS, sort_keys=True,
+ default=str).encode()).hexdigest())
if not memoable:
result = ((*prefix, json.dumps(None)), {})
return result
@@ -882,8 +890,6 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
# HIDDEN. So an unthreaded `st` UNDER-shares (a grantee cannot see their own column) rather
# than over-shares — visible and reportable, but still wrong, and `visible_fields`' own note
# requires the two calls to agree about it.
- # Internal wall inputs stay outside workspace, fields and all public row projections.
- permission_scope = {"fields": fields, "rows": rows_src, "row_fields": aios_grid.FIELDS}
hidden = perm_scope.hidden_keys(session.user, MODULE, fields, st=rt)
if hidden:
fields = [f for f in fields if f.get("key") not in hidden]
@@ -994,7 +1000,6 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
for pid, cells in _ovc.items()}
return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
"fields": fields, "views": views, "lists": lists, "derived": derived,
- "_permission_scope": permission_scope,
"measures": measures, "measure_sets": measure_sets, "today": today,
"team_id": team_id, "routes": normalized_routes, "zones": normalized_zones}
diff --git a/api/routes_external.py b/api/routes_external.py
index 979b182624b43566ed2284b7455a5bfa884ef51a..129ae5adda731be63dfe23529d8df9e5a4d924a6 100644
--- a/api/routes_external.py
+++ b/api/routes_external.py
@@ -144,6 +144,9 @@ class _PreviewRuntime:
def get_many(self, names):
return {str(name): self.get(name) for name in names or ()}
+ def get_entry(self, name, entry):
+ return copy.deepcopy((self.get(name) or {}).get(entry))
+
def get_projections(self, names, drop=(), timeout_s=None):
return {str(name): self.get_projection(name, drop=drop) for name in names or ()}
@@ -2937,7 +2940,7 @@ def _tool_context(session: Session, *, preview=False) -> external_tools.ToolCont
view_event=lambda kind, args: _view_event(session, kind, args),
view_share_preview=lambda args: _view_share_preview(session, args),
app_upsert=lambda args: _application_upsert(session, args),
- # Reuse the UI's atomic NameConfirmedDelete wrapper as well as the registry delete.
+ # The registry delete checks confirmName atomically.
app_delete=lambda args: routes_assets.delete_application(
args["app_id"], {"confirmName": args["confirmName"]}, session),
database_object=lambda args: (_plan_database_write(session, args)
@@ -3280,9 +3283,7 @@ def _mcp_guide(session: Session) -> str:
lines = ["# Loopable guide", "", f"Signed in as {session.uname}.", "", MCP_INSTRUCTIONS, "",
"## Your databases", "",
"Call describe_database with a key below for its fields before you query it.", ""]
- key_databases = _key_scope(session)[1]
- rows = [row for row in _resolve_external_scope(session) if row["permitted"]
- and external_access.database_allowed(key_databases, row["database"])]
+ rows = [row for row in _resolve_external_scope(session) if row["permitted"]]
for row in rows:
note = "" if row["answerable"] else f" Not queryable right now: {_markdown_inline(row['reason'])}"
lines.append(f"- `{row['database']}`: {_markdown_inline(row['label'])}.{note}")
diff --git a/api/routes_files.py b/api/routes_files.py
index 487ae374dffc80433174daba077b2aff5a38627a..ed33b4ba08eb70adbb3d668a9d246ef949f4b6b6 100644
--- a/api/routes_files.py
+++ b/api/routes_files.py
@@ -24,8 +24,9 @@ def _response(rt, item):
raise err(503, "file_unavailable", "This file could not be read.") from exc
if data is None:
raise _unknown()
- return Response(content=data, media_type="application/pdf", headers={
- "Content-Disposition": f'inline; filename="{item["filename"]}"',
+ disposition = "attachment" if item["mime"] == assistant_files.XLSX_MIME else "inline"
+ return Response(content=data, media_type=item["mime"], headers={
+ "Content-Disposition": f'{disposition}; filename="{item["filename"]}"',
"Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff"})
diff --git a/api/routes_module_index.py b/api/routes_module_index.py
index 3caf9c642a4f4e8db76e75eb03862c835661daeb..351d6e6c6d5de2c4fb8d3167d6a12b3490b57d8b 100644
--- a/api/routes_module_index.py
+++ b/api/routes_module_index.py
@@ -66,13 +66,8 @@ def _readable_ids(module, session):
# only listed items, so an unverifiable placement renders no tile. Use local voice
# records, never audience-option assembly, just to verify placement ids.
if module == "app":
- # S67-T38 (O24): the App home also renders the seeded Finance projections, so the wall
- # admits their ids through the SAME grant filter /nav/applications uses. Never ungated:
- # a Finance card the session cannot open is not placeable.
stored = {row["id"] for row in routes_assets.application_index(session=session)["applications"]}
- finance = application_registry.finance_application_records(
- may_open=lambda permission: _may_open(session, permission))
- return stored | {row["id"] for row in finance}
+ return stored
# ⭐⭐ W62-T17 — THE ID-ONLY ACCESSOR THIS COMMENT USED TO ASK FOR NOW EXISTS. It read
# *"all_definitions omits synthetic field/Odoo agents. Keep the complete automation list until
# it has an id-only accessor"*, and the whole Agents rail payload was being built to answer a
diff --git a/api/routes_nav.py b/api/routes_nav.py
index e280ab37de7a0dee8bcc6dd296c786943fa33bd3..380b6b9c8113868bae9fde8835648b5fb91599bb 100644
--- a/api/routes_nav.py
+++ b/api/routes_nav.py
@@ -10,7 +10,10 @@ The full rule set — archived is invisible to everyone, `group_only` rows are e
`prefs.json` Library preference is deliberately NOT applied — is documented on
`core.perms.nav_pages`, which is where it belongs: one place, both callers.
"""
+import json
+import re
import time
+from datetime import datetime, timezone
from fastapi import APIRouter, Body, Depends
@@ -1072,6 +1075,86 @@ def save_nav_prefs(body: dict = Body(default=None),
return {"prefs": clean}
+#: S72 C5: one user's small JSON preferences by key. A separate bucket from `nav_prefs`, so a
+#: keyed write never rewrites the folder picture. Shape: {uname: {key: {"value", "updated_at"}}}.
+_NAV_USER_PREFS_KEY = "nav_user_prefs"
+_USER_PREF_KEY_RE = re.compile(r"[a-z][a-z0-9_.:-]{0,79}")
+_MAX_USER_PREF_BYTES = 8192
+#: A full bucket refuses a NEW key loudly; it never evicts another key to make room.
+_MAX_USER_PREFS = 64
+
+
+def _user_pref_key(key):
+ key = str(key or "")
+ if not _USER_PREF_KEY_RE.fullmatch(key):
+ raise err(400, "pref_key_invalid", "That preference name is not valid.")
+ return key
+
+
+def _user_pref_bytes(value):
+ return len(json.dumps(value, separators=(",", ":"), ensure_ascii=False).encode("utf-8"))
+
+
+def _user_pref_now():
+ """A UTC ISO instant with a Z suffix, never naive local time."""
+ return datetime.fromtimestamp(_now(), timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+@router.get("/nav/prefs/{key}")
+def get_user_pref(key: str, session: Session = Depends(require_session)):
+ """C5: this user's stored value for one preference key, or 404 when unset."""
+ key = _user_pref_key(key)
+ try:
+ bucket = (session.runtime.get(_NAV_USER_PREFS_KEY) or {}).get(session.uname) or {}
+ except Exception:
+ raise err(503, "store_unavailable", "Your saved preferences could not be loaded.")
+ row = bucket.get(key) if isinstance(bucket, dict) else None
+ if not isinstance(row, dict) or "value" not in row:
+ raise err(404, "pref_not_set", "That preference is not saved yet.")
+ return {"key": key, "value": row.get("value"), "updated_at": row.get("updated_at")}
+
+
+@router.put("/nav/prefs/{key}")
+def put_user_pref(key: str, body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """C5: replace this user's value for one preference key, up to 8 KB of JSON."""
+ key = _user_pref_key(key)
+ if not isinstance(body, dict) or "value" not in body:
+ raise err(400, "bad_request", "Send the preference as a value.")
+ value = body.get("value")
+ size = _user_pref_bytes(value)
+ if size > _MAX_USER_PREF_BYTES:
+ raise err(400, "pref_too_large",
+ f"That preference is {size} bytes and the limit is {_MAX_USER_PREF_BYTES}. Nothing was saved.")
+ stamp, uname = _user_pref_now(), session.uname
+ from core import freeze_notice
+ if freeze_notice.enabled():
+ return {"key": key, "value": value, "updated_at": stamp}
+ if not session.runtime.available():
+ raise err(503, "store_unavailable", "The tenant store is unavailable. Nothing was saved.")
+ full = False
+
+ def _up(data):
+ nonlocal full
+ data = data if isinstance(data, dict) else {}
+ mine = dict(data.get(uname) or {}) if isinstance(data.get(uname), dict) else {}
+ if key not in mine and len(mine) >= _MAX_USER_PREFS:
+ full = True
+ return data
+ mine[key] = {"value": value, "updated_at": stamp}
+ data[uname] = mine
+ return data
+
+ try:
+ session.runtime.update(_NAV_USER_PREFS_KEY, _up)
+ except Exception:
+ raise err(503, "store_unavailable", "The store refused the write. Nothing was saved.")
+ if full:
+ raise err(409, "prefs_full",
+ f"Your account already keeps {_MAX_USER_PREFS} saved preferences. Nothing was saved.")
+ return {"key": key, "value": value, "updated_at": stamp}
+
+
def _schema_means(key: str) -> dict:
"""`{field_key: the agent's semantic definition}` for a database, or `{}` when there is none.
@@ -1395,6 +1478,8 @@ def create_nav_application(body: dict = Body(default=None),
allowed_databases={source})
except PermissionError as exc:
raise err(403, "forbidden", str(exc))
+ except application_registry.ApplicationExistsError as exc:
+ raise err(400, "app_exists", str(exc), {"existing": exc.existing})
except application_registry.ApplicationError as exc:
raise err(400, "bad_application", str(exc))
except Exception:
diff --git a/api/routes_odoo_tables.py b/api/routes_odoo_tables.py
index a5df46b2e1b5c69216ddc4f7363715d69b36ce78..2fcd8d2b2b9df7605cb10ede786a427ac5b46602 100644
--- a/api/routes_odoo_tables.py
+++ b/api/routes_odoo_tables.py
@@ -1106,6 +1106,8 @@ def _odoo_sources():
GRID_SOURCES.update(rel.stock_source_specs())
GRID_SOURCES.update(rel.purchase_source_specs())
GRID_SOURCES[rel.SHIPMENTS_KEY] = rel.shipment_source_spec()
+ # S72-T43 / R107: the audited Odoo columns. Their presets are declared in `odoo_relational`.
+ GRID_SOURCES = rel.merge_audit_cols(GRID_SOURCES)
for key, spec in GRID_SOURCES.items():
if key in rel.READ_THROUGH_KEYS:
spec["mirror_only"] = True
diff --git a/api/routes_products.py b/api/routes_products.py
index 1b6771b815f687b03c427dd0af52879cba19cce6..8706eb06cc1ee52234f35fc7d93797ade0b8c978 100644
--- a/api/routes_products.py
+++ b/api/routes_products.py
@@ -504,8 +504,6 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
projected.append(item)
fields = list(fields) + projected
- # Internal wall inputs stay outside workspace, fields and all public row projections.
- permission_scope = {"fields": fields, "rows": rows_src, "row_fields": fields_base}
hidden = perm_scope.hidden_keys(session.user, MODULE, fields, st=session.runtime)
if hidden:
fields = [f for f in fields if f.get("key") not in hidden]
@@ -577,7 +575,6 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
for field in fields]
return {"rows_src": rows_src, "pids": pids, "ws": ws, "workspace": workspace,
"fields": fields, "views": views, "lists": lists,
- "_permission_scope": permission_scope,
"derived": derived,
"measures": measures, "measure_sets": measure_sets, "today": today,
"team_id": team_id}
@@ -597,9 +594,7 @@ def products(session: Session = Depends(module_gate(MODULE)), related: str = Non
import modules.product_data as pd
g = product_assembly(session, consume_corrections=not bool(related))
- rows = aios_grid.rows_from_pool(
- g["rows_src"], g["fields"], g["ws"].get("overlays"), derived=g["derived"])
- rows = _seed_image(_seed_shared(rows, g["rows_src"], g["fields"]), g["fields"])
+ rows = product_rows(g)
from core import user_tables as _zones
rows = _zones.zone_cells("product_data", rows, allowed_row_ids=g["pids"],
st=session.runtime)
@@ -706,6 +701,14 @@ def patch_product(pid: int, body: dict = Body(default=None),
PRODUCT_IMAGE_KEY = "image"
+def product_rows(assembly):
+ """The grid and Assistant share the same permissioned overlay/default projection."""
+ import aios_grid
+ rows = aios_grid.rows_from_pool(assembly["rows_src"], assembly["fields"],
+ assembly["ws"].get("overlays"), derived=assembly["derived"])
+ return _seed_image(_seed_shared(rows, assembly["rows_src"], assembly["fields"]), assembly["fields"])
+
+
def _seed_shared(rows, rows_src, fields):
"""W30-T36 — the supplier master as a per-render DEFAULT for the four SHARED columns.
diff --git a/api/routes_query.py b/api/routes_query.py
index ab7a54e3a74f09f934a79e951a34f8a6b9c4f084..e51194212ae8a72e9410c5b4d937d3bf76792a80 100644
--- a/api/routes_query.py
+++ b/api/routes_query.py
@@ -10,9 +10,11 @@ import csv
import datetime as _dt
import base64
import hashlib
+import functools
import hmac
import io
import json
+import logging
import os
import re
import dash_norm
@@ -28,7 +30,36 @@ import turn_audit
import provider_limits
import provider_stream
-from fastapi import APIRouter, Body, Depends, Response
+from fastapi import APIRouter, Body, Depends, HTTPException, Response
+from fastapi.exceptions import RequestValidationError
+from fastapi.routing import APIRoute
+from starlette.exceptions import HTTPException as StarletteHTTPException
+from starlette.responses import StreamingResponse
+
+
+class _C2Route(APIRoute):
+ """Cover dependency and request validation refusals before the endpoint runs."""
+
+ def get_route_handler(self):
+ handler = super().get_route_handler()
+ if self.path not in {"/api/v1/query/tool", "/api/v1/query/chat", "/api/v1/query/chat/stream"}:
+ return handler
+
+ async def door(request):
+ route = self.path.removeprefix("/api/v1")
+ try:
+ return await handler(request)
+ except StarletteHTTPException as exc:
+ raise _c2_http(exc, route, None) from None
+ except RequestValidationError:
+ raise _c2_http(err(422, "bad_request", "request validation failed"), route, None) from None
+ except Exception as exc:
+ from core import grid_events
+ cause = "store_unavailable" if isinstance(exc, grid_events.StoreUnavailable) else "stream_failed"
+ raise _c2_http(err(503 if cause == "store_unavailable" else 500, cause,
+ _RefusalDetail(type(exc).__name__)), route, None) from None
+
+ return door
from deps import (Session, assistant_read_scope, assistant_source_status, err,
module_gate, require_session)
@@ -62,7 +93,7 @@ from deps import (Session, assistant_read_scope, assistant_source_status, err,
#: `analyst` grant. One entry, and adding a second is a decision somebody has to write down here.
SESSION_ONLY_PATHS = ("/api/v1/query/formula-catalogue",)
-_analyst = APIRouter(prefix="/api/v1", dependencies=[Depends(module_gate("analyst"))])
+_analyst = APIRouter(prefix="/api/v1", dependencies=[Depends(module_gate("analyst"))], route_class=_C2Route)
_session_only = APIRouter(prefix="/api/v1")
#: ⚠ REBOUND AT THE BOTTOM OF THIS FILE to the ungated parent that `main.py` mounts. Until then it
#: is the gated router, which is what keeps every `@router.` decorator below a gated door.
@@ -97,6 +128,121 @@ QUERY_DRAFT_ADMIN = "This database has no approved fields yet. Pick the ones thi
QUERY_DRAFT_MEMBER = "This database has no approved fields yet. Pick the ones you need and your administrators will be asked to approve them."
QUERY_DRAFT_SENT = "Sent to your administrators. Ask again once one of them approves."
+_LOG = logging.getLogger(__name__)
+#: C2: the refusal codes a client renders, each with its one sentence. Add a code only by a dated PRD amendment.
+C2_MESSAGES = {
+ "assistant_forbidden": "You do not have access to that database.",
+ "query_source_unavailable": "That source is still syncing. Try again in a few minutes.",
+ "source_needs_filter": "That question needs every row at once. Add a filter or ask for a total.",
+ "provider_unreachable": "The model did not answer. Try again in a moment.",
+ "provider_limited": "The model is busy. Your answer resumes shortly.",
+ "store_unavailable": "Loopable could not reach its store. Try again in a moment.",
+ "question_too_long": "That question is too long. Shorten it and send it again.",
+ "semantic_field_unapproved": "That field is not approved for answers yet. Ask an Administrator.",
+ "session_expired": "Your session ended. Sign in again.",
+}
+C2_GENERIC = "This database could not answer right now. Please try again."
+#: Internal refusal codes that answer as a C2 code. Any other code keeps its own name.
+_C2_ALIASES = {
+ "assistant_snapshot_unavailable": "query_source_unavailable",
+ "assistant_store_not_ready": "query_source_unavailable",
+ "assistant_unknown_database": "assistant_forbidden",
+ "forbidden": "assistant_forbidden",
+ "shared_channel_unavailable": "assistant_forbidden",
+ "invalid_session": "session_expired",
+ "no_session": "session_expired",
+ "shared_channel_semantics": "semantic_field_unapproved",
+ "not_configured": "provider_unreachable",
+ "no_credit": "provider_unreachable",
+ "no_provider": "provider_unreachable",
+ "model_unavailable": "provider_unreachable",
+ "provider_stream_error": "provider_unreachable",
+}
+
+
+class _RefusalDetail(str):
+ """Diagnostics composed from provider status or exception type, never response text."""
+
+
+_LOG_CAUSES = set(C2_MESSAGES) | set(_C2_ALIASES) | {
+ "model_refused", "no_spec", "unknown_columns",
+ "assistant_source_too_large", "query_no_source_matched", "bad_request", "unknown_model",
+ "turn_join_scope", "query_limit", "tool_arguments_invalid", "bad_formula", "bad_resume_token",
+ "unsupported_kind", "no_columns", "unknown_filter", "bad_filter", "bad_query_artifact",
+ "stream_failed", "stream_replaced", "turn_stopped",
+ "query_resume_refused", "filter_dropped", "rhs_dropped", "values_missing", "bad_aggregation",
+ "missing_ref", "wrong_ref_type", "display_dropped", "assistant_bad_filter", "assistant_bad_fields",
+ "assistant_unknown_field",
+}
+
+
+def c2_code(cause, detail=""):
+ """The C2 code a refusal answers with. An unmapped code stays itself."""
+ cause = str(cause or "")
+ if cause == "assistant_source_too_large":
+ # An evicted stored table is unavailable. The mirror row cap needs a narrower question.
+ return "query_source_unavailable" if "is not stored" in str(detail or "") else "source_needs_filter"
+ return _C2_ALIASES.get(cause, cause)
+
+
+def c2_message(code):
+ """The one sentence a C2 code carries. Any other code carries the generic sentence."""
+ return C2_MESSAGES.get(code, C2_GENERIC)
+
+
+def _log_refusal(route, code, cause, detail, session):
+ """One line per refusal: the C2 code and the real cause, never a key, URL, token or record value."""
+ tenant = str(getattr(session, "tenant", "") or "")
+ user = hashlib.sha256(f"{tenant}:{getattr(session, 'uname', '')}".encode("utf-8")).hexdigest()[:12]
+ # Redaction cannot prove arbitrary exception/model text is free of secrets or record values.
+ # Only diagnostics constructed at the transport boundary enter this line.
+ detail = str(detail) if isinstance(detail, _RefusalDetail) else ""
+ cause = cause if cause in _LOG_CAUSES else "unclassified"
+ logged_code = code if code in _LOG_CAUSES else "unclassified"
+ tenant = hashlib.sha256(tenant.encode("utf-8")).hexdigest()[:12]
+ _LOG.warning("assistant refusal route=%s code=%s cause=%s detail=%s tenant=%s user=%s",
+ route, logged_code, cause, json.dumps(detail, ensure_ascii=False), tenant, user)
+
+
+def _refusal(route, cause, detail, session):
+ """The C2 fields of a 200 refusal, logged once."""
+ code = c2_code(cause, detail)
+ _log_refusal(route, code, cause, detail, session)
+ return {"code": code, "message": c2_message(code), "cause": cause}
+
+
+def _c2_http(exc, route, session):
+ """The same HTTP refusal under its C2 code and sentence, with the original code as `cause`."""
+ detail = getattr(exc, "detail", None)
+ error = detail.get("error") if isinstance(detail, dict) else None
+ if getattr(exc, "_c2_normalized", False):
+ return exc
+ error = error if isinstance(error, dict) else {}
+ cause = error.get("cause") or error.get("code") or {
+ 401: "session_expired", 403: "assistant_forbidden"}.get(exc.status_code, "bad_request")
+ shaped = _refusal(route, str(cause), error.get("message", detail), session)
+ normalized = HTTPException(status_code=exc.status_code, detail={"error": shaped},
+ headers=getattr(exc, "headers", None))
+ normalized._c2_normalized = True
+ return normalized
+
+
+def _c2_refusals(route):
+ """Raise every refusal of the wrapped door under its C2 code and sentence."""
+ def wrap(fn):
+ @functools.wraps(fn)
+ def door(*args, **kwargs):
+ from core import grid_events
+ session = kwargs.get("session", args[1] if len(args) > 1 else None)
+ try:
+ return fn(*args, **kwargs)
+ except StarletteHTTPException as exc:
+ raise _c2_http(exc, route, session)
+ except grid_events.StoreUnavailable:
+ raise _c2_http(err(503, "store_unavailable", _RefusalDetail("StoreUnavailable")), route, session) from None
+ return door
+ return wrap
+
def _draft_approved_line(name, date):
return f"Approved by {_no_dashes(name)} on {str(date)[:10]}."
@@ -257,7 +403,15 @@ def _new_id(prefix):
def model_choices():
"""Choices are stable even when one is not configured, so explicit means explicit."""
- return [MODEL_AUTO, *(p.name for p in prov.LLM_PROVIDERS.values())]
+ return [MODEL_AUTO, *prov.LLM_DEFAULT_ORDER]
+
+
+def _resolve_model(model):
+ """A retired provider name resolves to `auto` (R112), and any other string stays as sent."""
+ requested = str(model or MODEL_AUTO).strip().lower()
+ if requested in prov.LLM_PROVIDERS and requested not in model_choices():
+ return MODEL_AUTO
+ return requested
def _ladder_drift():
@@ -338,17 +492,13 @@ def model_status():
def _providers(model=MODEL_AUTO):
- """Filter the available ladder by kind approval, preserving explicit provider choices."""
- requested = str(model or MODEL_AUTO).strip().lower()
+ """The callable ladder for this turn, narrowed to one provider when one was chosen."""
+ requested = _resolve_model(model)
chain = prov.llm_chain("llm_tool_calling")
if requested != MODEL_AUTO:
chain = [p for p in chain if p.name == requested]
- else:
- order = model_router.provider_order((_AGENT_TURN.get() or {}).get("turnKind", "other"),
- model_router.load_receipt())
- chain = [p for name in order for p in chain if p.name == name]
return [{"name": p.name, "label": p.label, "env": p.env, "url": p.url,
- "model": p.model, "wire": p.wire} for p in chain]
+ "model": p.current_model(), "wire": p.wire} for p in chain]
def _model_identity(provider):
@@ -448,6 +598,7 @@ def _spec_schema(field_keys):
"filters": {"type": "array", "items": {"type": "object", "properties": {
"colId": col, "op": {"type": "string", "enum": sorted(_grid().FILTER_OPS)},
"value": {"type": "string"},
+ "value2": {"type": "string"},
"values": {"type": "array", "items": {"type": "string"}},
"rhs": {"type": "object", "properties": {
"kind": {"type": "string", "enum": ["field"]}, "colId": col,
@@ -462,7 +613,7 @@ def _spec_schema(field_keys):
}, "required": ["colId", "dir"]}},
"groupBy": col,
"aggregation": {"type": "object", "properties": {
- "op": {"type": "string", "enum": ["count", "sum", "avg", "min", "max"]},
+ "op": {"type": "string", "enum": ["count", "count_distinct", "sum", "avg", "min", "max"]},
"field": col,
}, "required": ["op"]},
"stackField": col,
@@ -570,6 +721,23 @@ carries what. Every number you state comes from build_view over the snapshot abo
def _system_prompt(snapshot):
fields = snapshot["fields"]
+ today = _dt.datetime.fromisoformat(_now_iso()).date()
+ last_monday = today - _dt.timedelta(days=today.weekday() + 7)
+ scope = ""
+ try:
+ from harness import semantic as sem
+ topic = next((row for row in sem.topics().values()
+ if row.get("grid") == snapshot["database"]), {})
+ except Exception:
+ topic = {}
+ for text in (topic.get("scope"), (topic.get("semantic") or {}).get("scope")):
+ if isinstance(text, str) and text.strip():
+ scope += "\nCURATED TOPIC SCOPE: " + _no_dashes(text.strip())
+ schema_only = snapshot.get("query_schema_only") is True
+ population = "Unknown. No rows were read for planning." if schema_only else len(snapshot["records"])
+ planning = ("This is a schema-only Query plan. Call build_view for totals and groups too. "
+ "The server executes its validated aggregation over all permitted matching rows. "
+ "Do not infer values or a zero count from the empty planning records.") if schema_only else ""
cols = json.dumps([{"key": field["key"], "label": field.get("label", field["key"]),
"type": field.get("type", "text")} for field in fields], separators=(",", ":"))
return f"""You are the assistant inside this product, talking with one person about exactly one
@@ -577,9 +745,12 @@ database they already have permission to read. Reply in plain prose, and keep it
DATABASE: {snapshot['database']}
SNAPSHOT VERSION: {json.dumps(snapshot['source_version'], default=str)}
-PERMISSION-FILTERED RECORD COUNT: {len(snapshot['records'])}
+PERMISSION-FILTERED RECORD COUNT: {population}
FIELDS: {cols}
VIEW KINDS: {", ".join(QUERY_KINDS)}
+CURRENT DATE (UTC): {today.isoformat()}
+Last week means {last_monday.isoformat()} through {(last_monday + _dt.timedelta(days=6)).isoformat()}, inclusive, Monday to Sunday.
+Preserve the source's date and timezone semantics. Use explicit ISO dates for relative periods.{scope}
You may answer in words alone, and you may ask ONE short question back when the request is
ambiguous: which field is meant, which period, whether they want every record or a narrower set.
@@ -591,9 +762,11 @@ not call it to explain something, to confirm something, or to ask your question.
it you may also write one sentence saying what you built.
Inside build_view: choose visible fields, supported filters and an optional aggregation. Use count
-for record counts; sum, avg, min and max require one numeric field. The server computes and cites
+for record counts and count_distinct for distinct values. Sum, avg, min and max require one numeric field. The server computes and cites
every number from this exact snapshot. Never write SQL, invent fields, or name another database.
Return kind=refused with one plain sentence if the database cannot answer.
+For between, set value to the first bound and value2 to the second bound. Both are required.
+{planning}
To compare one column against ANOTHER column rather than a typed value, give the filter an rhs of
{{"kind":"field","colId":""}} and omit value. That is how you express questions like
@@ -796,7 +969,7 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
signature change. An omitted session is COUNTED in ``usage_ledger.UNATTRIBUTED`` and reported
to an admin, never dropped.
"""
- requested = str(model or MODEL_AUTO).strip().lower()
+ requested = _resolve_model(model)
if requested not in model_choices():
return None, f"the selected model ({requested or model}) is unavailable", None, "model_unavailable"
import agent_runtime
@@ -811,12 +984,21 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
tools.extend(agent_runtime.tool_specs(session, snapshot=snapshot))
if turn.get("openWork"):
tools = [tool for tool in tools if tool["function"]["name"] == "open_items"]
+ if turn.get("admittedTools"):
+ tools = [tool for tool in tools if tool["function"]["name"] in set(turn["admittedTools"])]
if turn.get("memoryOnly"):
tools = [tool for tool in tools if tool["function"]["name"] in {"remember", "recall_memory"}]
+ if turn.get("toolShareRequests"):
+ tools = [tool for tool in tools if tool["function"]["name"] == "tool_share_decide"]
prompt = (_system_prompt(snapshot) if snapshot is not None else
"You are the Loopable Assistant. Use tools for facts. Writes run at once. Deletes need the user's yes.")
if turn.get("context"):
prompt += "\n\n" + turn["context"]
+ if turn.get("toolShareRequests"):
+ prompt += ("\nThis turn concerns a pending tool-share approval only. Use the prior conversation to identify "
+ "the request. Ask which request when the user's approval is ambiguous. "
+ "No other write is authorized. The user already said yes to these requests: "
+ + json.dumps(turn["toolShareApproved"]) + ".")
if turn.get("channel") and not turn.get("memoryOnly"):
prompt += "\nThis is a shared channel. Only build_view over this snapshot is available."
if session is not None:
@@ -830,7 +1012,7 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
prompt += "\n\n" + memory
messages = [{"role": "system", "content": _no_dashes(prompt)},
*(history or []),
- {"role": "user", "content": question}]
+ {"role": "user", "content": agent_runtime.user_content(question)}]
turn["intentTexts"] = [question]
chosen = None
offered = {tool["function"]["name"] for tool in tools}
@@ -923,7 +1105,12 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
result = {"ok": False, "error": "New instructions arrived. Reconsider this tool before executing it."}
elif name not in offered or session is None:
result = {"ok": False, "error": "That tool is not available for this conversation."}
- elif name == "open_items":
+ elif turn.get("toolShareRequests") and (
+ name != "tool_share_decide" or not isinstance(args, dict) or args.get("decision") != "yes"
+ or args.get("request") not in turn["toolShareApproved"]
+ or len(turn.get("intentTexts") or []) != 1):
+ result = {"ok": False, "error": "Ask which pending tool-share request the user approves."}
+ elif name == "open_items" and _AGENT_DOOR.get() != "whatsapp":
import assistant_open_items
if turn.get("handle") is not None:
with turn["handle"].execution() as allowed:
@@ -940,6 +1127,13 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
reconsider = True
else:
result = agent_runtime.execute(session, name, args, door=_AGENT_DOOR.get(), turn=turn)
+ if (name == "remember" and isinstance(result, dict) and result.get("scope") == "company"
+ and result.get("ok") is not False and result.get("id")):
+ # The committed scope, rather than the model's requested scope, owns the acknowledgement.
+ turn["companyRemembered"] = True
+ for recorded in turn["toolCalls"]:
+ if recorded.get("name") == "remember" and recorded.get("ref") == result["id"]:
+ recorded.pop("linkNote", None)
if isinstance(result, dict) and result.get("stopped"):
return None, None, provider, "stopped"
content = json.dumps(result, default=str, ensure_ascii=False)
@@ -959,6 +1153,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
after_attempt=None, input_token_bound=None, output_token_bound=None):
"""The provider ladder runs before the first response; subsequent steps pin that provider."""
+ requested = _resolve_model(requested)
priced = before_attempt is not None or after_attempt is not None
if priced:
from core import login_run
@@ -977,23 +1172,9 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
if chosen:
providers = [provider for provider in providers if provider["name"] == chosen]
if not providers:
- # ⛔ THREE DIFFERENT EMPTINESSES, THREE DIFFERENT SENTENCES (R4). "Not configured" and
- # "every account is out of credit" are the same empty list and completely different
- # problems: one needs an administrator, the other needs a card. Answering both with one
- # sentence is how the owner ended up reading `HTTP 402` to find out which.
- broke = [row for row in prov.llm_status() if row["outOfCredit"]]
- if requested != MODEL_AUTO:
- row = next((r for r in prov.llm_status() if r["provider"] == requested), None)
- if row and row["outOfCredit"]:
- sentence = f"{row['label']} is out of credit, so it cannot answer right now"
- else:
- sentence = f"the selected model ({requested}) is unavailable"
- return None, sentence, None, "model_unavailable"
- if broke:
- names = ", ".join(row["label"] for row in broke)
- return (None, f"every model this deployment can reach is out of credit ({names}). "
- f"Top one up and it will answer again", None, "no_credit")
- return None, "the assistant is not configured on this deployment", None, "not_configured"
+ # No key or an out-of-credit cooldown is the C2 code `provider_unreachable` (R116).
+ broke = [row["label"] for row in prov.llm_status() if row["outOfCredit"]]
+ return None, _RefusalDetail("OpenRouter out of credit" if broke else "OpenRouter key unavailable"), None, "provider_unreachable"
import requests
@@ -1029,7 +1210,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
def pause():
if not turn.get("providerPaused"):
turn["providerPaused"] = True
- provider_stream.emit("paused", {"message": provider_limits.PAUSED_MESSAGE})
+ provider_stream.emit("paused", {"code": "provider_limited", "message": provider_limits.PAUSED_MESSAGE})
if turn.get("handle") is not None and session is not None:
turn_audit.write(turn["handle"], session.runtime, result={"status": "paused"})
@@ -1111,11 +1292,11 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
continue
except provider_limits.RetryExhausted:
turn["providerLimitExhausted"] = True
- return None, provider_limits.PAUSED_MESSAGE, provider["name"], "provider_limited"
+ return None, _RefusalDetail("HTTP 429 retry budget exhausted"), provider["name"], "provider_limited"
except Exception as exc: # noqa: BLE001
if priced:
raise
- trouble.append(f"{provider['label']} could not be reached ({type(exc).__name__})")
+ trouble.append(f"provider transport {type(exc).__name__}")
continue
if response.status_code == 400 and provider["wire"] == "openai":
@@ -1133,8 +1314,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
# it instead of paying the round trip again.
if prov.is_credit_failure(response.status_code, response.text):
prov.mark_no_credit(provider["name"])
- trouble.append(prov.refusal_sentence(provider["name"], response.status_code,
- response.text))
+ trouble.append(f"provider HTTP {int(response.status_code)}")
continue
try:
@@ -1146,7 +1326,7 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
_book(provider, body)
spec, said, refused = read(body)
if refused:
- trouble.append(f"{provider['label']}: {refused}")
+ trouble.append("provider refused its response")
continue
if spec is not None:
# The prose rides ALONG with the view when the model wrote both, so the reader gets
@@ -1154,21 +1334,21 @@ def _request_model(messages, tools, requested, session, chosen=None, *, before_a
return spec, said, provider["name"], None
if said:
return None, said, provider["name"], None
+ if turn.get("memoryReply"):
+ # A committed tool's server reply completes an otherwise empty model response.
+ return None, None, provider["name"], None
# ⚠ Neither a call nor a word is a FAILED turn, not a silent one: falling through to
# the next provider is right, and swallowing it as an empty answer would show the
# reader a blank reply [[empty-answer-vs-unfinished-answer]].
- trouble.append(f"{provider['label']} answered with nothing")
+ trouble.append("provider answered with nothing")
except provider_stream.StreamFailure as exc:
_book(provider, exc.body)
- return None, exc.reply, provider["name"], "provider_stream_error"
+ return None, _RefusalDetail("provider stream interrupted"), provider["name"], "provider_stream_error"
except Exception as exc: # noqa: BLE001
- trouble.append(f"{provider['label']} sent something unreadable "
- f"({type(exc).__name__})")
+ trouble.append(f"provider response unreadable {type(exc).__name__}")
if requested != MODEL_AUTO:
- return (None, f"the selected model ({requested}) could not answer: "
- + (trouble[0] if trouble else "it did not respond"), None, "model_unavailable")
- return (None, "the assistant could not be reached just now: "
- + ("; ".join(trouble) if trouble else "no provider answered"),
+ return (None, _RefusalDetail("; ".join(trouble) or "provider did not respond"), None, "model_unavailable")
+ return (None, _RefusalDetail("; ".join(trouble) or "provider did not respond"),
None, "provider_unreachable")
@@ -1185,10 +1365,10 @@ def _validate(spec, fields):
if kind in QUERY_EXCLUDED or kind not in QUERY_KINDS:
return None, "that kind of view cannot be built from this question", "unsupported_kind"
- named = set(spec.get("visible") or ())
+ named = dict.fromkeys(str(key) for key in (spec.get("visible") or ()))
for item in spec.get("filters") or ():
if isinstance(item, dict) and item.get("colId"):
- named.add(str(item["colId"]))
+ named[str(item["colId"])] = None
# ⛔ THE RIGHT-HAND COLUMN IS A COLUMN AND MUST FACE THE SAME `missing` CHECK. Collecting
# only the left side is what makes D-229 possible one layer down: `clean_filter_tree` does
# NOT drop a leaf whose field-rhs names a column that does not exist — it keeps the leaf,
@@ -1198,21 +1378,25 @@ def _validate(spec, fields):
# Naming it here turns that into the ordinary "this database does not have: X" refusal.
rhs = item.get("rhs") if isinstance(item, dict) else None
if isinstance(rhs, dict) and rhs.get("colId"):
- named.add(str(rhs["colId"]))
+ named[str(rhs["colId"])] = None
for item in spec.get("sorts") or ():
if isinstance(item, dict) and item.get("colId"):
- named.add(str(item["colId"]))
+ named[str(item["colId"])] = None
for key in ("groupBy", "stackField", "dateField", "colorField", "sizeField"):
if spec.get(key):
- named.add(str(spec[key]))
+ named[str(spec[key])] = None
raw_aggregation = spec.get("aggregation") or {"op": "count"}
if isinstance(raw_aggregation, dict) and raw_aggregation.get("field"):
- named.add(str(raw_aggregation["field"]))
- missing = sorted(named - keys)
+ named[str(raw_aggregation["field"])] = None
+ missing = sorted(set(named) - keys)
if missing:
return None, "this database does not have: " + ", ".join(missing), "unknown_columns"
visible = [str(key) for key in (spec.get("visible") or ()) if str(key) in keys][:MAX_VISIBLE]
+ # An empty `visible` shows the fields the spec names, else the snapshot's first fields.
+ if not visible:
+ visible = ([key for key in named if key in keys][:MAX_VISIBLE]
+ or [str(field.get("key")) for field in fields if field.get("key")][:MAX_VISIBLE])
if not visible:
return None, "that question did not name any fields to show", "no_columns"
raw_filters = [item for item in (spec.get("filters") or ()) if isinstance(item, dict)]
@@ -1229,6 +1413,12 @@ def _validate(spec, fields):
# `_clean_rhs` rule). Both doors, because the two catch different causes and the cost of
# missing this one is a wrong answer that looks right.
for sent, kept in zip(raw_filters, filters):
+ if sent.get("op") == "between":
+ from harness import filter_eval, filter_sql
+ if (by_key.get(kept.get("colId")) not in filter_eval.NUMERIC_TYPES | filter_eval.DATE_TYPES
+ or sent.get("rhs") is not None
+ or not filter_sql.is_rule_active(kept, keys)):
+ return None, "that range filter needs two bounds on a numeric or date field", "range_invalid"
if sent.get("rhs") and not kept.get("rhs"):
return None, "that column cannot be compared against another column", "rhs_dropped"
# D-658: an empty multi-value leaf survives cleaning but narrows no records.
@@ -1239,11 +1429,12 @@ def _validate(spec, fields):
aggregation = raw_aggregation if isinstance(raw_aggregation, dict) else {}
op = str(aggregation.get("op") or "").lower()
field = aggregation.get("field")
- if op not in {"count", "sum", "avg", "min", "max"}:
+ if op not in {"count", "count_distinct", "sum", "avg", "min", "max"}:
return None, "the assistant gave an unsupported aggregation", "bad_aggregation"
if op == "count":
field = None
- elif field not in keys or by_key.get(field) not in {"int", "currency", "pct", "formula"}:
+ elif field not in keys or (op != "count_distinct" and
+ by_key.get(field) not in {"int", "currency", "pct", "formula"}):
return None, "that aggregation needs one visible numeric field", "bad_aggregation"
display = {"mode": kind}
@@ -1320,6 +1511,12 @@ def _numeric_result(view, records):
aggregation = view["aggregation"]
if aggregation["op"] == "count":
return {"label": "Matching records", "value": len(records), "contributing_record_count": len(records)}
+ if aggregation["op"] == "count_distinct":
+ values = [row.get(aggregation["field"]) for row in records
+ if row.get(aggregation["field"]) is not None]
+ return {"label": f"Count distinct of {aggregation['field']}",
+ "value": len({json.dumps(value, sort_keys=True, default=str) for value in values}),
+ "contributing_record_count": len(values)}
values = []
for record in records:
try:
@@ -1687,14 +1884,13 @@ def _sources(body, target, session):
sources = list(dict.fromkeys(item for item in sources if item))
if target not in sources:
sources.insert(0, target)
- # Source chips are a permissioned selection, not untrusted labels remembered in a thread.
- # The model still receives ONLY `target`'s snapshot below; these calls do not pass a second
- # source to it and D's helper refuses cache misses, mirrors and unshared databases.
+ # Source chips validate metadata only. The model receives only the target's permitted data.
for source in sources:
- assistant_read_scope(session, source, fields=[], filters=None)
+ assistant_read_scope(session, source, fields=[], filters=None, mode="schema")
return sources
+@_c2_refusals("/query/chat")
def _submit(body, session, chat=None, *, also_as=(), door="app", audit_handle=None):
# C10 currently sets the door context; the explicit keyword is also the C12 consumer seam.
door = _AGENT_DOOR.get() if door == "app" else door
@@ -1717,7 +1913,7 @@ def _submit(body, session, chat=None, *, also_as=(), door="app", audit_handle=No
"toolCalls": [], "pendingDelete": None, "artifacts": [], "view": None, "citations": []}
context_hint = assistant_dock.context_of(body, session)
dock = assistant_dock.payload_context(body["dock"]) if context_hint is not None else None
- selected_model = str(body.get("model") or MODEL_AUTO).strip().lower()
+ selected_model = _resolve_model(body.get("model"))
if not question:
raise err(400, "bad_request", "no question was asked")
if len(question) > MAX_QUESTION:
@@ -1749,17 +1945,36 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
target = (dock.get("database", "") if dock is not None else
str((replay or {}).get("database") or body.get("database") or body.get("scope") or "").strip())
+ share_requests, share_approved = [], []
+ if (dock is None and not target and replay is None and not also_as and door != "slack"
+ and re.fullmatch(r"yes(?:[,.]?\s+(?:please|share(?:\s+it)?))?[.!]*", question.casefold())):
+ import loopy_tool_store
+ share_requests = loopy_tool_store.pending_shares(session)
+ if share_requests:
+ history = _history(session)
+ previous = history[-1]["content"] if history and history[-1]["role"] == "assistant" else ""
+ if "share" in question.casefold() or re.search(r"\bshar(?:e|ing)\b", previous, re.I):
+ named = [row["request"] for row in share_requests if
+ row["request"] in previous or (row["tool"] and row["tool"] in previous)]
+ share_approved = named if len(named) == 1 else (
+ [share_requests[0]["request"]] if len(share_requests) == 1 else [])
+
import assistant_open_items
+ import agent_tools
+ import agent_runtime
+ admitted = (agent_tools.admitted_tools(question)
+ if dock is None and not target and replay is None and not also_as and door != "slack"
+ else frozenset())
open_work = (dock is None and not target and replay is None and not also_as and door != "slack"
and assistant_open_items.admits(question))
memory_only = dock is None and not target and replay is None and assistant_memory.admits(question)
- routed = _route(session, question) if dock is None and not open_work and not memory_only and not target and replay is None else {
+ routed = _route(session, question) if dock is None and not open_work and not admitted and not memory_only and not share_requests and not agent_runtime.has_attachments() and not target and replay is None else {
"database": target, "auto": False, "alternatives": []}
target = routed["database"]
- route_refusal = (None if dock is not None or open_work or memory_only else
+ route_refusal = (None if dock is not None or open_work or admitted or memory_only or share_requests or agent_runtime.has_attachments() else
QUERY_NO_SOURCE_MATCHED if not target and replay is None else routed.get("refusal"))
- # Snapshot turns read here; dock turns read through the permissioned tools.
+ # Snapshot turns plan mirrors from schema. Dock turns read through permissioned tools.
scope_reader = assistant_read_scope
scope_extra = {}
if also_as:
@@ -1770,8 +1985,11 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
scope_reader = deps.assistant_read_scope
scope_extra["also_as"] = also_as
snapshot = (scope_reader(session, target, fields=None,
- filters=(replay or {}).get("filters", body.get("filters")), **scope_extra)
+ filters=(replay or {}).get("filters", body.get("filters")),
+ mode="query_plan", **scope_extra)
if dock is None and target and not route_refusal else None)
+ if snapshot is not None and snapshot.get("source_kind") == "mirror_user_table":
+ snapshot["query_schema_only"] = True
sources = (list(dict.fromkeys(key for key in
[target, *(dock.get("databases") or []), *(body.get("sources") or [])] if key))
if dock is not None else
@@ -1794,8 +2012,13 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
"also_as": list(also_as), "door": door, "turnKind": model_router.classify_turn(question, dock),
"handle": handle, "dock": dock}
handle.audit_turn = turn
+ if share_requests:
+ turn["toolShareRequests"] = [row["request"] for row in share_requests]
+ turn["toolShareApproved"] = share_approved
if open_work:
turn["openWork"] = True
+ if admitted:
+ turn["admittedTools"] = sorted(admitted)
if memory_only:
turn["memoryOnly"] = True
turn["memoryCompanyRequested"] = assistant_memory.company_requested(question)
@@ -1832,9 +2055,36 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
_AGENT_TURN.reset(token)
if reason == "stopped":
return turn_control.envelope(handle, "stopped")
+ if spec is None and not said and not reason and not turn.get("memoryReply"):
+ said, reason = _RefusalDetail("provider answered with nothing"), "provider_unreachable"
view, refusal, refusal_code = (_validate(spec, snapshot["fields"])
if spec is not None and snapshot is not None else (None, said, reason))
+ server_numeric = None
+ if view is not None and snapshot.get("query_schema_only"):
+ requested = [field["key"] for field in snapshot["fields"]]
+ protected = {row["field"] for row in records.values()
+ if row.get("sensitivity") in {"sensitive", "restricted"}}
+ sensitive = (view["aggregation"]["field"] in protected or view.get("groupBy") in protected
+ or bool(protected and view.get("filters")))
+ if view.get("sorts") or sensitive:
+ snapshot = scope_reader(session, target, fields=requested,
+ filters=(replay or {}).get("filters", body.get("filters")), **scope_extra)
+ snapshot = _semantic_answer_snapshot(snapshot, records)
+ else:
+ rows, server_numeric, groups, matching_count, group_page, summary = _tool_server_result(
+ session, target, requested, view, body, records, scope_reader=scope_reader,
+ also_as=also_as, base_filters=snapshot.get("filters"))
+ snapshot = {**snapshot, "records": rows, "source_version": summary["source_version"],
+ "retrieved_at": summary["retrieved_at"]}
+ said = _tool_wording(question, server_numeric, matching_count, group_page["total"])
+
+ # C2: the turn answers with its C2 code. A provider failure says the C2 sentence, never the vendor list.
+ cause, cause_detail = refusal_code, refusal
+ refusal_code = c2_code(cause, refusal) if cause else cause
+ if cause and not draft_card:
+ said, refusal = None, c2_message(refusal_code)
+
# Injected callers and non-model refusals also seal their completion against joins.
if handle.stopped or handle.cancel_requested.is_set():
return turn_control.envelope(handle, "stopped")
@@ -1842,9 +2092,11 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
if handle.close() == "stopped":
return turn_control.envelope(handle, "stopped")
- if turn.get("memoryReply"):
- # The server owns the member's personal-only explanation, including the saved reply.
+ if turn.get("memoryReply") and not cause:
+ # A committed tool's server reply is also the saved reply.
said, refusal = turn["memoryReply"], turn["memoryReply"]
+ if turn.get("companyRemembered") and not cause:
+ said, refusal = "I shared this fact with everyone.", "I shared this fact with everyone."
artifact = None
citation = None
@@ -1853,7 +2105,7 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
raise err(400, "query_limit", f"you already have {len(state['views'])} Query artefacts")
view_id = _new_id("query")
citation_id = _new_id("citation")
- numeric = _numeric_result(view, _view_records(snapshot, view))
+ numeric = server_numeric if server_numeric is not None else _numeric_result(view, _view_records(snapshot, view))
citation = _citation(citation_id, snapshot, view, numeric, view_id)
if not _citation_complete(citation):
raise RuntimeError("Query refused to persist an incomplete numeric citation")
@@ -1894,7 +2146,8 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
"targetDatabase": target, "requestedModel": selected_model, "model": provider, "turnKind": turn["turnKind"],
"routedTo": routed,
**_model_identity(provider),
- "reason": refusal_code, "viewId": artifact["id"] if artifact else None,
+ "reason": refusal_code, **({"cause": cause} if cause else {}),
+ "viewId": artifact["id"] if artifact else None,
"provenance": _answer_provenance(artifact),
"citationIds": artifact["citationIds"] if artifact else [], "numeric": artifact["numeric"] if artifact else None,
"toolCalls": turn["toolCalls"], "pendingDelete": turn["pendingDelete"], "artifacts": turn["artifacts"],
@@ -1927,7 +2180,11 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
if door != "slack" and not session.runtime.available():
raise err(503, "store_unavailable", "the tenant store is unavailable; no chat was saved")
if door != "slack":
+ import agent_runtime
+ held_preview = door == "whatsapp" and not refusal_code and (agent_runtime._HELD.get() or turn["pendingDelete"])
for message in (user_message, assistant_message):
+ if held_preview and message["role"] == "assistant":
+ continue
assistant_log.append(session.runtime, session.uname, {
"role": message["role"], "door": door, "kind": "text", "text": message["content"],
"at": now, "payload": {key: value for key, value in message.items()
@@ -1935,14 +2192,21 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
if artifact:
session.runtime.update(_namespace_key(session), update, flush="async")
import agent_runtime
- agent_runtime.maybe_compact(session.runtime, session.uname, chat=chat)
+ if not held_preview:
+ agent_runtime.maybe_compact(session.runtime, session.uname, chat=chat)
thread = {"id": thread_id, "title": "Conversation", "createdAt": now, "updatedAt": now,
"sources": sources, "model": selected_model, "activeViewId": artifact["id"] if artifact else None}
- return {"thread": thread, "userMessage": _safe(user_message),
- "message": _safe(assistant_message),
- "toolCalls": _safe(turn["toolCalls"]), "pendingDelete": _safe(turn["pendingDelete"]),
- "artifacts": _safe(turn["artifacts"]),
- "view": _public_view(artifact) if artifact else None, "citations": [citation] if citation else []}
+ result = {"thread": thread, "userMessage": _safe(user_message),
+ "message": _safe(assistant_message),
+ "toolCalls": _safe(turn["toolCalls"]), "pendingDelete": _safe(turn["pendingDelete"]),
+ "artifacts": _safe(turn["artifacts"]),
+ "view": _public_view(artifact) if artifact else None, "citations": [citation] if citation else []}
+ if cause and not draft_card:
+ # `message` is the assistant turn here, so the C2 sentence rides in `error` as on an HTTP refusal.
+ refused = _refusal("/query/chat", cause, cause_detail, session)
+ result.update({"status": "refused", "code": refused["code"], "cause": cause,
+ "error": {"code": refused["code"], "message": refused["message"]}})
+ return result
@router.post("/query/chat")
@@ -1950,7 +2214,34 @@ def submit_chat(body: dict = Body(default=None), session: Session = Depends(requ
return _submit(body, session)
+async def _c2_stream_events(body, session, *, submit=None):
+ """Keep the streaming turn's recovery result while giving every error its C2 sentence."""
+ import assistant_stream
+ async for frame in assistant_stream.events(body, session, submit=submit):
+ if frame.startswith("event: error\n"):
+ data = json.loads(frame.split("\ndata: ", 1)[1])
+ result = data.get("result") or {}
+ already_refused = result.get("status") == "refused"
+ cause = result.get("cause") if already_refused else data.get("code")
+ code = result.get("code") if already_refused else c2_code(cause)
+ message = c2_message(code)
+ # _submit logs its final refusal or normalized exception in the worker thread.
+ already_logged = already_refused or data.get("message") == message
+ if not already_logged:
+ _log_refusal("/query/chat/stream", code, cause, "", session)
+ data.update(code=code, message=message)
+ frame = assistant_stream._event("error", data)
+ yield frame
+
+
+@router.post("/query/chat/stream")
+def stream_chat(body: dict = Body(default=None), session: Session = Depends(require_session)):
+ return StreamingResponse(_c2_stream_events(body, session), media_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
+
+
@router.get("/assistant/log")
+@_c2_refusals("/assistant/log")
def conversation_log(before: str = None, limit: int = 50,
session: Session = Depends(require_session)):
try:
@@ -2099,7 +2390,8 @@ def list_artifacts(cursor: str = None, limit: int = 50, session: Session = Depen
next_cursor = base64.urlsafe_b64encode(json.dumps([
assistant_log._hash(session.runtime, session.uname), last["createdAt"], last["id"]]).encode()).decode()
return {"items": [{key: row[key] for key in (
- "id", "kind", "title", "door", "createdAt", "ref", "status", "toolCall", "actions")} for row in page],
+ "id", "kind", "title", "door", "createdAt", "ref", "status", "toolCall", "actions")} |
+ assistant_artifacts.c7(row) for row in page],
"nextCursor": next_cursor}
@@ -2117,6 +2409,26 @@ def _artifact_item(session, item_id):
return item
+@router.get("/artifacts/{id}/snapshot")
+def get_artifact_snapshot(id: str, session: Session = Depends(require_session)):
+ import artifact_snapshot
+ row = _artifact_item(session, id)
+ if row.get("kind") != "snapshot" or row.get("status") != "active":
+ raise err(404, "unknown_artifact", "That snapshot does not exist.")
+ sources = assistant_artifacts.c7(row)["sources"]
+ if sources is None:
+ raise err(403, "assistant_forbidden", "Your current permissions do not allow this snapshot.")
+ for database in sources:
+ if not _source_still_permitted(session, {"database": database}):
+ raise err(403, "assistant_forbidden", "Your current permissions do not allow this snapshot.")
+ snapshot = assistant_artifacts.read_snapshot(session.runtime, row)
+ if snapshot is None:
+ raise err(404, "unknown_artifact", "That snapshot does not exist.")
+ artifact_snapshot.require_permission(session, sources, snapshot)
+ return {"artifact": assistant_artifacts.c7(row),
+ "snapshot": {key: value for key, value in snapshot.items() if key != "_authorization"}}
+
+
def _replay_artifact(session, item, *, name=None, args=None):
import agent_runtime
call = item["toolCall"]
@@ -2825,21 +3137,70 @@ def _tool_plan(question, body, snapshot, session):
"""Use the existing governed planner only when a channel did not supply typed artifacts."""
artifact_keys = {"view", "filters", "sorts", "group", "hiddenFields", "aggregation", "kind"}
if any(key in body for key in artifact_keys):
- return _tool_spec(body, [field["key"] for field in snapshot.get("fields") or ()]), None, None
- selected_model = str(body.get("model") or MODEL_AUTO).strip().lower()
+ return _tool_spec(body, [field["key"] for field in snapshot.get("fields") or ()]), None, None, None
+ selected_model = _resolve_model(body.get("model"))
if selected_model not in model_choices():
raise err(400, "unknown_model", "that model is not available in Query")
spec, said, provider, reason = _call_model(
question, snapshot, model=selected_model, chat=None, history=None, session=session)
if spec is None:
- return None, (said or "Query could not build an answer"), provider
- return spec, said, provider
+ return None, (said or "Query could not build an answer"), provider, reason
+ return spec, said, provider, reason
+
+
+def _tool_view_filter(view):
+ """Represent an absent validated view predicate as no user filter."""
+ return ({"conj": view["filterConj"], "nodes": view["filters"]}
+ if view["filters"] else None)
+
+
+def _tool_server_result(session, database, requested, view, body, records, *,
+ scope_reader=None, also_as=(), base_filters=None):
+ """Compute connector totals and groups in SQL, then read one bounded record page."""
+ aggregation = view["aggregation"]
+ op, field = aggregation["op"], aggregation["field"]
+ specs = [{"fn": op, **({"field": field} if field else {})},
+ {"fn": "count", **({"field": field} if field else {})}]
+ filters = _tool_view_filter(view)
+ if base_filters:
+ from harness import filter_eval
+ nodes, conj = filter_eval.tree_parts(base_filters)
+ if nodes:
+ filters = ({"conj": "and", "nodes": [{"conj": conj, "children": nodes},
+ {"conj": filters["conj"], "children": filters["nodes"]}]}
+ if filters else {"conj": conj, "nodes": nodes})
+ reader = scope_reader or assistant_read_scope
+ scope_extra = {"also_as": also_as} if also_as else {}
+ mode = ("aggregate", specs)
+ group_offset, group_limit = body.get("groupOffset", 0), body.get("groupLimit", 50)
+ if (type(group_offset) is not int or group_offset < 0 or type(group_limit) is not int
+ or not 1 <= group_limit <= 500):
+ raise err(400, "bad_request", "Use a nonnegative groupOffset and a groupLimit from 1 to 500.")
+ if view.get("groupBy"):
+ mode += ({"groupBy": [{"field": view["groupBy"]}],
+ "offset": group_offset, "limit": group_limit},)
+ summary = reader(session, database, fields=requested, filters=filters, mode=mode, **scope_extra)
+
+ def numeric(values):
+ return {"label": "Matching records" if op == "count" else f"{op.replace('_', ' ').title()} of {field}",
+ "value": values[0]["value"], "contributing_record_count": values[1]["value"]}
+
+ groups = [{"value": str(group["keys"][view["groupBy"]])
+ if group["keys"][view["groupBy"]] is not None else "(blank)",
+ "numeric": numeric(group["aggregates"])} for group in summary.get("groups") or ()]
+ page = reader(session, database, fields=requested, filters=filters, mode=("page", 0, 50), **scope_extra)
+ if page["total_rows"] != summary["total_rows"]:
+ raise err(409, "query_source_unavailable", "The source changed between its summary and record page.")
+ page = _semantic_answer_snapshot(page, records)
+ return (page["records"], numeric(summary["server_aggregates"]), groups, summary["total_rows"],
+ {"offset": group_offset, "limit": group_limit, "total": summary.get("total_groups", 0)}, summary)
@router.post("/query/tool")
+@_c2_refusals("/query/tool")
def governed_query(body: dict = Body(default=None),
session: Session = Depends(require_session)):
- """Deterministic Query substrate; it never knows or calls a model/provider."""
+ """Plan a governed answer and compute its numbers through the scoped reader."""
body = body if isinstance(body, dict) else {}
database = str(body.get("database") or "").strip()
question = " ".join(str(body.get("prompt") or body.get("question") or "").split())
@@ -2854,8 +3215,11 @@ def governed_query(body: dict = Body(default=None),
_semantic_authorize(session, database, require_answerable=not routed["auto"])
route_refusal = QUERY_NO_SOURCE_MATCHED if not database else routed.get("refusal")
if route_refusal:
- return {"status": "refused", "wording": route_refusal, "speakable": route_refusal,
- "artifacts": None, "routedTo": routed, "model": _model_identity(None)}
+ refused = _refusal("/query/tool", "query_source_unavailable" if database else "query_no_source_matched",
+ route_refusal, session)
+ return {"status": "refused", "wording": refused["message"], "speakable": refused["message"],
+ "artifacts": None, "routedTo": routed, "model": _model_identity(None),
+ **refused}
records = _semantic_records(session, database)
if not routed["auto"]:
from harness import semantic as sem
@@ -2877,25 +3241,52 @@ def governed_query(body: dict = Body(default=None),
selected = [semantic_rt.require_approved(records, database, key) for key in requested]
except semantic_rt.SemanticError as exc:
raise err(403, "semantic_field_unapproved", str(exc))
- snapshot = assistant_read_scope(session, database, fields=requested, filters=None)
+ snapshot = assistant_read_scope(session, database, fields=requested, filters=None, mode="query_plan")
+ mirror_plan = snapshot.get("source_kind") == "mirror_user_table"
snapshot = _semantic_answer_snapshot(snapshot, records)
+ if mirror_plan:
+ snapshot["query_schema_only"] = True
snapshot, formulas = _tool_formula_snapshot(body, snapshot, requested)
- spec, planned_wording, provider = _tool_plan(question, body, snapshot, session)
+ spec, planned_wording, provider, reason = _tool_plan(question, body, snapshot, session)
if spec is None:
- return {"status": "refused", "wording": planned_wording,
- "speakable": planned_wording, "artifacts": None,
- "model": _model_identity(provider), "routedTo": routed}
+ refused = _refusal("/query/tool", reason or "no_spec", planned_wording, session)
+ # A provider failure says the C2 sentence, never the vendor list.
+ wording = refused["message"]
+ return {"status": "refused", "wording": wording,
+ "speakable": wording, "artifacts": None,
+ "model": _model_identity(provider), "routedTo": routed, **refused}
view, refusal, refusal_code = _validate(spec, snapshot.get("fields") or selected)
if view is None:
raise err(400, refusal_code or "bad_query_artifact", refusal or "that Query is invalid")
- filtered = _view_records(snapshot, view)
- ordered = _tool_sort(filtered, view.get("sorts"))
- rows = ordered[:50]
+ # Formula evaluation and Python sorting require a complete filtered row set.
+ # Keep the eager reader's memory refusal for those plans, never fold a partial page.
+ protected = {row["field"] for row in selected if row.get("sensitivity") in {"sensitive", "restricted"}}
+ sensitive = (view["aggregation"]["field"] in protected or view.get("groupBy") in protected
+ or bool(protected and view.get("filters")))
+ server = mirror_plan and not formulas and not view.get("sorts") and not sensitive
+ group_page = None
+ if server:
+ rows, numeric, groups, matching_count, group_page, _summary = _tool_server_result(
+ session, database, requested, view, body, records)
+ else:
+ if mirror_plan:
+ formula_filter = any(item.get("colId") in formulas or
+ (item.get("rhs") or {}).get("colId") in formulas
+ for item in view["filters"])
+ snapshot = assistant_read_scope(session, database, fields=requested,
+ filters=None if sensitive or formula_filter else
+ _tool_view_filter(view))
+ snapshot = _semantic_answer_snapshot(snapshot, records)
+ snapshot, formulas = _tool_formula_snapshot(body, snapshot, requested)
+ filtered = _view_records(snapshot, view)
+ ordered = _tool_sort(filtered, view.get("sorts"))
+ rows = ordered[:50]
+ groups = _tool_groups(ordered, view)
+ numeric = _numeric_result(view, ordered)
+ matching_count = len(ordered)
row_ids = [str(row.get("pid") or row.get("id") or index)
for index, row in enumerate(rows)]
hidden = [key for key in requested if key not in set(view.get("visible") or ())]
- groups = _tool_groups(ordered, view)
- numeric = _numeric_result(view, ordered)
artifacts = {"filters": _safe(view.get("filters") or []),
"sorts": _safe(view.get("sorts") or []),
"group": _safe(view.get("groupBy")),
@@ -2903,11 +3294,13 @@ def governed_query(body: dict = Body(default=None),
"formulas": _safe(formulas),
"source": {"database": database, "fields": requested,
"permissionScopeApplied": True}}
- wording = _tool_wording(question, numeric, len(ordered), len(groups))
+ wording = _tool_wording(question, numeric, matching_count,
+ group_page["total"] if group_page else len(groups))
return {"status": "answered", "wording": wording, "speakable": wording,
"citations": [{"database": database, "rowId": value} for value in row_ids],
"rows": [{key: row.get(key) for key in view["visible"]} for row in rows],
"groups": groups, "numeric": numeric,
+ **({"total_rows": matching_count, "groupPage": group_page} if server else {}),
"artifacts": artifacts, "semanticRouter": semantic_rt.router_projection(records, database),
"model": _model_identity(provider), "routedTo": routed}
@@ -3364,7 +3757,11 @@ router.routes.extend(_session_only.routes)
router.routes.extend(_analyst_routes.routes)
from assistant_routers import ROUTERS as _ASSISTANT_ROUTERS # noqa: E402
+from assistant_stream import router as _stream_router # noqa: E402
for _assistant_router in _ASSISTANT_ROUTERS:
+ if _assistant_router is _stream_router:
+ # The C2 route above retains this extension's event worker and dependency walls.
+ continue
_start = len(router.routes)
router.include_router(_assistant_router)
# FastAPI 0.139 adds lazy wrappers; existing route audits need the actual gated routes.
diff --git a/api/routes_shared_artifact.py b/api/routes_shared_artifact.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1f6d175275fbb5a18cc994c2c1a4cf16c5d6a42
--- /dev/null
+++ b/api/routes_shared_artifact.py
@@ -0,0 +1,299 @@
+"""Serve one frozen artifact through a signed capability without creating a session."""
+from __future__ import annotations
+
+import base64
+import re
+import time
+from collections import OrderedDict
+from datetime import datetime, timezone
+from functools import lru_cache
+from hashlib import sha256
+from html import escape
+from pathlib import Path
+from threading import Lock
+from urllib.parse import quote
+
+from fastapi import APIRouter, Request
+from fastapi.responses import HTMLResponse, RedirectResponse, Response
+from starlette.concurrency import run_in_threadpool
+
+import artifact_share
+import assistant_artifacts
+import assistant_files
+import loopy_links
+
+router = APIRouter()
+MAX_BODY_BYTES = 1024
+RATE_WINDOW_S = 60
+MAX_RATE_KEYS = 4096
+GET_LIMIT = 60
+POST_LIMIT = 5
+FAILURE_LIMIT = 30
+MAX_FILE_BYTES = 20 * 1024 * 1024
+_HITS = OrderedDict()
+_LOCK = Lock()
+FILE_TYPES = {"application/pdf": ".pdf",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
+ "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
+HEADERS = {"Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
+ "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY",
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; "
+ "font-src data:; img-src data:; form-action 'self'; "
+ "base-uri 'none'; frame-ancestors 'none'"}
+
+CSS = """
+:root { --lp-font: Inter, sans-serif; --lp-root: 17px; --lp-fs-sm: .875rem;
+--lp-fs-lg: 1.25rem; --lp-canvas: #f7f7f6; --lp-panel: #fff; --lp-surface: #fff;
+--lp-ink: #252525; --lp-muted: #686868; --lp-line: #e6e6e4; --lp-primary: #5433cc;
+--lp-primary-hover: #472bad; --lp-blue-deep: #2563a6; --lp-r-panel: 18px;
+--lp-scroll-thumb: #bfbfbf; --lp-scroll-thumb-hover: #a8a8a8;
+--lp-r-md: 8px; --lp-panel-shadow: 0 2px 12px #0000000a; }
+* { box-sizing: border-box; }
+html { font-size: var(--lp-root); font-family: var(--lp-font); color: var(--lp-ink);
+background: var(--lp-canvas); }
+body { margin: 0; padding: 24px 16px; }
+main { width: 100%; max-width: 720px; margin: 0 auto; padding: 24px;
+background: var(--lp-panel); border-radius: var(--lp-r-panel); box-shadow: var(--lp-panel-shadow); }
+h1 { margin: 0 0 8px; font-size: var(--lp-fs-lg); font-weight: 600; overflow-wrap: anywhere; }
+p, time { font-size: var(--lp-fs-sm); line-height: 1.5; }
+time, .note { color: var(--lp-muted); }
+.table-scroll { overflow-x: auto; margin: 24px 0 16px; scrollbar-width: thin;
+scrollbar-color: var(--lp-scroll-thumb) transparent; }
+.table-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
+.table-scroll::-webkit-scrollbar-track { background: transparent; }
+.table-scroll::-webkit-scrollbar-thumb { background: var(--lp-scroll-thumb); border: 1px solid transparent;
+background-clip: padding-box; border-radius: var(--lp-r-md); }
+@media (hover: hover) and (pointer: fine) {
+.table-scroll::-webkit-scrollbar-thumb:hover { background-color: var(--lp-scroll-thumb-hover); } }
+table { border-collapse: collapse; width: 100%; font-size: var(--lp-fs-sm); }
+th, td { padding: 12px 8px; border-bottom: 1px solid var(--lp-line); text-align: left;
+vertical-align: top; overflow-wrap: anywhere; }
+th { font-weight: 600; white-space: nowrap; overflow-wrap: normal; }
+.number, .totals { text-align: right; font-variant-numeric: tabular-nums; }
+.number { white-space: pre; overflow-wrap: normal; }
+.totals { margin: 16px 0; font-size: var(--lp-fs-sm); }
+img { display: block; max-width: 100%; height: auto; margin: 24px 0; }
+a { color: var(--lp-blue-deep); font-size: var(--lp-fs-sm); }
+.open { display: block; margin-top: 24px; }
+button { border: 0; background: transparent; font: inherit; color: inherit; cursor: pointer; }
+.primary { display: inline-block; padding: 12px 16px; border-radius: var(--lp-r-md);
+background: var(--lp-primary); color: var(--lp-surface); font-size: var(--lp-fs-sm);
+font-weight: 600; text-decoration: none; }
+.primary:hover { background: var(--lp-primary-hover); }
+a:focus-visible, button:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 4px; }
+"""
+
+
+@lru_cache(maxsize=1)
+def _font_css():
+ """Reuse the embedded Inter face from the shell's source or shipped CSS."""
+ web = Path(__file__).resolve().parents[1] / "web"
+ paths = [web / "src/index.css", *sorted((web / "dist/assets").glob("*.css"))]
+ for path in paths:
+ if not path.is_file():
+ continue
+ for face in re.findall(r"@font-face\s*\{[^}]*\}", path.read_text(encoding="utf-8")):
+ if re.search(r"font-family\s*:\s*['\"]?Inter\b", face) and "data:" in face:
+ return face
+ raise RuntimeError("The embedded Inter face is missing.")
+
+
+def _page(content, *, title="Shared artifact", status=200):
+ document = (""
+ ""
+ f"{escape(title)}"
+ f"{content}")
+ return HTMLResponse(document, status_code=status, headers=HEADERS)
+
+
+def _invalid(status=403):
+ return _page(f"
{artifact_share.NOT_VALID}
", status=status)
+
+
+def _admit(request, token, valid):
+ """Limit valid capabilities separately from failed guesses at the socket peer."""
+ peer = request.client.host if request.client else "unknown"
+ locator = sha256(token.encode()).hexdigest() if valid else peer
+ key = (request.method, valid, locator)
+ limit = (POST_LIMIT if request.method == "POST" else GET_LIMIT) if valid else FAILURE_LIMIT
+ now = time.monotonic()
+ with _LOCK:
+ seen = [stamp for stamp in _HITS.pop(key, ()) if now - stamp < RATE_WINDOW_S]
+ admitted = len(seen) < limit
+ if admitted:
+ seen.append(now)
+ _HITS[key] = seen
+ while len(_HITS) > MAX_RATE_KEYS:
+ _HITS.popitem(last=False)
+ return admitted
+
+
+def _renew_button(token):
+ return (f'')
+
+
+_NUMERIC_TYPES = frozenset({"currency", "int", "float", "number", "decimal", "percent", "percentage"})
+_DISPLAY_AMOUNT = re.compile(
+ r"(?:[-+]?[$€£]\s*|[$€£]\s*[-+]?)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?"
+ r"|\([$€£]\s*(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\)"
+ r"|[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\s*%"
+)
+
+
+def _numeric(value, column, summed):
+ """Use frozen column semantics, then explicit currency or percentage display text."""
+ kind = column.get("type")
+ if kind:
+ return kind in _NUMERIC_TYPES
+ if column.get("key") in summed:
+ return True
+ return ((isinstance(value, (int, float)) and not isinstance(value, bool))
+ or (isinstance(value, str) and _DISPLAY_AMOUNT.fullmatch(value.strip()) is not None))
+
+
+def _snapshot(rt, row):
+ content = assistant_artifacts.read_snapshot(rt, row)
+ if not isinstance(content, dict):
+ return None
+ columns, rows = content.get("columns"), content.get("rows")
+ if not isinstance(columns, list) or not isinstance(rows, list):
+ return None
+ totals = content.get("totals") or {}
+ summed = totals.get("sum") or {}
+ numeric_columns = [
+ _numeric(None, col, summed) or (
+ any(isinstance(values, list) and index < len(values) and values[index] not in (None, "")
+ for values in rows)
+ and all(_numeric(values[index], col, summed) for values in rows
+ if isinstance(values, list) and index < len(values) and values[index] not in (None, "")))
+ for index, col in enumerate(columns)
+ ]
+ header = "".join('
'
+ for index, col in enumerate(columns))
+ rendered = []
+ for values in rows:
+ if not isinstance(values, list):
+ return None
+ cells = []
+ for index, value in enumerate(values):
+ col = columns[index] if index < len(columns) else {}
+ numeric = _numeric(value, col, summed)
+ cls = ' class="number"' if numeric else ""
+ text = "" if value is None else str(value)
+ cells.append(f"
{escape(text)}
")
+ rendered.append("
" + "".join(cells) + "
")
+ labels = {col.get("key"): col.get("label", col.get("key", "")) for col in columns}
+ footer = []
+ if "count" in totals:
+ footer.append(f'Rows: {escape(str(totals["count"]))}')
+ for key, value in (totals.get("sum") or {}).items():
+ footer.append(f'{escape(str(labels.get(key, key)))}: {escape(str(value))}')
+ return ('
' + header + '
'
+ + "".join(rendered) + '
'
+ + " ".join(footer) + '
'
+ + (f'
{escape(str(content["note"]))}
' if content.get("note") else ""))
+
+
+def _file(rt, share, artifact):
+ metadata = assistant_files.owned_metadata(rt, share["owner"], artifact.get("file_id"))
+ if (not isinstance(metadata, dict) or metadata.get("artifactId") != artifact["id"]
+ or metadata.get("mime") not in FILE_TYPES
+ or artifact.get("mime", metadata.get("mime")) != metadata.get("mime")
+ or not isinstance(metadata.get("size"), int) or isinstance(metadata.get("size"), bool)
+ or not 0 <= metadata["size"] <= MAX_FILE_BYTES):
+ return None
+ data = assistant_files.read_bytes(rt, metadata)
+ if not isinstance(data, bytes) or len(data) != metadata["size"]:
+ return None
+ return metadata, data
+
+
+def _sign_in(found):
+ """Accept T31's validated resolution without exposing content or arbitrary redirects."""
+ row, share, rt = found.get("row"), found.get("share"), found.get("rt")
+ if (not isinstance(row, dict) or not isinstance(share, dict)
+ or row.get("id") != share.get("artifact_id") or row.get("status") != "active"
+ or getattr(rt, "key", None) is None):
+ return _invalid()
+ link = loopy_links.artifact_link(row["id"])
+ return RedirectResponse(link, status_code=303, headers=HEADERS) if link else _invalid()
+
+
+@router.get("/a/{token}", response_class=HTMLResponse)
+def shared_artifact(token: str, request: Request):
+ key = artifact_share._secret()
+ signed = key is not None and artifact_share._claims(token, key) is not None
+ if not _admit(request, token, signed):
+ return _invalid(429)
+ found = artifact_share.resolve(token)
+ if found["state"] == "sign_in":
+ return _sign_in(found)
+ if found["state"] == "expired":
+ return _page(_renew_button(token))
+ if found["state"] != "ok":
+ return _invalid()
+ row, rt, share = found["row"], found["rt"], found["share"]
+ try:
+ artifact = assistant_artifacts.c7(row)
+ content = None
+ if artifact["kind"] == "snapshot":
+ content = _snapshot(rt, row)
+ elif artifact["kind"] in {"pdf", "xlsx", "image"}:
+ frozen = _file(rt, share, artifact)
+ if frozen is not None:
+ metadata, data = frozen
+ mime = metadata["mime"]
+ if request.query_params.get("download") == "1":
+ name = re.sub(r"[^A-Za-z0-9._ ]", "_", str(artifact["title"]))[:100].strip(". ") or "Artifact"
+ name += FILE_TYPES[mime]
+ return Response(data, media_type=mime, headers={**HEADERS,
+ "Content-Disposition": f"attachment; filename*=UTF-8''{quote(name)}"})
+ if artifact["kind"] == "image" and mime.startswith("image/"):
+ content = (f'')
+ else:
+ content = f'Download file'
+ if content is None:
+ return _invalid()
+ title = escape(str(artifact["title"]))
+ made = escape(str(artifact["created_at"]), quote=True)
+ stamp = datetime.fromisoformat(str(artifact["created_at"]).replace("Z", "+00:00"))
+ if stamp.tzinfo is None:
+ stamp = stamp.replace(tzinfo=timezone.utc)
+ label = escape(stamp.astimezone(timezone.utc).strftime("%d %b %Y, %H:%M UTC"))
+ link = loopy_links.artifact_link(artifact["id"])
+ opening = f'Open in Loopable' if link else ""
+ return _page(f'
{title}
{content}{opening}',
+ title=str(artifact["title"]))
+ except Exception:
+ return _invalid()
+
+
+@router.post("/a/{token}/request-again", response_class=HTMLResponse)
+async def request_again(token: str, request: Request):
+ key = artifact_share._secret()
+ signed = key is not None and artifact_share._claims(token, key) is not None
+ if not _admit(request, token, signed):
+ return _invalid(429)
+ size = 0
+ chunks = []
+ async for chunk in request.stream():
+ size += len(chunk)
+ if size > MAX_BODY_BYTES:
+ return _invalid(413)
+ chunks.append(chunk)
+ if b"".join(chunks).strip() not in {b"", b"{}"}:
+ return _invalid(400)
+ found = await run_in_threadpool(artifact_share.resolve, token)
+ if found["state"] == "sign_in":
+ return _sign_in(found)
+ try:
+ result = await run_in_threadpool(artifact_share.request_again, token)
+ except Exception:
+ result = {"outcome": "failed", "message": artifact_share.NOT_SENT}
+ if result["outcome"] in {"invalid", "refused"}:
+ return _invalid()
+ button = _renew_button(token) if result["outcome"] == "failed" else ""
+ return _page(f'
{escape(result["message"])}
{button}')
diff --git a/api/routes_shares.py b/api/routes_shares.py
index a6f03b1a1d4c7aede5b8589ce0aa041d16f30508..b3690ebad22a7856984ace386244224925be6f1d 100644
--- a/api/routes_shares.py
+++ b/api/routes_shares.py
@@ -4,6 +4,7 @@
PUT /api/v1/share/{kind}/{oid} <- {entries:[{user,role}]} (REPLACES the set)
PUT /api/v1/share/{kind}/{oid}/owner <- {owner: ""} (R6d — `field` ONLY)
GET /api/v1/share/mine -> {view:[id], folder:[id], database:[id]}
+ POST /api/v1/assistant/inbox/{request_id}/{action} -> {state} (C6, S72-T28: approve | not_now)
`kind` ∈ view | folder | database | field. Roles are `view` | `edit` — the same two words the
view rail already speaks, now extended to folders, databases and COLUMNS so there is ONE
@@ -866,6 +867,27 @@ def _find_view_topic(session, oid):
return None, None
+def _find_view_record(session, oid):
+ """`(topic, creator, view)` for a saved view, else `(None, None, None)` (S72-T28).
+
+ Same loop as `_find_view_topic`. `find_view` answers `(owner_username, view, ...)`, and the
+ creator is the view's owner until a grant record names one.
+ """
+ try:
+ import core.table_store as table_store
+ except Exception: # noqa: BLE001
+ return None, None, None
+ for topic in _topics(session):
+ try:
+ hit = table_store.make(f"{topic}_table_workspace", st=session.runtime).find_view(oid)
+ except Exception: # noqa: BLE001
+ continue
+ if hit:
+ return (str(topic), str(hit[0] or "") or None,
+ (hit[1] if len(hit) > 1 and isinstance(hit[1], dict) else {}))
+ return None, None, None
+
+
def _promote_field_for_grant(session, table_key, field_key, resolved=None):
"""Promote a private column exactly once, stamp it shared, and answer its GRANT OID.
@@ -1487,6 +1509,20 @@ def put_share(kind: str, oid: str, body: dict = Body(default=None),
return out
+@router.post("/assistant/inbox/{request_id}/{action}")
+def inbox_action(request_id: str, action: str, session: Session = Depends(require_session)):
+ """C6 (S72-T28): the owner, or an Administrator for a database, answers an access request.
+
+ `action` is `approve` or `not_now` and the answer is `{"state"}`. This route is the only
+ caller of `agent_inbox.decide_request`: a grant changes on a person's click, never an agent's.
+ """
+ import agent_inbox
+ try:
+ return agent_inbox.decide_request(session, request_id, action)
+ except agent_inbox.Denied as exc:
+ raise err(exc.status, exc.code, exc.message)
+
+
@router.post("/share/view/{oid}/assign")
def assign_view(oid: str, body: dict = Body(default=None),
session: Session = Depends(require_session)):
diff --git a/api/routes_sheet.py b/api/routes_sheet.py
index 53667e0909e0cba65c907ca3384862ba5eb05376..c4d611398157d68ccec099cb40109509a264798e 100644
--- a/api/routes_sheet.py
+++ b/api/routes_sheet.py
@@ -2507,6 +2507,61 @@ def write_sheet(workbook_id: str, body: dict = Body(default=None),
return {"workbook": _response_workbook(book)}
+def _rename_rev(raw):
+ """Require an integer revision on every rename."""
+ rev = raw.get("rev")
+ if isinstance(rev, bool) or not isinstance(rev, int) or rev < 0:
+ raise HTTPException(status_code=400, detail={"error": {
+ "code": "workbook_revision_invalid", "message": "A rename needs the workbook revision."}})
+ return rev
+
+
+def _require_rename_editor(session, book):
+ """Keep rename permission refusals short and ahead of revision checks."""
+ if _role_on_workbook(session, book) not in ("owner", "edit"):
+ from core import sheets
+ raise _refuse(sheets.SheetRefusal("workbook_read_only", "This workbook is read only."))
+
+
+@router.patch("/sheets/{workbook_id}/name")
+def rename_sheet(workbook_id: str, body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """S72-T64: rename a workbook. Body `{name, rev}`, answer `{workbook}` without cells.
+
+ The read-only check runs before the revision check, as on every write door.
+ """
+ from core import sheets
+ raw = dict(body or {})
+ try:
+ _require_rename_editor(session, sheets.rename_access(_store(session), workbook_id))
+ expect = _rename_rev(raw)
+ book = sheets.rename_workbook(_store(session), workbook_id, raw.get("name"),
+ expect_rev=expect)
+ except sheets.SheetRefusal as exc:
+ raise _refuse(exc)
+ return {"workbook": sheets.rename_meta(book)}
+
+
+@router.patch("/sheets/{workbook_id}/tabs/{tab}/name")
+def rename_sheet_tab(workbook_id: str, tab: str, body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """S72-T64: rename one tab. Body `{name, rev}`, answer `{workbook}` without cells.
+
+ Formulas that name the old tab follow the new name on the server, so tabs the client never
+ loaded are covered without sending them.
+ """
+ from core import sheets
+ raw = dict(body or {})
+ try:
+ _require_rename_editor(session, sheets.rename_access(_store(session), workbook_id))
+ expect = _rename_rev(raw)
+ book = sheets.rename_tab(_store(session), workbook_id, tab, raw.get("name"),
+ expect_rev=expect)
+ except sheets.SheetRefusal as exc:
+ raise _refuse(exc)
+ return {"workbook": sheets.rename_meta(book)}
+
+
@router.delete("/sheets/{workbook_id}")
def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
"""Delete a workbook. THE OWNER's door, and an editor is refused by name (C5).
diff --git a/api/routes_starred.py b/api/routes_starred.py
index 30d48707c737cdc3736102a95cb0dd4a8d2e3a11..eec4f229c69e7215c2d730523b846b5119e60466 100644
--- a/api/routes_starred.py
+++ b/api/routes_starred.py
@@ -32,7 +32,7 @@ import copy
import hashlib
import json
import time
-from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from fastapi import APIRouter, Body, Depends
@@ -737,11 +737,15 @@ def set_starred(body: dict = Body(default=None),
try:
import application_registry
import routes_assets
- application_databases = routes_assets._application_databases(session.runtime, oid)
- allowed_databases, _ = routes_assets.application_access_context(
- session, application_databases)
- if not allowed_databases:
- raise application_registry.ApplicationError("application does not exist")
+ if routes_assets.finance_access(session, oid):
+ # A Finance copy binds no database, so the database wall does not apply.
+ allowed_databases = set()
+ else:
+ application_databases = routes_assets._application_databases(session.runtime, oid)
+ allowed_databases, _ = routes_assets.application_access_context(
+ session, application_databases)
+ if not allowed_databases:
+ raise application_registry.ApplicationError("application does not exist")
application_registry.mutate(session.runtime, oid, session.uname, session.admin,
{"starred": on}, allowed_databases=allowed_databases)
except PermissionError as exc:
@@ -803,25 +807,45 @@ def set_starred(body: dict = Body(default=None),
# ══════════════════════════════════════════════════════════════════ STARRED COUNTS (R7, C3)
#
-# ⭐ R7: *"Row counts come from a NEW on-demand endpoint called after Home/Starred paint, never from
-# `/nav`. A view whose count is not free shows the CAUSE, never an invented number."*
+# ⭐ R108 (f): every starred view's count is computed, and nothing shows while it loads or fails.
+# The count is the grid's own scoped aggregate (`routes_odoo_tables.odoo_table_aggregates`, the
+# door `CustomerGrid::readImportantViewCount` reads), called as this session, so a scoped member
+# reads the number the grid shows them.
#
-# ⛔ SO EVERY VID LANDS IN EXACTLY ONE OF `counts` AND `notes`, AND THAT IS THE CONTRACT (C3). A vid
-# in neither is a client rendering nothing with no idea why; a vid in both is two answers to one
-# question. `notes` is not a fallback for "we did not get round to it" — it is the CAUSE, in a
-# sentence, with what to do about it, which is R6's second sentence applied to a badge.
-
-
-def _cohort_sizes(session, key, cache):
- """`{cohort_id: size}` for THIS caller's own cohorts on `key`'s topic. Memoised per request.
-
- ⛔ THIS CALLER'S OWN COHORTS ONLY, and the consequence is deliberate: a SHARED view locked to a
- cohort somebody else owns finds no id here, so it is reported UNCOUNTED with that cause rather
- than counted out of a stratum this session cannot see. Widening the read would make the number
- disclose the SIZE of another person's private list, which is a leak wearing a bug fix.
- ⚠ Read through `session.runtime`, NOT `modules.cohort`'s module-level helpers: those call
- `core.store` directly and carry no tenant namespace. The MODULE is asked for the bucket NAME (it
- owns that rule) and this route does the reading, which is the only tenant-correct combination.
+# ⛔ EVERY VID LANDS IN EXACTLY ONE OF `counts` AND `notes` (C3). A note is the CAUSE a count could
+# not be computed (standing rule 1). The client draws nothing for a note.
+
+#: Counts in flight at once for one request. Each is one aggregate read on the grid's door.
+COUNT_WORKERS = 4
+
+#: Seconds one view may count before it lands in `notes`. The others keep counting.
+COUNT_VIEW_BUDGET_S = 6.0
+
+#: Ceiling on the whole counts pass, so a queue of slow views cannot hold the request open.
+COUNT_BUDGET_S = 12.0
+
+# One process-wide pool, for the reason `_BATCH_READ_POOL` gives: a timed-out thread cannot be
+# killed, so a per-request pool would grow one live worker per slow request.
+_COUNT_POOL = ThreadPoolExecutor(max_workers=COUNT_WORKERS, thread_name_prefix="starred-count")
+
+#: The aggregate `limits` effects that leave `total_rows` exact (`counts.ts::serverViewCount`).
+_EXACT_EFFECTS = ("none", "slow")
+
+#: The cause for a view locked to a cohort this caller cannot read.
+LOCKED_ELSEWHERE_NOTE = ("This view is locked to a list owned by somebody else, so its size is "
+ "not something your account can read. Ask whoever shared it.")
+
+
+class _Uncounted(Exception):
+ """A count that cannot be computed. The message is the cause, for `notes`."""
+
+
+def _cohort_members(session, key, cache):
+ """`{cohort_id: [pid]}` for THIS caller's own cohorts on `key`'s topic. Memoised per request.
+
+ ⛔ THIS CALLER'S OWN COHORTS ONLY: a count out of somebody else's private list would disclose
+ its size. ⚠ Read through `session.runtime` (tenant namespace), never `modules.cohort`'s
+ module-level helpers, which call `core.store` directly.
"""
import core.view_templates as view_templates
import modules.cohort as cohort_mod
@@ -833,33 +857,94 @@ def _cohort_sizes(session, key, cache):
try:
bucket = session.runtime.get(cohort_mod.key_for(scope)) or {}
mine = bucket.get(session.uname) or {}
- cache[scope] = {str(cid): len(c.get("members") or [])
+ cache[scope] = {str(cid): _int_ids(c.get("members"))
for cid, c in mine.items() if isinstance(c, dict)}
except Exception:
cache[scope] = {}
return cache[scope]
-def _count_note(cfg, cohorts):
- """WHY this view's size is not free, as one sentence naming a cause AND a next step.
+def _int_ids(raw):
+ """Record ids as ints, de-duplicated in order. A non-integer id is dropped."""
+ out = []
+ for item in (raw if isinstance(raw, (list, tuple)) else ()):
+ try:
+ out.append(int(item))
+ except (TypeError, ValueError):
+ continue
+ return list(dict.fromkeys(out))
+
+
+def _clean_cause(text):
+ """One sentence for `notes`, with no em or en dash (standing rule 2)."""
+ s = " ".join(str(text or "").split()).replace(chr(0x2014), ", ").replace(chr(0x2013), "-")
+ s = s.rstrip(" .")
+ return s or "the count read failed"
+
+
+def _refusal_message(exc):
+ """The `message` of an `err(...)` refusal, or None for any other exception."""
+ detail = getattr(exc, "detail", None)
+ if isinstance(detail, dict):
+ error = detail.get("error")
+ if isinstance(error, dict) and error.get("message"):
+ return str(error["message"])
+ return None
+
- ⛔ R6's SECOND SENTENCE IS THE SPEC HERE, and a bare dash is the thing it forbids. D-253 was
- booked once already for a limit whose explanation was hover-only, so this has to be a real
- sentence a client can put in a `title` AND an `aria-label`.
- ⚠ THREE DIFFERENT CAUSES, not one generic apology. A view locked to somebody else's list, a
- filtered view and a whole-table view are three different facts, and only one of them is
- something the reader can act on.
+def _door_count(session, key, nodes, conj, ids):
+ """`total_rows` of the grid's scoped aggregate door for one predicate, or `_Uncounted`."""
+ from routes_odoo_tables import odoo_table_aggregates
+ body = {"filters": nodes, "filterConj": conj, "search": "", "aggs": []}
+ if ids is not None:
+ body["ids"] = list(ids)
+ out = odoo_table_aggregates(key, body=body, session=session)
+ out = out if isinstance(out, dict) else {}
+ total = out.get("total_rows")
+ if type(total) is not int or total < 0:
+ raise _Uncounted("the count read returned no total")
+ limits = out.get("limits")
+ for limit in (limits if isinstance(limits, list) else [None]):
+ # A limit that narrows or widens the population makes the total a different view's size.
+ if not isinstance(limit, dict) or limit.get("effect") not in _EXACT_EFFECTS:
+ cause = limit.get("cause") if isinstance(limit, dict) else ""
+ raise _Uncounted(cause or "the count read reported a limit on this view")
+ return total
+
+
+def _view_count(session, key, cfg, cohorts):
+ """How many records this view shows THIS session, through the grid's scoped door.
+
+ The order is `CustomerGrid::runPipeline`'s: a cohort lock narrows first, then the filters with
+ `memberPids` pinned in (a union). With no filters, `memberPids` is the view.
"""
cfg = cfg if isinstance(cfg, dict) else {}
+ pin = None
lock = str(cfg.get("cohortLock") or "").strip()
if lock:
- return ("This view is locked to a list owned by somebody else, so its size is not "
- "something your account can read. Ask whoever shared it.")
- if cfg.get("filters"):
- return ("Counting a filtered view means reading every record, which this page does not "
- "do. Open the database and the number is beside the view.")
- return ("This view covers the whole database, so its size is the record count. Open the "
- "database to see it.")
+ if lock not in cohorts:
+ raise _Uncounted(LOCKED_ELSEWHERE_NOTE)
+ pin = cohorts[lock]
+ curated = _int_ids(cfg.get("memberPids"))
+ if pin is not None and curated:
+ allowed = set(pin)
+ curated = [pid for pid in curated if pid in allowed]
+ has_curated = bool(cfg.get("memberPids"))
+ nodes = cfg.get("filters") if isinstance(cfg.get("filters"), list) else []
+ conj = "or" if cfg.get("filterConj") == "or" else "and"
+ if not nodes:
+ return _door_count(session, key, [], conj, curated if has_curated else pin)
+ matched = _door_count(session, key, nodes, conj, pin)
+ if not has_curated:
+ return matched
+ # |filters ∪ curated| = |filters| + |curated| - |filters ∩ curated|, each on the same door.
+ return (matched + _door_count(session, key, [], conj, curated)
+ - _door_count(session, key, nodes, conj, curated))
+
+
+def _count_one(session, key, cfg, cohorts, started, count_key):
+ started[count_key] = time.monotonic()
+ return _view_count(session, key, cfg, cohorts)
def _count_key(database, view_id):
@@ -874,31 +959,49 @@ def _count_key(database, view_id):
@router.get("/starred/counts")
def starred_counts(session: Session = Depends(require_session)):
- """C3 — `{"counts": {database-and-view-id: int}, "notes": {...}, "degraded": [key]}`.
+ """C3: `{"counts": {database-and-view-id: int}, "notes": {...}, "degraded": [key]}`.
- ⛔ CALLED AFTER THE PAGE PAINTS, NEVER FROM `/nav` (R7). `/nav` is a rows-free projection whose
- budget was the subject of D-175, D-185, D-288 and D-289; W35-T43 takes the last of that off it,
- and putting a counting pass back on the nav's path would undo the whole point.
-
- ⚠ THE COUNTER IS `routes_nav._view_record_count`, CALLED — not a second implementation. It is the
- one function that knows which shapes are free (a cohort lock resolves to a stored member list; a
- curated `memberPids` carries its own length) and returns None for everything else. A second
- counter here would be free to disagree with the badge inside the database.
+ ⛔ CALLED AFTER THE PAGE PAINTS, NEVER FROM `/nav` (R7): every count here reads records.
+ Counts run on `_COUNT_POOL`, each inside `COUNT_VIEW_BUDGET_S` and all inside `COUNT_BUDGET_S`.
"""
rows, unread = _scan_starred_views(session)
- cache, counts, notes = {}, {}, {}
+ cache, counts, notes, futures, started = {}, {}, {}, {}, {}
for row in rows:
cfg, key, vid = row["config"], row["database"], row["id"]
count_key = _count_key(key, vid)
- sizes = _cohort_sizes(session, key, cache)
- n = routes_nav._view_record_count(cfg, sizes)
- # ⛔ EXACTLY ONE OF THE TWO MAPS (C3). The `if/else` is what makes that structural rather
- # than a rule somebody has to remember: there is no path that writes both and none that
- # writes neither.
- if isinstance(n, int):
- counts[count_key] = n
- else:
- notes[count_key] = _count_note(cfg, sizes)
+ try:
+ cohorts = _cohort_members(session, key, cache)
+ except Exception:
+ cohorts = {}
+ futures[count_key] = _COUNT_POOL.submit(_count_one, session, key, cfg, cohorts,
+ started, count_key)
+ deadline = time.monotonic() + COUNT_BUDGET_S
+ pending = dict(futures)
+ while pending:
+ now = time.monotonic()
+ for count_key, future in list(pending.items()):
+ if future.done():
+ pending.pop(count_key)
+ try:
+ counts[count_key] = int(future.result())
+ except _Uncounted as exc:
+ notes[count_key] = _clean_cause(str(exc)) + "."
+ except Exception as exc: # noqa: BLE001
+ cause = _refusal_message(exc) or f"the count read failed ({type(exc).__name__})"
+ notes[count_key] = "This view could not be counted: " + _clean_cause(cause) + "."
+ continue
+ began = started.get(count_key)
+ if now >= deadline or (began is not None and now - began >= COUNT_VIEW_BUDGET_S):
+ pending.pop(count_key)
+ future.cancel()
+ notes[count_key] = ("This view took too long to count. Open it to see its "
+ "records.")
+ if pending:
+ wait(list(pending.values()), timeout=0.05, return_when=FIRST_COMPLETED)
+ # ⛔ EXACTLY ONE OF THE TWO MAPS (C3), whatever order the futures finished in.
+ for count_key in futures:
+ if count_key in counts:
+ notes.pop(count_key, None)
return {"counts": counts, "notes": notes, "degraded": unread}
diff --git a/api/routes_tables.py b/api/routes_tables.py
index c8d44aef65cbd5a57f020d09e6f8a03a9b5a7492..53b6c8a30f0a3a16213fc38dbc811a232157c698 100644
--- a/api/routes_tables.py
+++ b/api/routes_tables.py
@@ -3722,6 +3722,19 @@ def _c1_mirror_rows(table_key, field_keys, st):
"store has finished opening") from e
+@router.get("/scope-limits")
+def scope_limits(session: Session = Depends(require_session)):
+ """S72-T61 / R114: the row limit this reader carries on each database, described safely.
+
+ Read-only and display-only: the filter panels paint it as a locked first row, and every
+ data door keeps enforcing the stored scope whatever the client sends. An Administrator
+ gets `{"limits": []}`. Shape: `{"limits": [{"database", "parts", "text", "rows", "fields"}]}`,
+ where `rows` is `describe_scope`'s reader-safe condition tree, passed through unchanged.
+ """
+ from core import perm_scope
+ return {"limits": perm_scope.scope_limits(session.user, st=session.runtime)}
+
+
def _register_mirror():
"""Declare the mirror reader to C1. Called at import; returns True once it is registered."""
import core.perm_scope as perm_scope
diff --git a/api/routes_templates.py b/api/routes_templates.py
index 37f101bcedd7d8f8cb84049af43573207bc6982d..806a59408d56f3fa70947ff3f450db148ac28028 100644
--- a/api/routes_templates.py
+++ b/api/routes_templates.py
@@ -280,6 +280,29 @@ def _data_template_database(template, definitions):
return ""
+def _own_template_apps(session):
+ """{template key: the caller's own App}; an unreadable registry offers every template."""
+ import application_registry
+ try:
+ return application_registry.own_template_apps(session.runtime, session.uname)
+ except Exception:
+ return {}
+
+
+def _existing_app(held):
+ """{id, name, address} of an owned App, where address is the hash the picker navigates to."""
+ from urllib.parse import quote
+ if not isinstance(held, dict) or not held.get("id"):
+ return None
+ if held.get("deepLink"):
+ address = "#" + str(held["deepLink"])
+ else:
+ address = ("#/app?database=" + quote(str(held.get("sourceDatabase") or ""), safe="")
+ + "&application=" + quote(str(held["id"]), safe=""))
+ return {"id": held["id"], "name": dash_norm.plain(str(held.get("name") or "")),
+ "address": address}
+
+
def _agent_templates():
"""Fresh starter definitions; saving one never arms its schedule."""
import os
@@ -375,6 +398,10 @@ def _module_templates(session):
app.extend(_catalog_row("finance:" + row["key"], row["label"], row["description"], [],
creation_mode="post")
for row in finance_templates(may_open=lambda permission: _may_open(session, permission)))
+ # R103: a template the caller already owns opens that App instead of creating a second.
+ owned = _own_template_apps(session)
+ for row in app:
+ row["existing"] = _existing_app(owned.get(row["key"]))
sections = [{"module": "sheet", "templates": sheet},
{"module": "data", "templates": data},
{"module": "app", "templates": app}]
@@ -513,6 +540,8 @@ def create_module_template(module: str, key: str, body: dict = Body(default=None
"financeKey": finance_key, "name": body.get("name") or descriptor["label"],
"navPlacement": {"section": "app", "order": 0}},
allowed_databases=set())
+ except application_registry.ApplicationExistsError as exc:
+ raise err(400, "app_exists", str(exc), {"existing": exc.existing})
except application_registry.ApplicationError as exc:
raise err(400, "bad_application", str(exc))
except PermissionError as exc:
diff --git a/api/schedule_tools.py b/api/schedule_tools.py
index a08a10eb379592e66344e73cb7c95cf267fec1f4..f0f7afb5f3b86eae7872d6479e55443bcaa6d8fd 100644
--- a/api/schedule_tools.py
+++ b/api/schedule_tools.py
@@ -138,6 +138,8 @@ def _owned(session, args):
def _record_artifact(session, args, item, *, tool_name="schedule_create"):
+ if getattr(session.runtime, "preview_only", False):
+ return
try:
artifacts = importlib.import_module("assistant_artifacts")
except ImportError:
diff --git a/api/schedules.py b/api/schedules.py
index 5e658392353a363c6790e246aae512fbab3f2425..d455f5f19b37bd8db17d08b003d55af32277ae30 100644
--- a/api/schedules.py
+++ b/api/schedules.py
@@ -10,6 +10,7 @@ import logging
import os
import secrets
import threading
+from core import write_execution
import time
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
@@ -28,7 +29,7 @@ _LOG = logging.getLogger(__name__)
def _utc(value=None):
- value = value if value is not None else dt.datetime.now(_UTC)
+ value = value if value is not None else write_execution.utcnow()
if isinstance(value, str):
value = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
return value.replace(tzinfo=_UTC) if value.tzinfo is None else value.astimezone(_UTC)
@@ -153,7 +154,7 @@ def create(rt, owner, *, cron=None, tz, action, label, system=False, once_at=Non
if once and next_at <= now:
raise ValueError("Choose a reminder time in the future.")
next_stamp = next_at.isoformat().replace("+00:00", "Z") if once else _iso(next_at)
- schedule_id = "sch_" + secrets.token_hex(8)
+ schedule_id = "sch_" + write_execution.new_id()[:16]
item = {"id": schedule_id, "owner": owner, "label": label,
"cron": None if once else " ".join(cron.split()),
"tz": tz, "action": action, "paused": False, "nextRunAt": next_stamp,
diff --git a/api/telnyx_whatsapp.py b/api/telnyx_whatsapp.py
index 4778c5bf81e8f6800aaa13cb0d4990bea03dd50e..2377988c27e2a2f150a2b161e9a6a584c861b2b7 100644
--- a/api/telnyx_whatsapp.py
+++ b/api/telnyx_whatsapp.py
@@ -2,13 +2,15 @@
from __future__ import annotations
import copy
+import ipaddress
import json
+import math
import os
import re
import time
import uuid
from datetime import datetime, timezone
-from urllib import request
+from urllib import parse, request
import core.store as store
@@ -19,10 +21,31 @@ OUTBOX_LIMIT = 500
MESSAGES_URL = "https://api.telnyx.com/v2/messages/whatsapp"
AUTH_TEMPLATE_TEXT = "{{1}} is your Loopable verification code. It expires in 10 minutes. Loopable is the business data assistant for your company's own records."
PING_TEMPLATE_TEXT = "Loopable found something in your company records that needs attention: {{1}}. Suggested action: {{2}}. Reply here to ask about it, or reply STOP to turn these alerts off."
+#: R101: the Meta body for the TELNYX_WA_LINK_TEMPLATE template. Meta refuses a body that starts or ends with a variable.
+LINK_TEMPLATE_TEXT = ("Your data assistant has an update for you: {{1}} Open it here: {{2}} "
+ "Reply here to ask about it.")
+LINK_PURPOSE = "link_notice"
+LINK_SUMMARY_LIMIT = 200
+LINK_SUMMARY_EMPTY = "Your answer is ready."
+_URL = re.compile(r"https?://\S+")
+_HTTPS_LINK = re.compile(r"https://[^\s<>\"]{1,2000}")
INBOUND_WEBHOOK_PATH = "/api/v1/whatsapp/telnyx/inbound"
WINDOW_KEY = "whatsapp_window"
WINDOW_SECONDS = 86400
DOCUMENT_LIMIT = 15 * 1024 * 1024
+IMAGE_LIMIT = 5 * 1024 * 1024
+XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+DOCUMENT_MIMES = {"application/pdf", XLSX_MIME}
+IMAGE_MIMES = {"image/png", "image/jpeg"}
+#: R99: an inbound photo or PDF is read; a voice note, video, sticker or other file is refused.
+INBOUND_KINDS = ("audio", "image", "video", "document", "sticker")
+INBOUND_IMAGE_MIMES = {"image/jpeg", "image/png", "image/webp"}
+INBOUND_PDF_MIME = "application/pdf"
+INBOUND_IMAGE_LIMIT = 5 * 1024 * 1024
+INBOUND_PDF_LIMIT = 10 * 1024 * 1024
+MEDIA_HOST = "telnyx.com"
+MEDIA_TIMEOUT_S = 15
+MEDIA_CHUNK = 64 * 1024
def _seconds(value):
@@ -47,19 +70,121 @@ def within_window(phone, now=None, *, store_=None):
def send_reply(to, text, *, purpose="reply", tenant="", username="", now=None,
- link=None, transport=None, store_=None):
+ link=None, audit=None, transport=None, store_=None):
_check_text(text)
if link is not None:
_check_text(link)
- kwargs = {"purpose": purpose, "tenant": tenant, "username": username,
- "transport": transport, "store_": store_}
- if within_window(to, now, store_=store_):
- return send_text(to, text, **kwargs)
- summary = " ".join(text.split())
- if len(summary) > 200:
- summary = summary[:197].rstrip() + "..."
- return send_template(to, ping_template(),
- [summary, link or "Open Loopable to see the full answer."], **kwargs)
+ # Inbound windows live globally, even when a tenant runtime holds the reminder outbox.
+ tenant_outbox = bool(tenant) and getattr(store_, "key", None) == tenant
+ window_store = None if tenant_outbox else store_
+ if within_window(to, now, store_=window_store):
+ return send_text(to, text, purpose=purpose, tenant=tenant, username=username,
+ transport=transport, store_=store_)
+ # A tenant runtime passed as the outbox store also holds that tenant's turn audit.
+ if audit is None and tenant_outbox:
+ audit = store_
+ return send_link_notice(to, text, link, owes=purpose, tenant=tenant, username=username,
+ audit=audit, transport=transport, store_=store_)
+
+
+def link_template():
+ """R101: the approved link template name from its one setting, or None. There is no default."""
+ return (os.environ.get("TELNYX_WA_LINK_TEMPLATE") or "").strip() or None
+
+
+def template_price():
+ """Return (price in USD per template message, None) or (None, the reason there is none)."""
+ raw = (os.environ.get("TELNYX_WA_TEMPLATE_PRICE_USD") or "").strip()
+ if not raw:
+ return None, "no price on file"
+ try:
+ price = float(raw)
+ except ValueError:
+ return None, "price setting is not a number"
+ if not math.isfinite(price) or price < 0:
+ return None, "price setting is not a number"
+ return price, None
+
+
+def notice_summary(text):
+ """One plain line for template param 1: links removed, ends in a full stop, at most 200 characters."""
+ summary = " ".join(_URL.sub(" ", text or "").split())
+ if not summary:
+ return LINK_SUMMARY_EMPTY
+ if summary[-1] not in ".!?":
+ summary += "."
+ if len(summary) > LINK_SUMMARY_LIMIT:
+ summary = summary[:LINK_SUMMARY_LIMIT - 3].rstrip() + "..."
+ return summary
+
+
+def https_link(value):
+ """Return the first https link in value, or None."""
+ match = _HTTPS_LINK.search(value) if isinstance(value, str) else None
+ return match.group() if match else None
+
+
+def send_link_notice(to, text, link=None, *, owes="reply", tenant="", username="",
+ audit=None, transport=None, store_=None):
+ """R101: after the window, one template with a summary and one https link. It never sends a file."""
+ _check_text(text)
+ import loopy_links
+ template = link_template()
+ link = https_link(link) or https_link(loopy_links.app_link("#/assistant"))
+ reason = "no_template" if template is None else None if link else "no_link"
+ if reason:
+ # Skipped, never retried: the caller reads status "skipped".
+ print(json.dumps({"kind": "whatsapp_link_notice_skipped", "reason": reason,
+ "setting": "TELNYX_WA_LINK_TEMPLATE", "owes": owes,
+ "tenant": tenant, "username": username}))
+ return {"kind": "template", "purpose": LINK_PURPOSE, "owes": owes,
+ "status": "skipped", "reason": reason}
+ return send_template(to, template, [notice_summary(text), link], purpose=LINK_PURPOSE,
+ owes=owes, tenant=tenant, username=username, audit=audit,
+ transport=transport, store_=store_)
+
+
+def _audit_template(rt, entry):
+ """Write one bounded cost line for a template send to the tenant's weekly turn audit."""
+ try:
+ import turn_audit
+ from core import freeze_notice
+ if freeze_notice.enabled():
+ return False
+ price, reason = template_price()
+ status = entry.get("status")
+ cost = price if status == "sent" and reason is None else None
+ if reason is None and cost is None:
+ reason = "sandbox, not sent" if status == "sandbox" else "not sent"
+ seconds = time.time()
+ week = turn_audit.usage_ledger.week_of(seconds)
+ row = {"turnId": "whatsapp-template-" + entry["id"],
+ "ts": datetime.fromtimestamp(seconds, timezone.utc).isoformat(),
+ "user": str(entry.get("username") or "")[:160], "door": "whatsapp",
+ "provider": "telnyx", "model": entry["template"], "tokensIn": None,
+ "tokensOut": None, "tokens": 0, "calls": 1, "unmeasured": 0, "unbookedCalls": 0,
+ "incompleteUsage": 0, "cost": cost, "costReason": reason, "tools": [],
+ "toolsOverflow": 0, "durationMs": 0,
+ "outcome": "answered" if status in {"sent", "sandbox"} else "failed",
+ "turnKind": "template", "template": entry["template"],
+ "purpose": entry["purpose"], "owes": entry.get("owes"), "priceUsd": price,
+ "mode": entry.get("mode"), "status": status}
+
+ def update(raw):
+ doc = {"week": week, "lines": copy.deepcopy((raw or {}).get("lines") or []),
+ "overflow": int((raw or {}).get("overflow") or 0)}
+ doc["lines"].append(row)
+ while doc["lines"] and (len(doc["lines"]) > turn_audit.MAX_LINES or len(json.dumps(
+ doc, ensure_ascii=True, separators=(",", ":")).encode("utf-8")) > turn_audit.MAX_BYTES):
+ doc["lines"].pop(0)
+ doc["overflow"] += 1
+ return doc
+
+ rt.update(turn_audit.week_key(week), update, flush="sync")
+ return True
+ except Exception as exc:
+ print(json.dumps({"kind": "whatsapp_template_audit_failed", "error": type(exc).__name__}))
+ return False
def mode():
@@ -88,6 +213,25 @@ def _request(url, headers, body_bytes):
return response.status, json.loads(response.read().decode("utf-8"))
+def _owned_file_message(tenant, username, message):
+ """Build a live document or image message for an owned file, or None on any failure."""
+ try:
+ import assistant_files
+ from harness.runtime import get_runtime
+ rt = get_runtime(tenant)
+ # Ownership is checked before a capability is minted.
+ if assistant_files.owned_metadata(rt, username, message["fileId"]) is None:
+ raise ValueError("That file does not belong to this member.")
+ body = {"link": assistant_files.capability_url(rt, message["fileId"])}
+ except Exception:
+ return None
+ if message["kind"] == "document":
+ body["filename"] = message["filename"]
+ elif message.get("caption"):
+ body["caption"] = message["caption"]
+ return {"type": message["kind"], message["kind"]: body}
+
+
def _send(to, message, *, purpose, tenant, username, transport, store_):
selected_mode = mode()
sender = os.environ.get("TELNYX_WHATSAPP_FROM") or ""
@@ -126,23 +270,14 @@ def _send(to, message, *, purpose, tenant, username, transport, store_):
elif message["kind"] == "text":
whatsapp_message = {"type": "text", "text": {"body": message["text"]}}
elif message["kind"] == "document":
- try:
- import assistant_files
- from harness.runtime import get_runtime
- rt = get_runtime(tenant)
- if assistant_files.owned_metadata(rt, username, message["fileId"]) is None:
- raise ValueError("That file does not belong to this member.")
- whatsapp_message = {"type": "document", "document": {
- "link": assistant_files.capability_url(rt, message["fileId"]),
- "filename": message["filename"]}}
- except Exception:
- entry.update(status="failed", error="WhatsApp delivery failed. Try again.")
- selected = store_ if store_ is not None else _store
- selected.update(OUTBOX_KEY, lambda doc: {
- **doc, "messages": ([*(doc.get("messages") or []), entry])[-OUTBOX_LIMIT:]})
- return copy.deepcopy(entry)
+ whatsapp_message = _owned_file_message(tenant, username, message)
+ elif message["kind"] == "image":
+ whatsapp_message = _owned_file_message(tenant, username, message)
payload = {"from": sender, "to": to, "whatsapp_message": whatsapp_message}
try:
+ # A file the member does not own fails here, before any HTTP request.
+ if whatsapp_message is None:
+ raise ValueError("The file message could not be built.")
status, response = (transport or _request)(
MESSAGES_URL, {"Authorization": "Bearer " + key,
"Content-Type": "application/json"},
@@ -267,15 +402,21 @@ def delivery_status(provider_id, *, store_=None):
return None
-def send_template(to, template, params, *, purpose, tenant="", username="",
- transport=None, store_=None):
+def send_template(to, template, params, *, purpose, tenant="", username="", owes=None,
+ audit=None, transport=None, store_=None):
+ """Send one template; with a tenant runtime as audit, also write its cost line."""
_check_text(template)
params = list(params)
for param in params:
_check_text(param)
- return _send(to, {"kind": "template", "template": template, "params": params},
- purpose=purpose, tenant=tenant, username=username,
- transport=transport, store_=store_)
+ message = {"kind": "template", "template": template, "params": params}
+ if owes:
+ message["owes"] = owes
+ entry = _send(to, message, purpose=purpose, tenant=tenant, username=username,
+ transport=transport, store_=store_)
+ if audit is not None:
+ _audit_template(audit, entry)
+ return entry
def send_text(to, text, *, purpose, tenant="", username="", transport=None, store_=None):
@@ -296,3 +437,197 @@ def send_document(to, file_id, filename, *, tenant, username, purpose="reply", n
return _send(to, {"kind": "document", "filename": filename, "fileId": file_id},
purpose=purpose, tenant=tenant, username=username,
transport=transport, store_=store_)
+
+
+def send_image(to, file_id, *, tenant, username, caption=None, purpose="reply", now=None,
+ transport=None, store_=None):
+ """Send an owned image within the reply window without storing its capability."""
+ if not within_window(to, now, store_=store_):
+ return None
+ if not all(isinstance(value, str) and value.strip()
+ for value in (file_id, tenant, username)):
+ raise ValueError("An image needs a file, tenant and member.")
+ message = {"kind": "image", "fileId": file_id}
+ if caption is not None:
+ _check_text(caption)
+ message["caption"] = caption
+ return _send(to, message, purpose=purpose, tenant=tenant, username=username,
+ transport=transport, store_=store_)
+
+
+class MediaRefusal(ValueError):
+ """An inbound attachment that cannot be read; `reason` names why, never the URL."""
+
+ def __init__(self, reason):
+ super().__init__(reason)
+ self.reason = reason
+
+
+def _media_mime(value):
+ return value.split(";", 1)[0].strip().lower() or None if isinstance(value, str) else None
+
+
+def _media_text(value, limit=200):
+ return value.strip()[:limit] or None if isinstance(value, str) else None
+
+
+def inbound_media(payload):
+ """Read an inbound attachment as {kind, mime, size, filename, caption, ref}, or None when there is none."""
+ body = payload.get("body")
+ kind = body.get("type") if isinstance(body, dict) else None
+ items = payload.get("media")
+ if kind in INBOUND_KINDS:
+ # Meta-style body: the caption lives on the attachment, so top-level text is never read.
+ detail = body.get(kind) if isinstance(body.get(kind), dict) else {}
+ url = detail.get("link") or detail.get("url")
+ mime, size, caption = detail.get("mime_type"), detail.get("file_size"), detail.get("caption")
+ filename, media_id = detail.get("filename"), detail.get("id")
+ elif kind is None and isinstance(items, list) and items:
+ detail = items[0] if isinstance(items[0], dict) else {}
+ url, mime, size = detail.get("url"), detail.get("content_type"), detail.get("size")
+ filename, media_id, caption = detail.get("filename"), None, payload.get("text")
+ family = (_media_mime(mime) or "").split("/", 1)[0]
+ kind = {"image": "image", "audio": "audio", "video": "video"}.get(family, "document")
+ else:
+ return None
+ ref = {key: value for key, value in (("url", url), ("id", media_id))
+ if isinstance(value, str) and value.strip()}
+ if isinstance(size, str) and size.isdigit():
+ size = int(size)
+ return {"kind": kind, "mime": _media_mime(mime),
+ "size": size if isinstance(size, int) and not isinstance(size, bool) and size >= 0 else None,
+ "filename": _media_text(filename, 120), "caption": _media_text(caption, 1000), "ref": ref}
+
+
+def media_refusal(media):
+ """Return voice, kind or None for one inbound attachment, from its declared kind and mime."""
+ if media["kind"] == "audio":
+ return "voice"
+ if media["kind"] == "image" and media["mime"] in INBOUND_IMAGE_MIMES:
+ return None
+ if media["kind"] == "document" and media["mime"] == INBOUND_PDF_MIME:
+ return None
+ return "kind"
+
+
+def _media_host(url):
+ parts = parse.urlsplit(url)
+ host = (parts.hostname or "").lower()
+ return (parts.scheme == "https" and not parts.username and not parts.password
+ and (host == MEDIA_HOST or host.endswith("." + MEDIA_HOST)))
+
+
+#: A DNS name with an alphabetic top label: no IP literal, no numeric host form.
+_HOST_NAME = re.compile(r"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}")
+#: Test seam: extra urllib handlers for the media opener. Empty in production.
+_MEDIA_HANDLERS = ()
+
+
+def _named_host(host):
+ """True for a public-looking DNS name; False for an IP literal, localhost or a numeric form."""
+ if not host or host == "localhost" or host.endswith(".localhost"):
+ return False
+ try:
+ ipaddress.ip_address(host)
+ return False
+ except ValueError:
+ return bool(_HOST_NAME.fullmatch(host))
+
+
+class _MediaRedirect(request.HTTPRedirectHandler):
+ """Keep the API key on the media host; follow a signed storage redirect without it."""
+
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ if _media_host(newurl):
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+ parts = parse.urlsplit(newurl)
+ if (parts.scheme != "https" or parts.username is not None or parts.password is not None
+ or not _named_host((parts.hostname or "").lower())):
+ raise MediaRefusal("host")
+ new = super().redirect_request(req, fp, code, msg, headers, newurl)
+ if new is not None:
+ # urllib copies every header to the redirect, the key included.
+ new.remove_header("Authorization")
+ return new
+
+
+def _open_media(req, timeout):
+ return request.build_opener(_MediaRedirect, *_MEDIA_HANDLERS).open(req, timeout=timeout)
+
+
+def sniff_mime(data):
+ """Return the mime its first bytes prove (PDF, PNG, JPEG, WEBP), or None."""
+ if data.startswith(b"%PDF-"):
+ return INBOUND_PDF_MIME
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "image/png"
+ if data.startswith(b"\xff\xd8\xff"):
+ return "image/jpeg"
+ if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ return None
+
+
+def fetch_media(ref, *, limit):
+ """Fetch an inbound attachment from Telnyx as (bytes, mime), at most `limit` bytes."""
+ url = ref.get("url") if isinstance(ref, dict) else None
+ if not isinstance(url, str) or not url.strip():
+ raise MediaRefusal("no_url")
+ if not _media_host(url):
+ raise MediaRefusal("host")
+ key = os.environ.get("TELNYX_API_KEY") or ""
+ if not key:
+ raise MediaRefusal("not_configured")
+ req = request.Request(url, headers={"Authorization": "Bearer " + key}, method="GET")
+ chunks, total = [], 0
+ try:
+ with _open_media(req, MEDIA_TIMEOUT_S) as response:
+ if not 200 <= getattr(response, "status", 200) < 300:
+ raise MediaRefusal("fetch")
+ declared = response.headers.get("Content-Length") if response.headers else None
+ if declared and declared.isdigit() and int(declared) > limit:
+ raise MediaRefusal("too_large")
+ while True:
+ chunk = response.read(MEDIA_CHUNK)
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > limit:
+ raise MediaRefusal("too_large")
+ chunks.append(chunk)
+ except MediaRefusal:
+ raise
+ except Exception:
+ # A provider exception can carry the URL or the key: only the reason leaves here.
+ raise MediaRefusal("fetch") from None
+ data = b"".join(chunks)
+ mime = sniff_mime(data)
+ if mime is None:
+ raise MediaRefusal("bytes")
+ return data, mime
+
+
+def read_inbound(media, *, reads_images):
+ """Return (attachments, refusal) for a readable attachment; refusals happen before any fetch when they can."""
+ refusal = media_refusal(media)
+ if refusal:
+ return None, refusal
+ image = media["kind"] == "image"
+ if image and not reads_images:
+ return None, "photo"
+ limit = INBOUND_IMAGE_LIMIT if image else INBOUND_PDF_LIMIT
+ if media["size"] is not None and media["size"] > limit:
+ return None, "too_large"
+ try:
+ data, mime = fetch_media(media["ref"], limit=limit)
+ if (mime in INBOUND_IMAGE_MIMES) != image:
+ raise MediaRefusal("bytes")
+ except MediaRefusal as exc:
+ # The log names the reference's shape keys only, never its URL or id.
+ print(json.dumps({"kind": "whatsapp_media_refused", "reason": exc.reason,
+ "media": media["kind"], "keys": sorted(media["ref"])}))
+ return None, "too_large" if exc.reason == "too_large" else "unreadable"
+ filename = media["filename"] or ("photo" + {"image/png": ".png", "image/webp": ".webp"}.get(
+ mime, ".jpg") if image else "document.pdf")
+ return [{"kind": media["kind"], "mime": mime, "filename": filename, "data": data,
+ "caption": media["caption"]}], None
diff --git a/api/tickets.py b/api/tickets.py
index b7f29863f779157ec573d1e769c189b7853ed568..e656384f1df2db89d9f67ecbe841a04b984f35e9 100644
--- a/api/tickets.py
+++ b/api/tickets.py
@@ -34,7 +34,8 @@ _FIELD_SPECS = (
def _utc(value=None):
- value = value if value is not None else dt.datetime.now(dt.timezone.utc)
+ from core import write_execution
+ value = value if value is not None else write_execution.utcnow()
if isinstance(value, str):
value = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
return value.replace(tzinfo=dt.timezone.utc) if value.tzinfo is None else value.astimezone(dt.timezone.utc)
diff --git a/api/whatsapp_door.py b/api/whatsapp_door.py
index c0fa465a86646d877ae7764d28d6e7e368f4b7c1..b7d216a452f6657b3c6960fa5fa6b1dfb4151257 100644
--- a/api/whatsapp_door.py
+++ b/api/whatsapp_door.py
@@ -26,20 +26,85 @@ PENDING_KEY = "whatsapp_pending_delete"
PING_LEDGER_KEY = "whatsapp_ping_ledger"
PING_CAP = 250
PING_WINDOW_S = 86400
-REGISTRATION = ("This number is not connected to Loopable yet. In Loopable, open Connectors "
- "and connect WhatsApp with this number.")
+# whatsapp_signup.connect_hint appends where to connect; this file carries no copy of it.
+REGISTRATION = "This number is not connected to Loopable yet."
UNAVAILABLE = "The Loopable assistant is not available right now. Try again in a few minutes."
-UNSUPPORTED = "I can read typed messages only. Please type your question."
+# R61: a voice note hears this. R99: photos and PDFs are read, other files hear MEDIA_ACCEPTS.
+UNSUPPORTED = "I cannot listen to voice notes. Please type your question."
+MEDIA_ACCEPTS = "I can read typed messages, photos up to 5 MB and PDFs up to 10 MB."
+MEDIA_ACCEPTS_NO_PHOTO = "I can read typed messages and PDFs up to 10 MB."
+PHOTO_TEXT_ONLY = "I cannot read photos yet. Type what it shows, or send it as a PDF."
+MEDIA_UNREADABLE = "I could not open that file. Please send it again."
+MEDIA_QUESTION = "What does this file show?"
CANCELLED = "Nothing was deleted."
+# R100: a held change. The answered-turn path must not reach these names (verify_loopy_tools rebuild).
+CHANGE_CANCELLED = "Nothing was changed."
+CHANGE_EXPIRED = "That change expired. Ask again to make it."
+CHANGE_PROMPT = "Reply YES to make this change. Any other reply cancels it."
+PENDING_TTL_S = 900
STOPPED = "You will not get alerts on WhatsApp anymore. Reply START to turn them back on."
STARTED = "Alerts on WhatsApp are on again."
FILE_TOO_LARGE = "This file is too large to send here. Open it in Loopable."
+FILE_NOT_SENDABLE = "WhatsApp cannot carry this kind of file. Open it in Loopable."
class WhatsAppDoorRefusal(ValueError):
pass
+def _file_route(item):
+ """Return image, document, too_large or unsupported for one file the turn made."""
+ mime = item.get("mime")
+ size = item.get("size")
+ if mime in telnyx_whatsapp.IMAGE_MIMES:
+ limit, route = telnyx_whatsapp.IMAGE_LIMIT, "image"
+ elif mime in telnyx_whatsapp.DOCUMENT_MIMES:
+ limit, route = telnyx_whatsapp.DOCUMENT_LIMIT, "document"
+ else:
+ return "unsupported"
+ # An unknown size is treated as over the limit: the file still arrives as its link.
+ if isinstance(size, bool) or not isinstance(size, (int, float)) or size > limit:
+ return "too_large"
+ return route
+
+
+def _artifact_links(rt, username, phone, files, made, *, now, mint):
+ """Resolve owned active frozen rows before issuing any C7 link."""
+ try:
+ artifacts = import_module("assistant_artifacts")
+ except ImportError:
+ return []
+ try:
+ share = import_module("artifact_share") if mint else None
+ except ImportError:
+ share = None
+ ids, links = [], []
+ for artifact_id in made + [item.get("artifactId") for item in files]:
+ if not isinstance(artifact_id, str) or not artifact_id or artifact_id in ids:
+ continue
+ ids.append(artifact_id)
+ try:
+ row = artifacts.get(rt, username, artifact_id)
+ except Exception:
+ continue
+ if (not isinstance(row, dict) or row.get("id") != artifact_id
+ or row.get("status") != "active"
+ or row.get("kind") not in {"snapshot", "pdf", "xlsx", "image"}
+ or not row.get("frozen_at")):
+ continue
+ link = loopy_links.artifact_link(artifact_id)
+ if share is not None and not share.needs_sign_in(row):
+ try:
+ link = share.signed_link(rt, artifact_id, phone=phone, now=now) or link
+ except Exception as exc:
+ # A revoked row or phone binding must not regain a protected fallback.
+ link = link if isinstance(exc, share.ShareRefused) and exc.link == link else None
+ print(json.dumps({"kind": "whatsapp_signed_link_refused", "error": type(exc).__name__}))
+ if link and link not in links:
+ links.append(link)
+ return links
+
+
def _run_turn():
if RUN_TURN is not None:
return RUN_TURN
@@ -129,7 +194,7 @@ def send_ping(rt, username, ping, *, now=None):
_ping_overflow(rt, username, payload)
return False
- digest = payload.get("digest")
+ digest, record_link = payload.get("digest"), ""
if digest:
count = len(digest)
text = (f"Loopable found {count} items that need attention. "
@@ -151,9 +216,14 @@ def send_ping(rt, username, ping, *, now=None):
kwargs = {"purpose": "ping", "tenant": rt.key, "username": username}
if telnyx_whatsapp.within_window(phone, seconds):
delivery = telnyx_whatsapp.send_text(phone, text, **kwargs)
+ elif ping.get("kind") == "notice":
+ # R101: a notice after the window is the link template. A C22 alert keeps the alert template.
+ delivery = telnyx_whatsapp.send_link_notice(
+ phone, params[0], loopy_links.absolutize_text(record_link) or None,
+ owes="notice", tenant=rt.key, username=username, audit=rt)
else:
delivery = telnyx_whatsapp.send_template(
- phone, telnyx_whatsapp.ping_template(), params, **kwargs)
+ phone, telnyx_whatsapp.ping_template(), params, audit=rt, **kwargs)
return isinstance(delivery, dict) and delivery.get("status") in {"sandbox", "sent"}
@@ -185,15 +255,16 @@ def accept(raw: bytes, signature: str, timestamp: str, *, now=None):
if not isinstance(message_id, str) or not message_id.strip():
raise ValueError("Invalid message fields")
body = payload.get("body", "")
- unsupported = False
- # Only named media types qualify for a reply. Edits and unknown types stay ignored.
- if isinstance(body, dict) and body.get("type") != "text":
- if body.get("type") in ("audio", "image", "video", "document", "sticker"):
- unsupported = True
+ media = telnyx_whatsapp.inbound_media(payload)
+ unsupported = None
+ # Only named media types qualify for a read or a reply. Edits and unknown types stay ignored.
+ if isinstance(body, dict) and body.get("type") != "text" or media is not None:
+ if media is not None:
+ unsupported = telnyx_whatsapp.media_refusal(media)
else:
return None
text = payload.get("text", body)
- if unsupported:
+ if media is not None:
text = ""
elif isinstance(body, dict) and not isinstance(text, str):
text = body["text"]["body"]
@@ -216,7 +287,10 @@ def accept(raw: bytes, signature: str, timestamp: str, *, now=None):
_store.update(SEEN_KEY, claim)
message = {"messageId": message_id, "phone": phone, "text": text, "at": stamp}
if unsupported:
- message["unsupported"] = True
+ message["unsupported"] = unsupported
+ elif media is not None:
+ # Held in memory for the background turn only: the media URL is never stored or logged.
+ message["media"] = media
if outcome["duplicate"]:
return {**message, "duplicate": True}
@@ -238,9 +312,22 @@ def process(message, *, run_turn=None, append=None, now=None):
_store.update(PENDING_KEY, lambda doc: {p: row for p, row in doc.items() if p != phone})
return whatsapp_signup.handle_unregistered(phone, text, seconds, registration=REGISTRATION)
tenant, username = owner
- if message.get("unsupported"):
+ refusal, attachments = message.get("unsupported"), None
+ if refusal or message.get("media"):
+ try:
+ reads_images = bool(import_module("agent_runtime").reads_images())
+ except ImportError:
+ reads_images = False
+ if not refusal:
+ # The owner lookup above runs first: an unregistered number's file is never fetched.
+ attachments, refusal = telnyx_whatsapp.read_inbound(
+ message["media"], reads_images=reads_images)
+ if refusal:
+ sentence = {"voice": UNSUPPORTED, "photo": PHOTO_TEXT_ONLY,
+ "unreadable": MEDIA_UNREADABLE}.get(refusal) or (
+ MEDIA_ACCEPTS if reads_images else MEDIA_ACCEPTS_NO_PHOTO)
delivery = telnyx_whatsapp.send_reply(
- phone, UNSUPPORTED, tenant=tenant, username=username, now=seconds)
+ phone, sentence, tenant=tenant, username=username, now=seconds)
return {"status": "unsupported", "deliveryStatus": delivery.get("status")}
principal = {"tenant": tenant, "username": username, "also_as": []}
rt = runtime.get_runtime(tenant)
@@ -250,8 +337,9 @@ def process(message, *, run_turn=None, append=None, now=None):
username=username, now=seconds)
return {"status": "code_received", "deliveryStatus": delivery.get("status")}
log = append if append is not None else _append()
- files = []
+ files, made = [], []
runtime_owned = False
+ held_preview = None
kind = "text"
command = text.strip().upper()
@@ -271,24 +359,34 @@ def process(message, *, run_turn=None, append=None, now=None):
confirm = None
cancelled = False
if pending:
+ owned = (pending.get("tenant"), pending.get("username")) == owner
try:
- valid = (pending.get("tenant"), pending.get("username")) == owner and (
- seconds < telnyx_whatsapp._seconds(pending["expiresAt"]))
+ fresh = seconds < telnyx_whatsapp._seconds(pending["expiresAt"])
except (KeyError, TypeError, ValueError, OverflowError):
- valid = False
- if command == "YES" and valid:
+ fresh = False
+ if command == "YES" and owned and fresh:
confirm = pending["id"]
else:
cancelled = True
- if cancelled:
+ if cancelled and pending.get("kind") == "change":
+ if owned:
+ import_module("agent_runtime").cancel(rt, principal, pending["id"])
+ # An expired change runs nothing; YES then hears why, any other reply hears the cancel.
+ reply, status = ((CHANGE_EXPIRED, "expired") if command == "YES" and owned and not fresh
+ else (CHANGE_CANCELLED, "cancelled"))
+ elif cancelled:
reply, status = CANCELLED, "cancelled"
elif not callable(turn):
reply, status = UNAVAILABLE, "unavailable"
else:
# C13: memory and shared conversation context belong to the runtime on every door.
since = datetime.now(timezone.utc).timestamp()
+ # A file goes to the turn with its caption; a text-only turn keeps its old call shape.
result = (turn(rt, principal, "whatsapp", text, confirm=confirm) if confirm is not None
+ else turn(rt, principal, "whatsapp",
+ attachments[0]["caption"] or MEDIA_QUESTION,
+ attachments=attachments) if attachments
else turn(rt, principal, "whatsapp", text))
runtime_owned = confirm is None
if (result.get("status") == "joined" or
@@ -296,58 +394,90 @@ def process(message, *, run_turn=None, append=None, now=None):
return {"status": result["status"]}
if result.get("status") == "stopped":
runtime_owned = True
+ made = [item.get("id") if isinstance(item, dict) else item
+ for item in result.get("artifacts") or []]
try:
file_module = import_module("assistant_files")
except ModuleNotFoundError as exc:
if exc.name != "assistant_files":
raise
else:
- files = [item for item in file_module.created_in_turn(rt, username, since)
- if item.get("mime") == "application/pdf"]
- delete = result.get("pendingDelete")
- if delete:
- expiry = seconds + 600
- if delete.get("expiresAt") is not None:
- expiry = min(expiry, telnyx_whatsapp._seconds(delete["expiresAt"]))
- record = {"id": delete["id"], "summary": clean_reply(delete["summary"]),
+ # Every file the turn made is routed by kind and size below: none is dropped.
+ files = list(file_module.created_in_turn(rt, username, since))
+ # One pending change per number: a held change replaces any earlier one.
+ change = result.get("pendingChange")
+ delete = None if change else result.get("pendingDelete")
+ if change or delete:
+ held_preview = {"pendingChange" if change else "pendingDelete": change or delete,
+ "artifacts": result.get("artifacts") or [],
+ "toolCalls": result.get("toolCalls") or []}
+ held = change or delete
+ expiry = seconds + PENDING_TTL_S
+ if held.get("expiresAt") is not None:
+ expiry = min(expiry, telnyx_whatsapp._seconds(held["expiresAt"]))
+ record = {"id": held["id"], "summary": clean_reply(held["summary"]),
"expiresAt": _iso(expiry), "tenant": tenant, "username": username}
+ if change:
+ record["kind"] = "change"
_store.update(PENDING_KEY, lambda doc: {**doc, phone: record})
- reply, kind, status = "Reply YES to delete " + record["summary"], "confirm", "pending_delete"
+ if change:
+ reply, kind, status = record["summary"] + "\n" + CHANGE_PROMPT, "confirm", "pending_change"
+ else:
+ reply, kind, status = "Reply YES to delete " + record["summary"], "confirm", "pending_delete"
else:
reply = result.get("refused") or result.get("reply") or ""
status = "refused" if result.get("refused") else "answered"
- reply = loopy_links.absolutize_text(str(reply or ""))
+ # C7 URLs come from stored rows and the signer, never from model text.
+ original_reply = str(reply or "")
+ reply = re.sub(r"(?:https?://[^\s<>]*?)?#/artifacts(?:\?[^\s<>]*)?"
+ r"|(?:https?://[^\s<>]*?)?/a/[^\s<>]+", "", str(reply or "")).strip()
+ if not reply and original_reply.strip():
+ reply = "Open Loopable to view this item."
+ reply = loopy_links.absolutize_text(reply)
reply = _omit_unconfigured_links(reply, tenant=tenant, username=username)
reply = clean_reply(reply)
- links = []
- for item in files:
- link = loopy_links.absolutize_text(item.get("link") or "")
- if not link.startswith("https://"):
- link = loopy_links.artifact_link(item.get("artifactId"))
- if link and link not in links:
- links.append(link)
- if any(item["size"] > telnyx_whatsapp.DOCUMENT_LIMIT for item in files):
+ inside = telnyx_whatsapp.within_window(phone, seconds)
+ links = _artifact_links(rt, username, phone, files, made, now=seconds,
+ mint=inside or bool(telnyx_whatsapp.link_template())) if files or made else []
+ routes = [_file_route(item) for item in files]
+ if "unsupported" in routes:
+ reply = FILE_NOT_SENDABLE + ("\n" + reply if reply else "")
+ if "too_large" in routes:
reply = FILE_TOO_LARGE + ("\n" + reply if reply else "")
link = "\n".join(links) or None
if link:
reply = reply.rstrip()
if not reply.endswith(link):
reply += "\n" + link
- if callable(log) and not runtime_owned:
- log(rt, username, {"role": "user", "door": "whatsapp", "kind": "text",
- "text": text, "at": message.get("at") or _iso(seconds)})
- log(rt, username, {"role": "assistant", "door": "whatsapp", "kind": kind,
- "text": reply, "at": _iso(seconds)})
- delivery = telnyx_whatsapp.send_reply(
- phone, reply, tenant=tenant, username=username, now=seconds, link=link)
- if telnyx_whatsapp.within_window(phone, seconds):
- for item in files:
- if item["size"] <= telnyx_whatsapp.DOCUMENT_LIMIT:
- document = telnyx_whatsapp.send_document(
+ if callable(log):
+ if not runtime_owned:
+ log(rt, username, {"role": "user", "door": "whatsapp", "kind": "text",
+ "text": text, "at": message.get("at") or _iso(seconds)})
+ if not runtime_owned or held_preview:
+ log(rt, username, {"role": "assistant", "door": "whatsapp", "kind": "text" if held_preview else kind,
+ "text": reply, "at": _iso(seconds), "payload": held_preview or {}})
+ if not inside:
+ # R101: after the window, one template with a link and never a file. No template mints no link.
+ notice_link = ((links[0] if links else loopy_links.app_link("#/assistant"))
+ if telnyx_whatsapp.link_template() else None)
+ delivery = telnyx_whatsapp.send_link_notice(
+ phone, reply, notice_link, owes="file" if files else "reply",
+ tenant=tenant, username=username, audit=rt)
+ else:
+ delivery = telnyx_whatsapp.send_reply(
+ phone, reply, tenant=tenant, username=username, now=seconds, link=link)
+ for item, route in zip(files, routes):
+ if route == "document":
+ attachment = telnyx_whatsapp.send_document(
phone, item["id"], item["filename"], tenant=tenant,
username=username, now=seconds)
- if document and document.get("status") == "failed":
- delivery = document
+ elif route == "image":
+ attachment = telnyx_whatsapp.send_image(
+ phone, item["id"], tenant=tenant, username=username, now=seconds)
+ else:
+ continue
+ if attachment and attachment.get("status") == "failed":
+ delivery = attachment
return {"status": status, "loggingUnavailable": not callable(log),
"deliveryStatus": delivery.get("status")}
diff --git a/api/whatsapp_identity.py b/api/whatsapp_identity.py
index 3173cd9b8502e21ac6078af19d412f6868facce5..8c782b104e8a64ae03670995f32e2216121d0971 100644
--- a/api/whatsapp_identity.py
+++ b/api/whatsapp_identity.py
@@ -23,6 +23,7 @@ PHONE_TAKEN = "This number is already connected to another Loopable account."
CODE_WRONG = "That code is not right. Check the latest WhatsApp message and try again."
CODE_EXPIRED = "That code has expired. Send a new code."
CODE_UNDELIVERED = "The code could not be delivered to this number."
+COUNTRY_UNAVAILABLE = "WhatsApp cannot send a code to this country."
class WhatsAppRefusal(ValueError):
@@ -41,23 +42,46 @@ def _owns(record, tenant, username):
return isinstance(record, dict) and (record.get("tenant"), record.get("username")) == (tenant, username)
+def _ownership_read(source, key):
+ # HF display reads can fall back to stale data; ownership decisions must raise instead.
+ reader = getattr(source, "_read_strict", None)
+ return reader(key) if callable(reader) else source.get(key, fresh=True)
+
+
def _account(tenant, username):
- record = (users.registry() or {}).get(username)
+ record = (_ownership_read(users.store, "users") or {}).get(username)
if not isinstance(record, dict) or str(record.get("tenant") or "royal-imports") != tenant:
raise WhatsAppRefusal("This account is not available in this workspace.")
return record
def _phone_conflict(phone, tenant, username, index=None):
- index = (_store.get(INDEX_KEY) or {}) if index is None else index
- return phone in index and not _owns(index[phone], tenant, username)
+ index = (_ownership_read(_store, INDEX_KEY) or {}) if index is None else index
+ # The registry proves ownership. An interrupted index write proves no binding.
+ registry = _ownership_read(users.store, "users") or {}
+ caller = registry.get(username)
+ if not isinstance(caller, dict) or str(caller.get("tenant") or "royal-imports") != tenant:
+ raise WhatsAppRefusal("This account is not available in this workspace.")
+ entry = index.get(phone)
+ if isinstance(entry, dict) and not _owns(entry, tenant, username):
+ holder = registry.get(entry.get("username"))
+ if (isinstance(holder, dict)
+ and str(holder.get("tenant") or "royal-imports") == entry.get("tenant")
+ and isinstance(holder.get("whatsapp"), dict)
+ and holder["whatsapp"].get("phone") == phone):
+ return True
+ # A crash after the account write must also remain exclusive if its index is missing.
+ return any(isinstance(record, dict) and isinstance(record.get("whatsapp"), dict)
+ and record["whatsapp"].get("phone") == phone
+ and (str(record.get("tenant") or "royal-imports"), holder) != (tenant, username)
+ for holder, record in registry.items())
def lookup(phone_e164):
- entry = (_store.get(INDEX_KEY) or {}).get(phone_e164)
+ entry = (_ownership_read(_store, INDEX_KEY) or {}).get(phone_e164)
if not isinstance(entry, dict):
return None
- record = (users.registry() or {}).get(entry.get("username"))
+ record = (_ownership_read(users.store, "users") or {}).get(entry.get("username"))
if not isinstance(record, dict):
return None
whatsapp = record.get("whatsapp")
@@ -74,21 +98,16 @@ def bind(tenant, username, phone):
value = {"phone": phone, "verifiedAt": stamp, "optOutPings": False}
def reserve(index):
- # Check within the read-modify-write so concurrent accounts cannot claim one phone.
+ # Hold the index lock through the account write, so a live bind is never reclaimed.
if _phone_conflict(phone, tenant, username, index):
raise WhatsAppRefusal(PHONE_TAKEN)
+ users.set_whatsapp(username, value)
+ index = {p: row for p, row in index.items()
+ if p == phone or not _owns(row, tenant, username)}
index[phone] = {"tenant": tenant, "username": username, "at": stamp}
return index
_store.update(INDEX_KEY, reserve)
- # Lookup confirms both documents, so a partial write cannot authorize an inbound sender.
- users.set_whatsapp(username, value)
-
- def drop_old(index):
- return {p: row for p, row in index.items()
- if p == phone or not _owns(row, tenant, username)}
-
- _store.update(INDEX_KEY, drop_old)
return value
@@ -114,6 +133,23 @@ def _hash(salt, code):
return hmac.new(bytes.fromhex(salt), code.encode("utf-8"), hashlib.sha256).hexdigest()
+def _delivery_sentence(delivery, fallback=CODE_UNDELIVERED):
+ # Known provider codes become short user copy; never expose raw provider errors.
+ if isinstance(delivery, dict) and str(delivery.get("metaCode")) == "130497":
+ return COUNTRY_UNAVAILABLE
+ return fallback
+
+
+def _pending_delivery_sentence(pending, tenant, username):
+ provider_id = pending.get("providerId")
+ messages = (_store.get(telnyx_whatsapp.OUTBOX_KEY) or {}).get("messages") or []
+ for entry in reversed(messages):
+ if (isinstance(entry, dict) and provider_id and entry.get("providerId") == provider_id
+ and _owns(entry, tenant, username) and entry.get("purpose") == "auth_code"):
+ return _delivery_sentence(entry)
+ return CODE_UNDELIVERED
+
+
def start(tenant, username, phone, *, now=None, sender=None):
now = time.time() if now is None else now
phone = normalize_phone(phone)
@@ -145,7 +181,7 @@ def start(tenant, username, phone, *, now=None, sender=None):
_store.update(CODES_KEY, lambda doc: {
p: row for p, row in doc.items()
if p != phone or row.get("codeHash") != pending["codeHash"]})
- raise WhatsAppRefusal("The code could not be sent. Try again.")
+ raise WhatsAppRefusal(_delivery_sentence(delivery, "The code could not be sent. Try again."))
provider_id = delivery.get("providerId") if isinstance(delivery, dict) else None
if provider_id:
# status() reads the outbox by this id, so a later refusal can reach the caller.
@@ -211,7 +247,8 @@ def status(tenant, username, *, now=None):
return {"state": "locked", "phone": phone, "lockedUntil": pending["lockedUntil"],
"message": _lock_sentence(pending, now)}
if pending["expiresAt"] <= now:
- return {"state": "none"}
+ return {"state": "none", "phone": phone, "message": CODE_EXPIRED}
if telnyx_whatsapp.delivery_status(pending.get("providerId")) == "failed":
- return {"state": "undelivered", "phone": phone, "message": CODE_UNDELIVERED}
+ return {"state": "undelivered", "phone": phone,
+ "message": _pending_delivery_sentence(pending, tenant, username)}
return {"state": "pending", "phone": phone, "expiresAt": pending["expiresAt"]}
diff --git a/api/whatsapp_signup.py b/api/whatsapp_signup.py
index 8580966a1122c601116c45f930119dd1294fb74f..f4fe97863a86fcd2419461933f50705fb5cb9db4 100644
--- a/api/whatsapp_signup.py
+++ b/api/whatsapp_signup.py
@@ -26,6 +26,25 @@ PURPOSE = "whatsapp_join_v1"
TOKEN_RE = re.compile(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}", re.ASCII)
INVITE_FIELDS = ("tenant", "role", "bus", "modules", "invitedBy", "expiresAt")
WAITLIST = "Thanks. We saved your request and will get back to you."
+# The Contact section of the Connectors page holds the WhatsApp card; verify_voice_control_plane pins both.
+CONNECT_FRAGMENT = "#/connectors?section=contact"
+CONNECT_STEP = "In Loopable, open Connectors and press Connect on the WhatsApp card."
+ALREADY_A_USER = "Already use Loopable?"
+
+
+def connect_hint():
+ """Say where to connect WhatsApp, with the sign-in link when an HTTPS base is configured."""
+ link = loopy_links.app_link(CONNECT_FRAGMENT)
+ # The link ends the reply so no punctuation joins the URL.
+ return CONNECT_STEP if link is None else CONNECT_STEP + " Sign in here: " + link
+
+
+def registration_reply(registration):
+ return registration + " " + connect_hint()
+
+
+def waitlist_reply():
+ return WAITLIST + " " + ALREADY_A_USER + " " + connect_hint()
def token_hash(token):
@@ -224,7 +243,7 @@ def handle_unregistered(phone, text, now=None, *, registration=None):
isinstance(record, dict) and isinstance(record.get("whatsapp"), dict)
and record["whatsapp"].get("phone") == phone
for record in (users.registry() or {}).values()):
- reply, digest, status = registration, "registration", "unregistered"
+ reply, digest, status = registration_reply(registration), "registration", "unregistered"
else:
def save(rows):
rows = rows if isinstance(rows, list) else []
@@ -234,7 +253,7 @@ def handle_unregistered(phone, text, now=None, *, registration=None):
return rows
_store.update(REQUESTS_KEY, save)
- reply, digest, status = WAITLIST, "waitlist", "unregistered"
+ reply, digest, status = waitlist_reply(), "waitlist", "unregistered"
if _reserve_reply(phone, seconds, digest):
telnyx_whatsapp.send_reply(phone, reply, now=seconds)
return {"status": status}
diff --git a/platform/aios_grid.py b/platform/aios_grid.py
index 11a78e55ca859c3f26b14f1ab587ec98d85ab069..b05022510043bbd07c474785ede1d7a2daebc476 100644
--- a/platform/aios_grid.py
+++ b/platform/aios_grid.py
@@ -1918,6 +1918,9 @@ def rows_from_pool(pool_rows, fields=None, overlays=None, derived=None):
v = saved[k]
# D-153 — three roundings, not two: text/status/date pass through verbatim, currency
# and pct keep two decimals (`_round2`), everything else stays a whole number.
+ if field["type"] == "int" and (field.get("format") or {}).get("decimals", 0) > 0:
+ row[k] = v
+ continue
row[k] = v if field["type"] in {"text", "status", "date"} else (
_round2(v) if field["type"] in {"currency", "pct"} else _round(v))
for field in overlay_fields:
diff --git a/platform/aios_grid_fields.json b/platform/aios_grid_fields.json
index ae786ab87813f7144d2f586a316f9636b622339e..fc3a48dec3b9404f2769d4325dfd2f6a29fe3b9f 100644
--- a/platform/aios_grid_fields.json
+++ b/platform/aios_grid_fields.json
@@ -327,7 +327,24 @@
"source": "overlay",
"default": false,
"description": "Your notes on this customer. Saved in this app only, visible only to you."
- }
+ },
+ {"key": "source_notes", "label": "Source notes", "type": "text", "source": "odoo", "default": false, "description": "The customer notes recorded in Odoo."},
+ {"key": "company_name", "label": "Company name", "type": "text", "source": "odoo", "default": false, "description": "The customer's commercial company name in Odoo."},
+ {"key": "commercial_partner", "label": "Commercial entity", "type": "text", "source": "odoo", "default": false, "description": "The commercial account this customer belongs to."},
+ {"key": "customer_rank", "label": "Customer rank", "type": "int", "source": "odoo", "default": false, "description": "The customer's rank recorded in Odoo."},
+ {"key": "doing_business_as", "label": "Doing business as", "type": "text", "source": "odoo", "default": false, "description": "The doing business as name assigned in Odoo."},
+ {"key": "invoice_age_limit", "label": "Invoice age limit on", "type": "checkbox", "source": "odoo", "default": false, "description": "Whether Odoo enforces the maximum invoice age."},
+ {"key": "reminders", "label": "Reminders", "type": "text", "source": "odoo", "default": false, "description": "The customer's follow-up reminder setting in Odoo."},
+ {"key": "is_company", "label": "Company", "type": "checkbox", "source": "odoo", "default": false, "description": "Whether Odoo identifies this customer as a company."},
+ {"key": "max_invoice_age", "label": "Max invoice age", "type": "int", "source": "odoo", "default": false, "description": "The maximum invoice age in days configured in Odoo."},
+ {"key": "online_payment", "label": "Online payment", "type": "checkbox", "source": "odoo", "default": false, "description": "Whether online payment is enabled for this customer."},
+ {"key": "parent_company", "label": "Related company", "type": "text", "source": "odoo", "default": false, "description": "The customer's parent company in Odoo."},
+ {"key": "sales_warning", "label": "Sales warning", "type": "text", "source": "odoo", "default": false, "description": "The sales warning setting recorded in Odoo."},
+ {"key": "supplier_rank", "label": "Supplier rank", "type": "int", "source": "odoo", "default": false, "description": "The supplier rank recorded on this customer in Odoo."},
+ {"key": "sales_team", "label": "Sales team", "type": "text", "source": "odoo", "default": false, "description": "The sales team assigned to this customer in Odoo."},
+ {"key": "address_type", "label": "Address type", "type": "text", "source": "odoo", "default": false, "description": "The contact address type recorded in Odoo."},
+ {"key": "timezone", "label": "Timezone", "type": "text", "source": "odoo", "default": false, "description": "The customer's timezone recorded in Odoo."},
+ {"key": "hubspot_company_id", "label": "HubSpot company ID", "type": "text", "source": "odoo", "default": false, "description": "The HubSpot company identifier linked in Odoo."}
],
"_product_comment": "ADDITIVE, wave 15 C-TOPIC. The PRODUCT table's field contract. Kept as a SEPARATE top-level key rather than restructuring `fields` into {customer_data, product_data}: both existing readers (aios_grid._load_fields, aios-web/api/main.py) index doc['fields'] directly, and reshaping that mid-wave would break the embed for a cosmetic gain. The keyed shape can arrive when both readers move in ONE commit; until then this is the product half and `fields` is the customer half.",
"_product_removed_buy_now": "OWNER, 2026-08-03: 'Buy signal' (key buy_now, a select of Buy now / OK) is NO LONGER A PRESET FIELD. It never earned one: it is a formula over two columns that are both still right here, and the platform has a formula field type for exactly that. THE FORMULA, which reproduces the retired column row for row (modules/product_data.validate proves the equivalence, and goes red if it ever stops holding): IF({lead_days} > 0, IF({dos} < {lead_days}, \"Buy now\", \"OK\"), \"\") . Every branch matches the old server rule, including the blanks - the formula engine refuses a comparison against a blank rather than coercing it to 0, so a SKU with no days-of-supply or no lead time comes out empty, which is 'we do not know' and not 'you are fine'. NOTE the column is still COMPUTED in product_data.pool(): it ships nowhere (rows_from_pool projects strictly through this contract, so no Field means no cell on the wire) and exists only as validate()'s oracle. A formula field is PER-USER, so nothing shared may filter on it - the Buy list view filters on dos/lead_days directly (_seed_wave17).",
@@ -352,6 +369,23 @@
"default": false,
"description": "The Odoo product.product id, the key every Odoo document joins on. Carried on the row rather than derived, because a product's pid is a CRC32 of its SKU and the id cannot be recovered from it."
},
+ {
+ "key": "product_tmpl_id",
+ "label": "Template",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The product template name. Products sharing a SKU use the first product record."
+ },
+ {
+ "key": "volume",
+ "label": "Volume",
+ "type": "int",
+ "format": {"decimals": 4},
+ "source": "odoo",
+ "default": false,
+ "description": "Volume per unit. Products sharing a SKU use the first product record."
+ },
{
"key": "product",
"label": "Product",
@@ -654,6 +688,20 @@
"source": "odoo",
"description": "Units in stock. Consolidated: one physical warehouse, not brand-tagged, so every caller sees the same company-wide figure, a BU-scoped one included."
},
+ {
+ "key": "available",
+ "label": "Available",
+ "type": "int",
+ "source": "odoo",
+ "description": "Units in stock minus units reserved for orders."
+ },
+ {
+ "key": "forecasted",
+ "label": "Forecasted",
+ "type": "int",
+ "source": "odoo",
+ "description": "Units in stock plus inbound minus outbound."
+ },
{
"key": "fba",
"label": "FBA",
diff --git a/platform/core/alerts.py b/platform/core/alerts.py
index dbd45cba034b0a8b482d00719d9366ec5ab2a972..e27b368328b17e4814d68f77e135ef44aa25d068 100644
--- a/platform/core/alerts.py
+++ b/platform/core/alerts.py
@@ -80,7 +80,8 @@ def _publish(owner, item, st):
def _now_iso():
"""UTC, WITH the offset — `2026-08-05T09:41:07.123456+00:00`. See the module note (D-18)."""
- return _dt.datetime.now(_dt.timezone.utc).isoformat()
+ from core import write_execution
+ return write_execution.utcnow().isoformat()
def _st(st):
@@ -232,7 +233,7 @@ def _queue(rec, pids, labels, st=None):
def notify(owner, label, *, topic='automation', key='', row_id='', detail='', actor='', st=None,
- replace=False, target=None):
+ replace=False, target=None, inbox=None):
"""⭐ WAVE 23 (C6) — put ONE notification in a named user's inbox, for a producer that is not
a view-alert evaluation.
@@ -263,10 +264,13 @@ def notify(owner, label, *, topic='automation', key='', row_id='', detail='', ac
English.
⚠ Blank is a legitimate value and means *"no person did this"*, NOT "unknown". The client falls
back BY KIND rather than to an empty From column, so an automation never borrows a human's name.
+
+ `inbox` (S72-T27) is an agent message's C6 payload. It rides to the sink only and never
+ enters the compatibility row or the returned item.
"""
items = notify_many([{'owner': owner, 'label': label, 'topic': topic, 'key': key,
'row_id': row_id, 'detail': detail, 'actor': actor,
- 'replace': replace, 'target': target}], st=st)
+ 'replace': replace, 'target': target, 'inbox': inbox}], st=st)
return items[0] if items else None
@@ -295,16 +299,17 @@ def notify_many(entries, st=None):
item['detail'] = detail
if isinstance(entry.get('target'), dict):
item['target'] = dict(entry['target'])
- queued.append((owner, replace, item))
+ sink_extra = {'inbox': dict(entry['inbox'])} if isinstance(entry.get('inbox'), dict) else {}
+ queued.append((owner, replace, item, sink_extra))
if not queued:
return []
# Cutover drops old unread rows before this batch writes fresh compatibility rows.
- for owner, _replace, item in queued:
- _publish(owner, item, st)
+ for owner, _replace, item, sink_extra in queued:
+ _publish(owner, {**item, **sink_extra}, st)
def _apply(data):
owners = set()
- for owner, replace, item in queued:
+ for owner, replace, item, _extra in queued:
box = list(data.get(owner) or [])
if replace:
box = [n for n in box if (n.get('topic'), n.get('alertId')) !=
@@ -323,7 +328,7 @@ def notify_many(entries, st=None):
return data
_st(st).update(NOTIFICATIONS_KEY, _apply, flush='async')
- return [item for _owner, _replace, item in queued]
+ return [item for _owner, _replace, item, _extra in queued]
def inbox(user, st=None, limit=100):
diff --git a/platform/core/connector_spec.py b/platform/core/connector_spec.py
index d4038227e3165d6f49593933c75021dedbb3e8e1..dc1f0c54bcf5fa6eb0d620939553cc32708c63ae 100644
--- a/platform/core/connector_spec.py
+++ b/platform/core/connector_spec.py
@@ -169,7 +169,11 @@ def _label(col):
"""`amazon_order_id` -> `Amazon order id`. ⛔ THE SAME RULE BOTH CONNECTORS ALREADY USE
(`amazon_relational._label`, `meta_relational._label`), copied because `core` cannot import
them. The parity gate holds the two spellings together."""
- return col.replace("_", " ").strip().capitalize()
+ acronyms = {"sku", "asin", "fnsku", "id", "b2b"}
+ words = col.replace("_", " ").strip().split()
+ return " ".join(word.upper() if word.lower() in acronyms else
+ word.capitalize() if index == 0 else word.lower()
+ for index, word in enumerate(words))
def edges_for(key):
diff --git a/platform/core/external_oauth.py b/platform/core/external_oauth.py
index c84a44c7cc7fa0d7217c32b4907b4e7ac0d4bf3d..d92197dc7deefff0a7f59cebbb166a3a7a2a2ff4 100644
--- a/platform/core/external_oauth.py
+++ b/platform/core/external_oauth.py
@@ -634,7 +634,7 @@ def _live_permission_user(username: str, tenant: str) -> dict:
or any(not isinstance(field, str) for field in entry["hiddenFields"])):
raise ExternalOAuthAuthError(AUTH_ERROR)
modules = record.get("modules", "all")
- if modules != "all" and (not isinstance(modules, (list, tuple))
+ if modules != "all" and (not isinstance(modules, (list, tuple)) or not modules
or any(not isinstance(key, str) or not key for key in modules)):
raise ExternalOAuthAuthError(AUTH_ERROR)
public = users._public(username, record)
diff --git a/platform/core/perm_scope.py b/platform/core/perm_scope.py
index ce20d1a263326b68eb5d1e9480b4daa336a425c5..78ecd21c20ac462c0df14cdc79f5157cc71f84a0 100644
--- a/platform/core/perm_scope.py
+++ b/platform/core/perm_scope.py
@@ -219,7 +219,19 @@ def nav_may_open(user, key, st=None):
def assistant_entry(user, module):
- """Resolve an effective database grant without losing its stored row or field restrictions."""
+ """The explicit database grant an Assistant snapshot may rely on, else ``None``.
+
+ The interactive application retains an admin break-glass path and a temporary legacy-grant
+ compatibility path. Neither is an answer at the Assistant's app-stored data boundary:
+ that reader must be able to name the migrated grant that admitted a database. In particular,
+ a store-outage admin identity with no ``perms`` document is not an unresolved permission that
+ may be widened into data access.
+
+ ⭐ S67-T34 / D-276: ONE NAMED EXCEPTION, the grant the NAVIGATION uses. For the two registry
+ topics in ``ASSISTANT_NAV_TOPICS`` an administrator account is admitted unfiltered (unless
+ explicitly unticked), because ``nav_may_open`` leg 1 opens them to it; the AI list must equal
+ the nav (R33). See the comment at that leg for why the outage identity no longer reaches it.
+ """
e = entry(user, module)
# T55: the AI list and read use the same named admin grant for the Data topics.
# Return the complete entry so hidden fields and row restrictions survive admission.
@@ -227,11 +239,8 @@ def assistant_entry(user, module):
if isinstance(e, dict) and e.get('access') is False:
return None
return dict(e) if isinstance(e, dict) else {'access': True, 'filter': None}
- if module in ASSISTANT_NAV_TOPICS:
- if not may_read(user, module):
- return None
- return e if e is not None else {'access': True, 'filter': None}
- if (isinstance(e, dict) and bool(e.get('access', True)) and may_access(user, module)):
+ if (is_migrated(user) and isinstance(e, dict)
+ and bool(e.get('access', True)) and may_access(user, module)):
return e
# ⭐⭐ S67-T34 / D-276 / R26: THE ADMINISTRATOR THE NAVIGATION ADMITS. `nav_may_open` leg 1
# opens every registry topic to an administrator, and `_clean_perms` writes no per-topic
@@ -241,10 +250,12 @@ def assistant_entry(user, module):
# answer is the grant the nav already uses, admitted for exactly these topics: an account
# whose ROLE is admin, minus an explicit `access: false` (narrower than the nav, never wider).
# Unfiltered, as the nav's break-glass is.
- # ⚠ THE STORE-OUTAGE IDENTITY is no longer built by `deps._user_for`
+ # ⚠ THE STORE-OUTAGE IDENTITY the docstring names is no longer built by `deps._user_for`
# (it admits a stored record or the QA runner, nothing else), so the role is read off a
# stored account here. If a synthetic admin identity is ever reintroduced, it must be kept
# out of this leg.
+ # ⛔ NOT A MEMBER. A non-administrator still needs the explicit migrated grant above, so a
+ # user without it does not see the database (the NC).
return None
@@ -1855,11 +1866,6 @@ def derive_pool_scope(user, module):
if perms.is_admin(user):
return None, None
team_id, agent = _derive_from_filter(user, module)
- # Legacy account scope remains binding even when a stored filter adds another restriction.
- if not is_migrated(user):
- legacy_team = perms.scope_team_id(user)
- team_id = legacy_team if legacy_team is not None else team_id
- agent = perms.scope_agent(user) or agent
if team_id is None and module not in BU_FILTERABLE_MODULES:
team_id = perms.scope_team_id(user)
return team_id, agent
@@ -1950,6 +1956,287 @@ def _group_dba_team(group):
return None
+# ── S72-T61 / R114: THE ACCESS LIMIT, DESCRIBED FOR THE READER ────────────────────────────────
+#: R108 (c): a limit this reader may not see in full names no field and no value.
+SCOPE_LIMIT_HIDDEN = 'Limited by your access'
+#: The label of the legacy `bus` scope, which has no field of its own.
+SCOPE_LIMIT_BU_LABEL = 'Business Unit'
+#: The legacy `agent` scope shapes only the customer pool (`deps` keys the product pool by team).
+_LEGACY_AGENT_MODULES = frozenset({'customer_data'})
+#: The registry topics whose POOL carries the legacy `bus` scope (`derive_pool_scope` callers).
+_LEGACY_POOL_MODULES = frozenset({'customer_data', 'product_data'})
+#: Most values a phrase lists before it says how many more there are.
+_SCOPE_MAX_VALUES = 3
+
+_SCOPE_OP_WORDS = {
+ 'eq': 'is', 'neq': 'is not', 'contains': 'contains', 'doesNotContain': 'does not contain',
+ 'gt': 'is more than', 'gte': 'is at least', 'lt': 'is less than', 'lte': 'is at most',
+}
+_SCOPE_VALUE_FREE = {'isEmpty': 'is empty', 'isNotEmpty': 'is not empty'}
+_SCOPE_MULTI_WORDS = {'isAnyOf': ('is', 'is'), 'isNoneOf': ('is not', 'is none of'),
+ 'hasAnyOf': ('has', 'has any of'), 'hasAllOf': ('has', 'has all of'),
+ 'hasNoneOf': ('does not have', 'has none of')}
+
+
+def _scope_names_field(col, hidden, by_key):
+ """May a phrase name `col`? Only a column the reader can see, never a hidden one."""
+ return col in by_key and col not in hidden
+
+
+def _scope_values(vals, last_word):
+ vals = [v for v in vals if v]
+ if not vals:
+ return None
+ shown = vals[:_SCOPE_MAX_VALUES]
+ more = len(vals) - len(shown)
+ if more:
+ return ', '.join(shown) + f' and {more} more'
+ if len(shown) == 1:
+ return shown[0]
+ return ', '.join(shown[:-1]) + f' {last_word} ' + shown[-1]
+
+
+def _scope_leaf_phrase(node, hidden, by_key):
+ """One leaf as plain words, or None when it cannot be said without naming too much."""
+ col = node.get('colId')
+ if not isinstance(col, str) or not _scope_names_field(col, hidden, by_key):
+ return None
+ if node.get('rhs') is not None or (node.get('dateMode') or 'exact') != 'exact':
+ return None
+ label = str(by_key[col].get('label') or col).strip() or col
+ op = node.get('op')
+ if op in _SCOPE_VALUE_FREE:
+ return f'{label} {_SCOPE_VALUE_FREE[op]}'
+ if op in _SCOPE_MULTI_WORDS:
+ raw = node.get('values')
+ vals = [str(v).strip() for v in raw] if isinstance(raw, list) else []
+ one, many = _SCOPE_MULTI_WORDS[op]
+ joined = _scope_values(vals, 'or' if op in ('isAnyOf', 'hasAnyOf') else 'and')
+ if joined is None:
+ return None
+ return f'{label} {one if len([v for v in vals if v]) == 1 else many} {joined}'
+ if op == 'between':
+ lo, hi = str(node.get('value') or '').strip(), str(node.get('value2') or '').strip()
+ return f'{label} is between {lo} and {hi}' if lo and hi else None
+ if op in _SCOPE_OP_WORDS:
+ val = str(node.get('value') or '').strip()
+ return f'{label} {_SCOPE_OP_WORDS[op]} {val}' if val else None
+ return None
+
+
+def _scope_node_phrase(node, hidden, by_key, outer=False):
+ """A leaf or a group as plain words, or None. A group with one unsayable child is unsayable.
+
+ `outer`: the group is the whole limit, so it needs no parentheses of its own.
+ """
+ if not isinstance(node, dict):
+ return None
+ if isinstance(node.get('children'), list):
+ conj = 'or' if node.get('conj') == 'or' else 'and'
+ said = [_scope_node_phrase(c, hidden, by_key) for c in node['children']]
+ if not said or any(s is None for s in said):
+ return None
+ if len(said) == 1:
+ return said[0]
+ joined = f' {conj} '.join(said)
+ return joined if outer else '(' + joined + ')'
+ return _scope_leaf_phrase(node, hidden, by_key)
+
+
+def _scope_leaf_row(node, hidden, by_key):
+ """One sayable leaf as a reader-safe row, or None exactly when `_scope_leaf_phrase` refuses."""
+ if _scope_leaf_phrase(node, hidden, by_key) is None:
+ return None
+ col = node['colId']
+ field = by_key[col]
+ row = {'field': col, 'label': str(field.get('label') or col).strip() or col,
+ 'op': node['op'], 'type': str(field.get('type') or 'text')}
+ op = node['op']
+ if op in _SCOPE_MULTI_WORDS:
+ row['values'] = [str(v).strip() for v in node.get('values') or () if str(v).strip()]
+ elif op == 'between':
+ row['value'] = str(node.get('value') or '').strip()
+ row['value2'] = str(node.get('value2') or '').strip()
+ elif op not in _SCOPE_VALUE_FREE:
+ row['value'] = str(node.get('value') or '').strip()
+ return row
+
+
+#: Field types whose operator select offers `isAnyOf` (`filter-kit/ops.ts::opsForType`).
+#: `multiselect` is absent on purpose: its cell is a set, and `eq` there means "is exactly".
+_SCOPE_ANY_OF_TYPES = frozenset({'status', 'select', 'user'})
+
+
+def _scope_any_of_row(kids):
+ """`or` rows that are all equality leaves on one any-of field, as ONE `isAnyOf` leaf, or None.
+
+ Display only: `eq a or eq b` and `isAnyOf [a, b]` select the same rows on a single-valued
+ field, and the filter panel says the second as one normal row.
+ """
+ if len(kids) < 2 or not all(isinstance(k, dict) and 'field' in k for k in kids):
+ return None
+ first = kids[0]
+ if first.get('type') not in _SCOPE_ANY_OF_TYPES:
+ return None
+ values = []
+ for kid in kids:
+ if kid['field'] != first['field'] or kid.get('type') != first.get('type'):
+ return None
+ if kid['op'] == 'eq':
+ got = [kid.get('value')]
+ elif kid['op'] == 'isAnyOf':
+ got = kid.get('values') or []
+ else:
+ return None
+ values.extend(v for v in got if v and v not in values)
+ if not values:
+ return None
+ return {'field': first['field'], 'label': first['label'], 'op': 'isAnyOf',
+ 'type': first['type'], 'values': values}
+
+
+def _scope_or_rows(kids):
+ """An `or` group of rows: one `isAnyOf` leaf when `_scope_any_of_row` allows, else the group."""
+ return _scope_any_of_row(kids) or {'conj': 'or', 'children': kids}
+
+
+def _scope_node_row(node, hidden, by_key):
+ """A leaf or group as a reader-safe row, or None exactly when `_scope_node_phrase` refuses."""
+ if _scope_node_phrase(node, hidden, by_key) is None:
+ return None
+ if isinstance(node.get('children'), list):
+ kids = [_scope_node_row(c, hidden, by_key) for c in node['children']]
+ if len(kids) == 1:
+ return kids[0]
+ if node.get('conj') == 'or':
+ return _scope_or_rows(kids)
+ return {'conj': 'and', 'children': kids}
+ return _scope_leaf_row(node, hidden, by_key)
+
+
+def _legacy_scope_parts(user, module):
+ """The legacy `bus`/`agent` pool scope on `module` that the permanent filter does not say."""
+ return [part for part, _row in _legacy_scope_items(user, module)]
+
+
+def _legacy_scope_items(user, module):
+ """`(part, row)` pairs for `_legacy_scope_parts`, each row a leaf or `{'hidden': True}`."""
+ if module not in _LEGACY_POOL_MODULES:
+ return []
+ team_id, agent = derive_pool_scope(user, module)
+ if (entry(user, module) or {}).get('filter'):
+ ftid, _fagent = _derive_from_filter(user, module)
+ if ftid is not None:
+ team_id = None # the filter's own leaf already says it
+ agent = None # with a filter, the agent comes only from it
+ parts = []
+ if team_id is not None:
+ import core.context as ctxlib
+ label = next((k for k, v in ctxlib.BRANDS.items() if v == team_id), None)
+ parts.append((f'{SCOPE_LIMIT_BU_LABEL} is {label}', {
+ 'field': 'bus', 'label': SCOPE_LIMIT_BU_LABEL, 'op': 'eq', 'type': 'text',
+ 'value': label}) if label else (SCOPE_LIMIT_HIDDEN, {'hidden': True}))
+ if agent and module in _LEGACY_AGENT_MODULES:
+ parts.append((f'Agent is {agent}', {'field': 'agent', 'label': 'Agent', 'op': 'eq',
+ 'type': 'text', 'value': str(agent)}))
+ return parts
+
+
+def describe_scope(user, module, fields, st=None):
+ """The reader-safe description of the row limit `user` carries on `module`, or None.
+
+ `fields` is the UNSTRIPPED contract. A leaf on a hidden or unknown column, or one this
+ cannot say exactly, becomes `SCOPE_LIMIT_HIDDEN`. Returns `{'parts', 'text', 'rows'}`.
+
+ `rows` is the same limit as a tree `{'conj': 'and', 'nodes': [...]}` the filter panel paints
+ as locked condition rows. Its nodes mirror `parts`: a node exists only where a part does, and
+ every unsayable condition is the ONE `{'hidden': True}` node, so no hidden key, label or
+ value and no count of hidden conditions reaches it. An `or` of equality leaves on one
+ single-valued field is one `isAnyOf` leaf (`_scope_any_of_row`), so it paints as one row.
+ """
+ if perms.is_admin(user):
+ return None
+ by_key = {str(f['key']): f for f in (fields or ()) if isinstance(f, dict) and f.get('key')}
+ tree = (entry(user, module) or {}).get('filter')
+ parts, rows = [], []
+ if tree:
+ from harness import filter_eval as fe
+ hidden = set(hidden_keys(user, module, list(by_key.values()), st=st)) if by_key else set()
+ nodes, conj = fe.tree_parts(tree)
+ nodes = [n for n in nodes if isinstance(n, dict)]
+ said = [_scope_node_phrase(n, hidden, by_key, outer=len(nodes) == 1) for n in nodes]
+ shaped = [_scope_node_row(n, hidden, by_key) for n in nodes]
+ if conj == 'or' and len(said) > 1:
+ if any(s is None for s in said):
+ said, shaped = [None], [None]
+ else:
+ said, shaped = [' or '.join(said)], [_scope_or_rows(shaped)]
+ unsaid = any(s is None for s in said)
+ parts = [s for s in said if s is not None]
+ rows = [r for s, r in zip(said, shaped) if s is not None]
+ if unsaid or not said:
+ parts.append(SCOPE_LIMIT_HIDDEN)
+ rows.append({'hidden': True})
+ for part, row in _legacy_scope_items(user, module):
+ if part not in parts:
+ parts.append(part)
+ rows.append(row)
+ if not parts:
+ return None
+ return {'parts': parts, 'text': ' · '.join(parts), 'rows': {'conj': 'and', 'nodes': rows}}
+
+
+def _scope_limit_fields(user, module, st=None):
+ """The unstripped contract the description reads labels from, or None if it cannot be read.
+
+ Never builds a pool: a registry topic whose reader cannot skip rows answers from its
+ static contract.
+ """
+ try:
+ if module.startswith(_ut().KEY_PREFIX) or _ROW_SOURCE_WANT_ROWS.get(module, False):
+ fields, _rows = _read(module, user, st, want_rows=False)
+ return list(fields or ())
+ if module in _LEGACY_POOL_MODULES:
+ import aios_grid
+ return list(aios_grid.FIELDS if module == 'customer_data'
+ else aios_grid.product_fields())
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
+def scope_limits(user, st=None):
+ """Every database on which `user` carries a row limit, described for that reader.
+
+ Admins get `[]`. Each item is `{'database', 'parts', 'text', 'fields'}`, where `fields`
+ lists the keys of the columns the reader may see, or None when they could not be read.
+ """
+ if perms.is_admin(user):
+ return []
+ p = _rec(user).get('perms')
+ keys = {str(k) for k, e in (p.items() if isinstance(p, dict) else ())
+ if isinstance(e, dict) and e.get('filter')}
+ keys |= {k for k in _LEGACY_POOL_MODULES if _legacy_scope_parts(user, k)}
+ out = []
+ for key in sorted(keys):
+ try:
+ if not may_read(user, key, st=st):
+ continue
+ except Exception: # noqa: BLE001
+ continue
+ fields = _scope_limit_fields(user, key, st=st)
+ described = describe_scope(user, key, fields or [], st=st)
+ if not described:
+ continue
+ visible = None
+ if fields is not None:
+ hide = hidden_keys(user, key, fields, st=st)
+ visible = [str(f['key']) for f in fields
+ if isinstance(f, dict) and f.get('key') and str(f['key']) not in hide]
+ out.append({'database': key, **described, 'fields': visible})
+ return out
+
+
# ── C1: THE ONE DOOR TO ANY DATABASE'S ROWS (wave 36, W36-T20) ────────────────────────────────
#: ⭐⭐ OWNER RULING R6, AND IT IS WHY THIS SECTION EXISTS AT ALL: *"EVERY database gets the same
#: permission logic, always"* — per-user field visibility AND row filtration on every database
diff --git a/platform/core/sheets.py b/platform/core/sheets.py
index 5b7553d224d83d7788d3b6d9ca1e46d97f8507e2..c8106c288a29829e69d9ae7f82ff4dfc1b6d1683 100644
--- a/platform/core/sheets.py
+++ b/platform/core/sheets.py
@@ -2292,6 +2292,148 @@ def patch_cells(st, workbook_id, tab_ref, raw_cells, expect_rev=None, *, actor="
return out
+# ── S72-T64: name-only writes for a workbook and a tab ──────────────────────────────────────
+#
+# A rename carries a name and a revision. It never reads, cleans, diffs or rewrites cells, so it
+# never goes through `put_workbook` or `_persist` (both copy and diff the whole document).
+
+
+def _rename_guard(prior, expect_rev):
+ """Refuse a rename of a missing workbook or one at another revision."""
+ if not prior or not prior.get("id"):
+ raise SheetRefusal("workbook_missing", "That workbook no longer exists.")
+ if isinstance(expect_rev, bool) or not isinstance(expect_rev, int) or expect_rev < 0:
+ raise SheetRefusal("workbook_revision_invalid", "A rename needs the workbook revision.")
+ current = int(prior.get("rev") or 0)
+ if current != expect_rev:
+ raise SheetStaleRefusal(
+ "workbook_revision_stale",
+ "This workbook changed. The name was not saved.",
+ rev_current=current)
+ return current
+
+
+def rename_access(st, workbook_id):
+ """Read rename permission fields without normalizing any cells."""
+ book = _read_workbook_doc(st, workbook_key(_slug_id(workbook_id)))
+ if not book or not book.get("id"):
+ raise SheetRefusal("workbook_missing", "That workbook no longer exists.")
+ return {key: value for key, value in book.items() if key != "sheets"}
+
+
+def rename_meta(book):
+ """A renamed workbook without cells or write history, read off the stored document as is."""
+ meta = {k: v for k, v in (book or {}).items() if k != "sheets"}
+ tabs = []
+ for tab in (book or {}).get("sheets") or ():
+ if not isinstance(tab, dict):
+ continue
+ thin = {k: v for k, v in tab.items() if k not in ("cells", "writes", "writesFrom")}
+ thin["cellCount"] = len(tab.get("cells") or {})
+ tabs.append(thin)
+ meta["sheets"] = tabs
+ return meta
+
+
+def rename_workbook(st, workbook_id, name, expect_rev=None):
+ """Write a workbook's name and bump `rev`. Cells are not read or rewritten."""
+ wid = _slug_id(workbook_id)
+ clean = _text(name, _MAX_NAME)
+ if not clean:
+ raise SheetRefusal("workbook_name_empty", "A workbook needs a name.")
+ saved = {}
+
+ def _apply(state):
+ prior = state if isinstance(state, dict) else {}
+ current = _rename_guard(prior, expect_rev)
+ # Shallow on purpose: the tabs are shared with the read, never copied or changed.
+ book = dict(prior)
+ book["name"] = clean
+ book["rev"] = current + 1
+ book["updated_at"] = _now()
+ saved.clear()
+ saved.update(book)
+ return book
+
+ st.update(workbook_key(wid), _apply, flush="sync")
+ _index_upsert(st, saved)
+ return saved
+
+
+def rename_tab(st, workbook_id, tab_ref, name, expect_rev=None):
+ """Write one tab's name and bump `rev`; formulas that name the old tab follow it (R5).
+
+ Only formula cells whose text changes are copied. When any did, `structureRev` moves, so a
+ stale client cannot write a formula back under the old tab name.
+ """
+ from core.sheet_structure import rewrite_refs
+
+ wid = _slug_id(workbook_id)
+ clean = _text(name, _MAX_NAME)
+ if not clean:
+ raise SheetRefusal("tab_name_empty", "A sheet needs a name.")
+ if "'" in clean:
+ raise SheetRefusal("tab_name_invalid", "A sheet name cannot contain an apostrophe.")
+ saved = {}
+
+ def _same(left, right):
+ return str(left or "").strip().casefold() == str(right or "").strip().casefold()
+
+ def _follow(text, old):
+ def rewrite(ref):
+ return {**ref, "sheet": clean} if ref["sheet"] and _same(ref["sheet"], old) else ref
+ return rewrite_refs(text, rewrite)
+
+ def _apply(state):
+ prior = state if isinstance(state, dict) else {}
+ current = _rename_guard(prior, expect_rev)
+ tabs = list(prior.get("sheets") or [])
+ at = _tab_index(tabs, tab_ref)
+ if at is None:
+ raise SheetRefusal("tab_missing",
+ "Tab " + (str(tab_ref) or "(unnamed)") + " is not in this workbook.")
+ old = str(tabs[at].get("name") or "")
+ if any(i != at and isinstance(t, dict) and _same(t.get("name"), clean)
+ for i, t in enumerate(tabs)):
+ raise SheetRefusal("tab_name_taken", "Another sheet already has that name.")
+ moved = False
+ if not _same(old, clean):
+ for i, tab in enumerate(tabs):
+ if not isinstance(tab, dict):
+ continue
+ cells, changed = tab.get("cells") or {}, {}
+ for addr, cell in cells.items():
+ if not isinstance(cell, dict) or cell.get("kind") != "formula":
+ continue
+ text = cell.get("formula")
+ if not isinstance(text, str) or "!" not in text:
+ continue
+ after = _follow(text, old)
+ if after == text:
+ continue
+ fresh = dict(cell, formula=after)
+ if cell.get("display") == text:
+ fresh["display"] = after
+ changed[addr] = fresh
+ if changed:
+ tabs[i] = dict(tab, cells={**cells, **changed})
+ moved = True
+ tabs[at] = dict(tabs[at], name=clean)
+ book = dict(prior)
+ book["sheets"] = tabs
+ book["rev"] = current + 1
+ if moved:
+ book["structureRev"] = book["rev"]
+ book["updated_at"] = _now()
+ saved.clear()
+ saved.update(book)
+ return book
+
+ st.update(workbook_key(wid), _apply, flush="sync")
+ _index_upsert(st, saved)
+ return saved
+
+
# ── W52-T12: the per-scope bound-cell cache (instr 9, ruling R3) ────────────────────────────
#
# ⭐⭐ A SEPARATE DOCUMENT, NEVER A KEY ON THE CELL, AND THAT IS THE WHOLE DESIGN. The obvious
diff --git a/platform/core/users.py b/platform/core/users.py
index 8c76408324ca8edf1d43c74b46617cc70b9938e8..2d050fbd364242df74ff9480316bd44caf4f1ea9 100644
--- a/platform/core/users.py
+++ b/platform/core/users.py
@@ -1028,6 +1028,82 @@ def set_whatsapp_opt_out(username, on):
return store.update('users', _set)
+def database_access_state(record):
+ """Copy the permission state used to admit a narrow database change."""
+ import copy
+ keys = ('perms', 'perms_v', 'modules', 'bus', 'agent', 'role', 'active', 'tenant')
+ return {key: copy.deepcopy(record[key]) for key in keys if key in record}
+
+
+def set_database_access(username, database, entry, *, actor, tenant, expect,
+ legacy_filter=None, restore=None):
+ """Compare fresh permission state and replace only one database entry."""
+ import copy
+ freeze_notice.check_write()
+ username = str(username or '').strip().lower()
+ actor = str(actor or '').strip().lower()
+ tenant = str(tenant or '').strip().lower()
+ if not database or not isinstance(expect, dict) or (entry is None and restore is None) or (
+ entry is not None and (not isinstance(entry, dict)
+ or type(entry.get('access')) is not bool)):
+ raise ValueError('a database change requires an entry and expected permission state')
+ expect, entry = copy.deepcopy(expect), copy.deepcopy(entry)
+ legacy_filter, restore = copy.deepcopy(legacy_filter), copy.deepcopy(restore)
+ outcome = {}
+
+ def _tenant(rec):
+ return str(rec.get('tenant') or 'royal-imports').strip().lower()
+
+ def _set(reg):
+ # A provisional callback can lose its commit and run again against newer state.
+ outcome.clear()
+ current_actor, target = reg.get(actor), reg.get(username)
+ if (not isinstance(current_actor, dict) or current_actor.get('role') != 'admin'
+ or not current_actor.get('active', True) or _tenant(current_actor) != tenant):
+ outcome['status'] = 'forbidden'
+ return reg
+ if (not isinstance(target, dict) or not target.get('active', True)
+ or _tenant(target) != tenant):
+ outcome['status'] = 'missing'
+ return reg
+ if database_access_state(target) != expect:
+ outcome['status'] = 'conflict'
+ return reg
+ if target.get('perms') is not None and not isinstance(target['perms'], dict):
+ outcome['status'] = 'conflict'
+ return reg
+ block = copy.deepcopy(target.get('perms') or {})
+ if restore is not None:
+ prior_block = restore.get('perms') or {}
+ if database in prior_block:
+ block[database] = copy.deepcopy(prior_block[database])
+ else:
+ block.pop(database, None)
+ else:
+ selected = block.get(database) or {}
+ if not isinstance(selected, dict):
+ outcome['status'] = 'conflict'
+ return reg
+ block[database] = dict(selected, access=entry['access'])
+ if legacy_filter is not None:
+ block[database]['filter'] = copy.deepcopy(legacy_filter)
+ if restore is not None and not block:
+ if 'perms' not in restore:
+ target.pop('perms', None)
+ else:
+ target['perms'] = None if restore.get('perms') is None else {}
+ elif block or 'perms' in expect:
+ target['perms'] = block
+ else:
+ target.pop('perms', None)
+ # A narrow overlay must not stamp migration and revoke undeclared legacy modules.
+ outcome.update(status='updated', after=database_access_state(target))
+ return reg
+
+ store.update('users', _set, flush='sync')
+ return outcome
+
+
def set_access(username, role=None, bus=None, modules=None, agent=None, email=None,
name=None, perms=None):
"""Update access fields. agent/email: pass '' to clear, None to leave unchanged —
diff --git a/platform/evals/analyst_golden.yml b/platform/evals/analyst_golden.yml
index 1284cc2f0cef27997a231a69049c43f58cc5ad88..5028f284d518b8c816d3b6d2c311c602747ef56b 100644
--- a/platform/evals/analyst_golden.yml
+++ b/platform/evals/analyst_golden.yml
@@ -9,37 +9,53 @@
# expect.tools: tool names that MUST appear in the trace (the answer must come FROM the tools).
# expect.not_tools: tool names that must NOT appear (the over-refusal guard — an answerable ask
# must never end in report_gap; a gap ask must never end in a forced wrong query).
+# Truths below come from the semantic layer over this seed, with no LLM. A live Odoo read after the
+# cut can differ (documents edited later); the seed value is the truth and the drift is logged.
+seed:
+ contentSha: 3857b63c11148c7565463cbae21b24f54602f1106624ab7337b115c278828a5b
+ cutDate: "2026-09-03"
+ dataset: royal-imports/cfo-os-data
+ revision: e91188cbb12e6d13e48b7d754afd9bfdd6e84ae4
+ truthsComputed: "2026-10-09"
+# The OpenRouter model the paid eval measured. analyst.py PROVIDERS defaults to it.
+measured:
+ model: z-ai/glm-4.7-flash
+ openWeights: zai-org/GLM-4.7-Flash
+ score: "20/26"
+ runs: 2
+ date: "2026-10-09"
+ provider: openrouter
items:
- id: rev_h1
ask: "What was our wholesale revenue for the first half of 2026 (Jan 1 through Jun 30)?"
- expect: {value: 3501508.33, rel: 0.001, tools: [run_semantic_query]}
+ expect: {value: 3502957.34, rel: 0.001, tools: [run_semantic_query]}
- id: rev_h1_fisch
ask: "Fisch revenue only, H1 2026 (Jan 1 - Jun 30)?"
- expect: {value: 2494244.70, rel: 0.001, tools: [run_semantic_query]}
+ expect: {value: 2489001.85, rel: 0.001, tools: [run_semantic_query]}
- id: rev_h1_royal
ask: "And Royal's revenue for the same H1 2026 window?"
- expect: {value: 1007263.63, rel: 0.001, tools: [run_semantic_query]}
+ expect: {value: 1013955.49, rel: 0.001, tools: [run_semantic_query]}
- id: rev_june
ask: "Revenue for June 2026?"
- expect: {value: 535046.06, rel: 0.001, tools: [run_semantic_query]}
+ expect: {value: 536944.56, rel: 0.001, tools: [run_semantic_query]}
- id: margin_h1
ask: "Gross margin dollars for H1 2026 (Jan-Jun), wholesale?"
- expect: {value: 2067509.45, rel: 0.001, tools: [run_semantic_query]}
+ expect: {value: 2069536.47, rel: 0.001, tools: [run_semantic_query]}
- id: margin_pct_h1
ask: "What gross margin percentage did we run in H1 2026?"
- expect: {value: 0.59, abs: 0.005, allow_pct_form: true, tools: [run_semantic_query]}
+ expect: {value: 0.5908, abs: 0.005, allow_pct_form: true, tools: [run_semantic_query]}
- id: orders_h1
ask: "How many confirmed wholesale orders did we take in H1 2026 (Jan 1 - Jun 30)?"
- expect: {value: 4989, abs: 1, tools: [run_semantic_query]}
+ expect: {value: 4985, abs: 1, tools: [run_semantic_query]}
- id: customers_h1
ask: "How many distinct customers bought from us in H1 2026?"
- expect: {value: 1037, abs: 1, tools: [run_semantic_query]}
+ expect: {value: 1036, abs: 1, tools: [run_semantic_query]}
- id: top_customer
ask: "Who was our biggest customer by revenue in H1 2026?"
expect: {contains: ["Poppy Flowers"], tools: [run_semantic_query], not_tools: [report_gap]}
- id: opex_h1
ask: "Total operating expense on the GL for H1 2026 (Jan 1 - Jun 30)?"
- expect: {value: 4683428.81, rel: 0.001, tools: [run_semantic_query]}
+ expect: {value: 4959379.38, rel: 0.001, tools: [run_semantic_query]}
- id: top_expense
ask: "What is our single largest expense account in H1 2026?"
expect: {contains: ["FBA"], tools: [run_semantic_query]}
@@ -73,21 +89,24 @@ items:
not_tools: [report_gap]}
- id: agent_revenue
ask: "How much revenue did agent Naomi's book of customers bring in H1 2026 (Jan 1 - Jun 30)?"
- expect: {value: 872869.98, rel: 0.005, tools: [run_semantic_query], not_tools: [report_gap]}
+ expect: {value: 880329.39, rel: 0.005, tools: [run_semantic_query], not_tools: [report_gap]}
# --- the TWO agent sources (added 2026-07-28). Odoo holds a customer-master book AND a
# per-invoice-line commission agent; they name different people, and the commission table also
# carries internal SALESPEOPLE who are not agents. These three lock the distinction: the
# unallocated bucket must be answerable at all, and Anna/Shantal must never be called agents.
+# The two value truths are the governed metrics agent_allocated_sales and unallocated_line_sales
+# (out_invoice lines, gross of credit notes by design); net of credit notes they read 2,995,664.75
+# and 1,447,442.59 on the same seed.
- id: agent_unallocated
ask: "Using the invoice-line basis, how much of Fisch's 2025 sales was NOT allocated to an agent?"
- expect: {value: 1447579.59, rel: 0.01, tools: [run_semantic_query], not_tools: [report_gap]}
+ expect: {value: 1480806.97, rel: 0.01, tools: [run_semantic_query], not_tools: [report_gap]}
- id: agent_not_salesperson
ask: "Who are our agents on the Fisch invoice lines in 2025, and what did each generate?"
expect: {contains: ["Pasternak"], not_contains: ["Anna", "Shantal"],
tools: [run_semantic_query], not_tools: [report_gap]}
- id: agent_allocated_2025
ask: "On the invoice-line basis, how much of Fisch's 2025 sales was allocated to a real agent?"
- expect: {value: 2995664.75, rel: 0.01, tools: [run_semantic_query], not_tools: [report_gap]}
+ expect: {value: 3069547.18, rel: 0.01, tools: [run_semantic_query], not_tools: [report_gap]}
- id: gap_refusal
ask: "How many units of our best-selling SKU do we physically have in stock right now?"
expect: {tools: [report_gap]} # stock-on-hand has NO topic in the store — must self-report, never guess
@@ -95,10 +114,10 @@ items:
# the parity-proven semantic layer over the CLOSED H1 2026 window.
- id: abc_a_tier
ask: "Using an ABC / Pareto analysis of H1 2026 revenue (Jan 1 - Jun 30), how many customers fall in the A tier — the vital few that make up the first 80% of revenue?"
- expect: {value: 311, abs: 6, tools: [run_semantic_query, transform_result], not_tools: [report_gap]}
+ expect: {value: 310, abs: 6, tools: [run_semantic_query, transform_result], not_tools: [report_gap]}
- id: ytd_customers
ask: "How many distinct customers had we sold to cumulatively from Jan 1 through the end of March 2026?"
expect: {value: 790, abs: 1, tools: [run_semantic_query], not_tools: [report_gap]}
- id: concentration_top5
ask: "What percent of our H1 2026 revenue (Jan 1 - Jun 30) is accounted for by our top 5 customers?"
- expect: {value: 7.84, abs: 0.5, tools: [run_semantic_query], not_tools: [report_gap]}
+ expect: {value: 7.93, abs: 0.5, tools: [run_semantic_query], not_tools: [report_gap]}
diff --git a/platform/harness/amazon_semantic.py b/platform/harness/amazon_semantic.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47c89aed641a36016f488dfe8fab4176db89673
--- /dev/null
+++ b/platform/harness/amazon_semantic.py
@@ -0,0 +1,234 @@
+"""Read-only Amazon count contract over the existing tenant mirror and Sales summary seam.
+
+Only a fully authorized Administrator may use this unfiltered source summary. Member, field,
+row, BU and related scopes require independent source evidence for that narrower population.
+No sync, restore, credential read or live API call belongs in this path.
+"""
+from contextlib import contextmanager
+from datetime import date, datetime, time, timedelta, timezone
+import json
+from pathlib import Path
+import re
+
+from harness import amazon_store as AZ, datastore as DS
+
+
+def _fail(message):
+ from harness.semantic import ModelError
+ raise ModelError(message)
+
+
+def _bounds(date_from, date_to):
+ values = []
+ for value in (date_from, date_to):
+ if not isinstance(value, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', value):
+ _fail('Amazon order count requires both UTC dates in YYYY-MM-DD format')
+ try:
+ values.append(date.fromisoformat(value))
+ except ValueError:
+ _fail('Amazon order count requires valid UTC dates')
+ if values[0] > values[1]:
+ _fail('Amazon order count start date must precede its end date')
+ try:
+ return tuple(datetime.combine(value, time(), timezone.utc)
+ for value in (values[0], values[1] + timedelta(days=1)))
+ except OverflowError:
+ _fail('Amazon order-count end date exceeds the supported UTC date range')
+
+
+def _unrestricted_bu(user):
+ from core import perms, users
+ raw = user.get('bus', 'all')
+ if raw == 'all':
+ return 'All' in perms.allowed_bu_labels(user)
+ # The canonical boundary consumes BU ids. Session projections can carry labels instead.
+ # Reject empty/unknown inputs before its legacy fallback can turn them into all BUs.
+ if not isinstance(raw, (list, tuple)) or not raw:
+ return False
+ ids = []
+ by_label = {label: key for key, label in users.BU_LABELS.items()}
+ for value in raw:
+ if type(value) is int and value in users.BU_LABELS:
+ ids.append(value)
+ elif isinstance(value, str) and value in by_label:
+ ids.append(by_label[value])
+ elif value != 'All':
+ return False
+ # 'All' is a selector label, not a substitute for the concrete granted population.
+ ids = sorted(set(ids))
+ return bool(ids) and 'All' in perms.allowed_bu_labels(dict(user, bus=ids))
+
+
+@contextmanager
+def _cursor(runtime, user):
+ from core import perm_scope, perms, route_system, user_tables
+ try:
+ if runtime is None or not getattr(runtime, 'key', None):
+ _fail('Amazon order count requires the requesting tenant runtime')
+ if not isinstance(user, dict) or not user.get('username') or not perms.is_admin(user):
+ _fail('Amazon source-summary counts require an unrestricted Administrator caller')
+ if user.get('tenant') != runtime.key:
+ _fail('Amazon order count requires a caller bound to the requesting tenant')
+ if not _unrestricted_bu(user) or perms.scope_agent(user) is not None:
+ _fail('Amazon source summary cannot validate a business-unit or agent-restricted caller')
+ # Use the native ut_* reader's rows-free, runtime-bound definition wall. Registry
+ # topics need assistant_entry; user tables may have no entry at all. Lend only this
+ # read pass so a cached result cannot retain yesterday's definition or recipient wall.
+ definitions = runtime.get_projection('user_tables', drop=('rows',))
+ definition = definitions.get('ut_amzn_orders') if isinstance(definitions, dict) else None
+ if not isinstance(definition, dict) or not definition:
+ _fail('Amazon orders database has no readable table definition')
+ lent = user_tables.lend(runtime, user_tables=definitions)
+ grant = perm_scope.entry(user, 'ut_amzn_orders')
+ # The core admin bypass must not discard a stored untick or narrowing: an unfiltered
+ # Sales summary supplies no independent evidence for a field/row-restricted caller.
+ if grant is not None and (not grant.get('access', True) or grant.get('filter')
+ or grant.get('hiddenFields')):
+ _fail('Amazon order count requires unrestricted stored database permissions')
+ if (not perm_scope.may_read(user, 'ut_amzn_orders', st=lent)
+ or not perm_scope.nav_may_open(user, 'ut_amzn_orders', st=lent)
+ or route_system.is_managed(definition) or route_system.is_managed('ut_amzn_orders')):
+ _fail('Amazon orders database access was refused')
+ if perm_scope.row_scope_applies(user, 'ut_amzn_orders', st=lent, defn=definition):
+ _fail('Amazon source summary cannot validate a recipient or row-restricted population')
+ fields = perm_scope.scoped_fields(user, 'ut_amzn_orders', st=lent)
+ keys = {f['key'] for f in fields}
+ declared = {f['key'] for f in definition.get('fields', ())}
+ if (keys != declared
+ or not {'amazon_order_id', 'purchase_date', 'order_status'} <= keys):
+ _fail('Amazon order count dependencies are unavailable to this caller')
+ runtime.assert_datastore_matches()
+ # The general runtime guard allows bespoke fixture pins. This source proof needs EXACT
+ # runtime/file identity, even for an otherwise unowned file. Never infer tenant zero.
+ path = Path(runtime.datastore_path).resolve()
+ if path != Path(DS.DB_PATH).resolve() or not path.is_file():
+ _fail('Amazon order count requires this tenant runtime\'s existing mirror file')
+ # Amazon readiness is its own completed markers, not Odoo's global backfill gate.
+ con = DS.ro_cursor()
+ except Exception as exc:
+ from harness.semantic import ModelError
+ if isinstance(exc, ModelError):
+ raise
+ _fail(f'Amazon tenant source or permission proof is unavailable ({type(exc).__name__})')
+ try:
+ con.execute('BEGIN TRANSACTION')
+ yield con
+ finally:
+ con.close()
+
+
+def _evidence(con, bounds):
+ orders = AZ._read_state(con, AZ.entity_key('orders'))
+ summary = AZ._read_state(con, AZ.entity_key('reconcile_order_metrics'))
+ if not orders or orders['state'] != 'done':
+ _fail('Amazon orders have no completed mirror sync')
+ if not summary or summary['state'] != 'done' or not summary.get('detail'):
+ _fail('Amazon Sales source summary is unavailable or refused')
+ try:
+ if not con.execute('SELECT count(*) FROM amzn_orders').fetchone()[0]:
+ _fail('Amazon orders mirror is empty; source validation remains unproven')
+ malformed = con.execute(
+ "SELECT count(*) FROM amzn_orders WHERE NULLIF(trim(amazon_order_id), '') IS NULL "
+ "OR TRY_CAST(purchase_date AS TIMESTAMPTZ) IS NULL").fetchone()[0]
+ if malformed:
+ _fail('Amazon orders lack valid ids or UTC purchase dates')
+ conflicting = con.execute(
+ 'SELECT count(*) FROM (SELECT amazon_order_id FROM amzn_orders '
+ 'GROUP BY amazon_order_id HAVING count(DISTINCT CAST(purchase_date AS TIMESTAMPTZ)) > 1 '
+ "OR count(DISTINCT lower(COALESCE(order_status, ''))) > 1)").fetchone()[0]
+ if conflicting:
+ _fail('Amazon order heads have conflicting dates or statuses; sync the deduplicated source')
+ marker = json.loads(summary['detail'])
+ if (type(marker.get('count')) is not int or marker['count'] <= 0
+ or marker.get('column') != '_period_start' or marker.get('range') is not True):
+ _fail('Amazon Sales source summary has no completed interval evidence')
+ saved_bounds = tuple(datetime.fromisoformat(marker[k].replace('Z', '+00:00'))
+ for k in ('start', 'end'))
+ if any(v.tzinfo is None for v in saved_bounds) or saved_bounds != bounds:
+ _fail('Requested UTC dates do not match the completed Amazon Sales source summary')
+ expected = marker['metrics']['orders']
+ if type(expected) is not int or expected < 0:
+ _fail('Amazon Sales source summary has no valid orderCount')
+ except Exception as exc:
+ from harness.semantic import ModelError
+ if isinstance(exc, ModelError):
+ raise
+ _fail(f'Amazon orders or source summary cannot be read ({type(exc).__name__})')
+ # Reuse the connector's independent summary-versus-detail seam and cancellation predicate.
+ evidence = AZ._validate_orders(con)
+ if evidence.get('state') not in ('ok', 'refused') or 'actual' not in evidence:
+ _fail('Amazon Sales order-count reconciliation remains unproven')
+ return evidence['actual'], expected
+
+
+def validate(date_from, date_to, team_id=None, *, runtime=None, user=None):
+ if team_id is not None:
+ _fail('Amazon Sales source summary has no business-unit scope')
+ bounds = _bounds(date_from, date_to)
+ with _cursor(runtime, user) as con:
+ return _evidence(con, bounds)
+
+
+def existing_summary_window(*, runtime=None, user=None):
+ """Read this authorized caller's existing summary interval; never fetch or create it."""
+ with _cursor(runtime, user) as con:
+ saved = AZ._read_state(con, AZ.entity_key('reconcile_order_metrics'))
+ if not saved or saved['state'] != 'done' or not saved.get('detail'):
+ _fail('Amazon Sales source summary is unavailable or refused')
+ try:
+ marker = json.loads(saved['detail'])
+ start, end = (datetime.fromisoformat(marker[k].replace('Z', '+00:00'))
+ for k in ('start', 'end'))
+ if start.tzinfo is None or end.tzinfo is None:
+ _fail('Amazon Sales source summary requires a UTC interval')
+ start, end = (v.astimezone(timezone.utc) for v in (start, end))
+ date_from, date_to = start.date().isoformat(), (end.date() - timedelta(days=1)).isoformat()
+ _evidence(con, _bounds(date_from, date_to))
+ return date_from, date_to
+ except Exception as exc:
+ from harness.semantic import ModelError
+ if isinstance(exc, ModelError):
+ raise
+ _fail(f'Amazon Sales source interval is unavailable ({type(exc).__name__})')
+
+
+def query(date_from, date_to, *, runtime=None, user=None, group_by=None, grain=None,
+ sort=None, limit=1000):
+ bounds = _bounds(date_from, date_to)
+ gb = list(group_by or [])
+ if gb not in ([], ['purchase_date']) or (gb and grain):
+ _fail('Amazon order count supports UTC purchase date or one time grain')
+ if grain not in (None, 'day', 'week', 'month'):
+ _fail('Amazon order-count grain must be day, week or month')
+ period = ('CAST(CAST(purchase_date AS TIMESTAMPTZ) AT TIME ZONE \'UTC\' AS DATE)'
+ if gb else f"date_trunc('{grain}', CAST(purchase_date AS TIMESTAMPTZ) AT TIME ZONE 'UTC')"
+ if grain else None)
+ column = 'purchase_date' if gb else 'period'
+ selected = f'{period} AS {column}, ' if period else ''
+ sql = (f'SELECT {selected}COUNT(DISTINCT amazon_order_id) AS amazon_order_count '
+ 'FROM amzn_orders WHERE CAST(purchase_date AS TIMESTAMPTZ) >= CAST(? AS TIMESTAMPTZ) '
+ 'AND CAST(purchase_date AS TIMESTAMPTZ) < CAST(? AS TIMESTAMPTZ) '
+ "AND lower(COALESCE(order_status, '')) NOT IN ('cancelled', 'canceled')")
+ if period:
+ sql += f' GROUP BY {period}'
+ if sort:
+ if sort.lstrip('-') not in (['amazon_order_count', column] if period else ['amazon_order_count']):
+ _fail('Amazon order-count sort must name a selected measure or date')
+ sql += f" ORDER BY {sort.lstrip('-')} {'DESC' if sort.startswith('-') else 'ASC'}"
+ elif period:
+ sql += f' ORDER BY {column}'
+ from harness.semantic import MAX_GROUPS
+ limit = max(1, min(int(limit or 1000), MAX_GROUPS if period else 5000))
+ with _cursor(runtime, user) as con:
+ ours, expected = _evidence(con, bounds)
+ if ours != expected:
+ _fail(f'Amazon Sales summary counted {expected} orders; mirror counted {ours}')
+ cur = con.execute(sql + f' LIMIT {limit + 1}', [v.isoformat() for v in bounds])
+ names = [d[0] for d in cur.description]
+ rows = [dict(zip(names, row)) for row in cur.fetchall()]
+ for row in rows:
+ if period:
+ row[column] = str(row[column])[:10]
+ return {'topic': 'amazon_orders', 'rows': rows[:limit], 'row_count': min(len(rows), limit),
+ 'truncated': len(rows) > limit, 'sql': sql, 'measures': ['amazon_order_count'],
+ 'group_by': gb, 'grain': grain}
diff --git a/platform/harness/analyst.py b/platform/harness/analyst.py
index 03e9d73932918057400ca172934c2b23de0631ad..e3af6226e89e4fedf6ce7a332fd667d66bec74cd 100644
--- a/platform/harness/analyst.py
+++ b/platform/harness/analyst.py
@@ -36,10 +36,72 @@ PROVIDERS = [
"model": "gpt-oss-120b"}, # this account's tool-capable model (from /v1/models)
{"name": "openrouter", "env": "OPENROUTER_API_KEY",
"url": "https://openrouter.ai/api/v1/chat/completions",
- "model": "openai/gpt-4o-mini"},
+ # The eval measures this default: analyst_golden.yml `measured` names it, open weights only (R11).
+ "model": "z-ai/glm-4.7-flash"},
]
DEFAULT_MODEL = None # None = the selected provider's default model
-MAX_ITERS = 8
+# A map, YoY or name-resolution ask needs about 8 tool turns with no retry (list, describe,
+# recipe, field values, query, transform, chart, answer), so 8 exhausted 7 of 26 items (D-8280).
+# 14 leaves room for 6 error-correction turns. ANALYST_MAX_ITERS overrides it per run.
+MAX_ITERS = 14
+
+
+def iter_budget():
+ """The tool-loop budget: ANALYST_MAX_ITERS when set to a positive integer, else MAX_ITERS."""
+ try:
+ value = int(os.environ.get("ANALYST_MAX_ITERS") or MAX_ITERS)
+ except ValueError:
+ return MAX_ITERS
+ return value if value > 0 else MAX_ITERS
+
+
+#: Working-context byte ceiling per provider. Groq and Cerebras fail near 8k request tokens.
+#: OpenRouter tool models take 128k+ tokens. 120000 bytes (about 30k tokens) fits a full
+#: discovery run and keeps each request cheap.
+REQUEST_BYTES = {"groq": 32000, "cerebras": 32000, "openrouter": 120000}
+DEFAULT_REQUEST_BYTES = 32000
+
+
+def request_budget(provider=None):
+ """The request byte ceiling: ANALYST_MAX_REQUEST_BYTES when a positive integer, else per provider."""
+ try:
+ value = int(os.environ.get("ANALYST_MAX_REQUEST_BYTES") or 0)
+ except ValueError:
+ value = 0
+ if value > 0:
+ return value
+ return REQUEST_BYTES.get(provider, DEFAULT_REQUEST_BYTES)
+
+
+#: Set by harness/evals.run to the golden item id, so each ledger line names its item.
+CALL_ITEM = None
+#: Running totals of ledger lines written by this process (evals.run reads the delta).
+CALL_TOTALS = {"calls": 0, "cost": 0.0, "cost_missing": 0}
+
+
+def _log_call(usage):
+ """Append one cost line to ANALYST_CALL_LOG. Never writes message or answer text."""
+ path = os.environ.get("ANALYST_CALL_LOG")
+ if not path:
+ return
+ import time as _time
+
+ usage = usage or {}
+ cost = usage.get("cost")
+ cost = float(cost) if isinstance(cost, (int, float)) and not isinstance(cost, bool) else None
+ line = {"ts": _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime()),
+ "provider": usage.get("provider"), "model": usage.get("model"),
+ "item": CALL_ITEM,
+ "prompt_tokens": usage.get("prompt_tokens"),
+ "completion_tokens": usage.get("completion_tokens"),
+ "cost": cost}
+ with open(path, "a", encoding="utf-8", newline="") as fh:
+ fh.write(json.dumps(line, separators=(",", ":")) + "\n")
+ CALL_TOTALS["calls"] += 1
+ if cost is None:
+ CALL_TOTALS["cost_missing"] += 1
+ else:
+ CALL_TOTALS["cost"] += cost
def available_providers():
@@ -240,16 +302,18 @@ def _live_chat(messages, tools, model, tool_choice="auto"):
if _COOLDOWN.get(p["name"], 0) > _time.time():
last_err = RuntimeError(f"{p['name']}: cooling down (quota)")
continue
+ sent_model = model or os.environ.get("ANALYST_MODEL") or p["model"]
+ body = {"model": sent_model, "messages": messages, "tools": tools,
+ "tool_choice": tool_choice, "temperature": 0.1,
+ "max_tokens": _MAX_ANSWER_TOKENS}
+ if p["name"] == "openrouter":
+ body["usage"] = {"include": True} # OpenRouter returns usage.cost in USD
try:
r = requests.post(p["url"], timeout=120,
headers={"Authorization": f"Bearer {os.environ[p['env']]}",
"HTTP-Referer": "https://aios.local",
"X-Title": "AIOS Analyst"},
- json={"model": (model or os.environ.get("ANALYST_MODEL")
- or p["model"]),
- "messages": messages, "tools": tools,
- "tool_choice": tool_choice, "temperature": 0.1,
- "max_tokens": _MAX_ANSWER_TOKENS})
+ json=body)
if r.status_code in _DEAD_STATUS:
last_err = RuntimeError(f"{p['name']}: HTTP {r.status_code}")
_COOLDOWN[p["name"]] = _time.time() + 300 # don't re-poke dead auth/payment
@@ -288,8 +352,11 @@ def _live_chat(messages, tools, model, tool_choice="auto"):
saw_retryable = True # NO sleep — next provider NOW
continue
r.raise_for_status()
- usage = r.json().get("usage", {})
- return r.json()["choices"][0]["message"], usage
+ payload = r.json()
+ usage = dict(payload.get("usage") or {})
+ usage["provider"] = p["name"]
+ usage["model"] = payload.get("model") or sent_model
+ return payload["choices"][0]["message"], usage
except requests.RequestException as e:
last_err = e
continue # network blip — next provider
@@ -376,8 +443,8 @@ class _AskContext:
Discovery is not an append-only prompt. Keep the current topic schema, newly requested
metadata body and newest data response, plus every loaded rule. Older bodies remain
retrievable by their original tool/arguments. No process-global or cross-user cache.
- The byte ceiling bounds requests even without a tokenizer; it is deliberately below
- the measured 8k-token provider failure on this registry. Oversize protected material
+ The byte ceiling bounds requests even without a tokenizer; it is set per provider by
+ request_budget(), below each provider's measured request limit. Oversize protected material
stops explicitly rather than being truncated. Artifacts/results are never row-capped.
"""
_READS = frozenset(("list_topics", "describe_topic", "get_recipe", "get_field_values",
@@ -385,10 +452,13 @@ class _AskContext:
_METADATA = frozenset(("list_topics", "describe_topic", "get_recipe"))
# Corpus: initial prompt/tools ~3.2k tokens; schema ~1.8k. Groq's observed 8k
# request limit counts input, not max_tokens. Leave room for exact ops/schema together.
- MAX_REQUEST_BYTES = 32000
+ # The default only. ask() passes the provider's ceiling from request_budget().
+ MAX_REQUEST_BYTES = DEFAULT_REQUEST_BYTES
- def __init__(self, messages, tools):
+ def __init__(self, messages, tools, max_request_bytes=None):
self.messages, self.tools = messages, tools
+ if max_request_bytes:
+ self.MAX_REQUEST_BYTES = max_request_bytes
self.cache, self.entries, self.rules, self.results = {}, [], {}, {}
self.current_topic = None
@@ -510,7 +580,7 @@ class _AskContext:
for e in self.entries], "results": self.results}
-def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX_ITERS,
+def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=None,
telemetry_kind="analyst", user=None):
"""Run one Analyst turn. Returns {answer, artifacts, tool_trace, iterations, exhausted,
usage}. chat_fn(messages, tools, model) -> (assistant_message_dict, usage_dict).
@@ -525,6 +595,8 @@ def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX
return {"answer": ANALYST_DENIED, "artifacts": [], "tool_trace": [],
"iterations": 0, "exhausted": False, "denied": True,
"usage": {"prompt_tokens": 0, "completion_tokens": 0}}
+ if max_iters is None:
+ max_iters = iter_budget()
chat = chat_fn or _live_chat
tools = _tool_schemas()
messages = [{"role": "system", "content": system_prompt()}]
@@ -535,7 +607,9 @@ def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX
messages.append({"role": "user",
"content": f"(today is {_dt.date.today().isoformat()})\n{question}"})
trace, artifacts, usage_total = [], [], {"prompt_tokens": 0, "completion_tokens": 0}
- context = _AskContext(messages, tools)
+ # The live ladder's first provider sets the ceiling. An injected chat_fn has no provider.
+ provider = (available_providers() or [{}])[0].get("name") if chat is _live_chat else None
+ context = _AskContext(messages, tools, request_budget(provider))
for i in range(max_iters):
try:
@@ -547,6 +621,7 @@ def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX
"exhausted": True, "context_exhausted": True, "usage": usage_total,
**context.retained()}
msg, usage = chat(working, tools, model)
+ _log_call({"provider": "chat_fn", "model": model, **(usage or {})})
for k in usage_total:
usage_total[k] += usage.get(k, 0) or 0
tool_calls = msg.get("tool_calls") or []
@@ -556,6 +631,7 @@ def ask(question, history=None, chat_fn=None, model=DEFAULT_MODEL, max_iters=MAX
# questions just get a harmless schema lookup before answering.
if i == 0 and not tool_calls and chat is _live_chat:
msg, usage = _live_chat(working, tools, model, tool_choice="required")
+ _log_call(usage)
for k in usage_total:
usage_total[k] += usage.get(k, 0) or 0
tool_calls = msg.get("tool_calls") or []
diff --git a/platform/harness/datastore.py b/platform/harness/datastore.py
index 9774009cddd845ee5a0ab2d6f9e2d12de6162add..e1ffa94f972603ace5a5674f7704637a0a924164 100644
--- a/platform/harness/datastore.py
+++ b/platform/harness/datastore.py
@@ -1017,6 +1017,102 @@ NUMERIC_FIELDS = ("amount_untaxed", "amount_untaxed_signed", "amount_residual_si
# Odoo also names this many2one without the usual `_id` suffix.
MANY2ONE_FIELDS = frozenset({"product_uom"})
+# S72-T43 / R107: the audited Odoo fields the Data grids show. Each one is declared AND
+# backfilled, because existing rows never re-sync when the schema grows. The list must equal
+# `aios-web/api/odoo_relational.py::audit_mirror_additions()`; verify_odoo_relational holds both.
+AUDIT_FIELD_ADDITIONS = {
+ "account_move": ["amount_total", "amount_total_signed", "amount_total_in_currency_signed",
+ "amount_untaxed", "commercial_partner_id", "commission_total", "create_date",
+ "date", "invoice_payment_term_id", "invoice_user_id", "is_move_sent",
+ "journal_id", "narration", "partner_shipping_id", "payment_reference", "ref",
+ "team_id"],
+ "account_invoice_line_agent": ["amount", "commission_id", "create_date", "settled"],
+ "account_move_line": ["account_root_id", "amount_currency", "create_date", "date_maturity",
+ "full_reconcile_id", "journal_id", "matching_number", "name",
+ "payment_id", "price_subtotal", "price_total", "price_unit",
+ "product_uom_id", "quantity", "reconciled", "ref"],
+ "account_account": ["create_date", "deprecated", "include_initial_balance", "internal_group",
+ "reconcile", "root_id"],
+ "sale_order": ["amount_total", "carrier_id", "commission_total", "create_date",
+ "effective_date", "margin", "margin_percent", "note", "online_payment_based_on",
+ "partner_invoice_id", "partner_shipping_id", "payment_term_id",
+ "picking_policy", "procurement_group_id", "recompute_delivery_price",
+ "require_signature", "user_id", "warehouse_id"],
+ "sale_order_line": ["commission_free", "create_date", "customer_lead", "invoice_status",
+ "is_delivery", "margin_percent", "name", "packaging_price", "price_reduce",
+ "price_reduce_taxexcl", "price_reduce_taxinc", "price_total", "price_unit",
+ "product_packaging_id", "product_packaging_qty", "product_uom",
+ "qty_delivered", "qty_delivered_method", "qty_invoiced", "qty_to_invoice",
+ "salesman_id", "untaxed_amount_invoiced", "untaxed_amount_to_invoice",
+ "untaxed_amount_to_invoice_credit_limit"],
+ "res_partner": ["comment", "commercial_company_name", "commercial_partner_id",
+ "customer_rank", "dba_id", "enable_max_invoice_age", "followup_reminder_type",
+ "is_company", "max_invoice_age", "online_payment", "parent_id", "sale_warn",
+ "supplier_rank", "team_id", "type", "tz", "x_hubspot_company_id"],
+ "stock_picking": ["antsroute_delivery_barcodes", "antsroute_delivery_comment",
+ "antsroute_delivery_date", "antsroute_delivery_driver",
+ "antsroute_delivery_status", "antsroute_delivery_vehicle_plate",
+ "antsroute_nb_delivery_photo", "antsroute_shipping_value", "backorder_id",
+ "carrier_id", "create_date", "currency_id", "date", "date_deadline",
+ "group_id", "is_locked", "location_dest_id", "location_id", "move_type",
+ "picking_type_id", "priority", "sent_to_carrier", "use_antsroute",
+ "user_id"],
+ "stock_move": ["create_date", "date_deadline", "description_picking", "fulfillment_status_id",
+ "group_id", "is_inventory", "origin", "partner_id", "picking_type_id",
+ "priority", "procure_method", "product_packaging_id", "product_qty",
+ "product_uom_qty", "propagate_cancel", "reference", "reservation_date",
+ "rule_id", "sale_line_id", "warehouse_id"],
+ "stock_valuation_layer": ["account_move_id", "description", "unit_cost"],
+ "stock_quant": ["create_date", "in_date", "inventory_date", "inventory_diff_quantity",
+ "package_id", "warehouse_id", "x_warehouse_id"],
+ "stock_location": ["active", "barcode", "company_id", "create_date", "last_inventory_date",
+ "location_id", "name", "warehouse_id"],
+ "purchase_order": ["create_date", "date_planned", "effective_date", "group_id",
+ "invoice_count", "invoice_status", "notes", "partner_ref",
+ "payment_term_id", "picking_type_id", "receipt_status", "user_id"],
+ "purchase_order_line": ["create_date", "name", "price_total", "product_packaging_id",
+ "product_packaging_qty", "qty_invoiced", "qty_received_method",
+ "qty_to_invoice", "total_invoiced"],
+}
+for _entity, _added in AUDIT_FIELD_ADDITIONS.items():
+ _spec = ENTITIES[_entity]
+ _new = [f for f in _added if f not in _spec["fields"]]
+ if _new:
+ _tail = ["write_date"] if "write_date" in _spec["fields"] else []
+ _spec["fields"] = [f for f in _spec["fields"] if f != "write_date"] + _new + _tail
+ _backfill = list(_spec.get("backfill_fields") or [])
+ _spec["backfill_fields"] = _backfill + [f for f in _new if f not in _backfill]
+BOOL_FIELDS += ("deprecated", "enable_max_invoice_age", "include_initial_balance", "is_company",
+ "is_delivery", "is_inventory", "is_locked", "is_move_sent", "online_payment",
+ "propagate_cancel", "recompute_delivery_price", "reconcile", "reconciled",
+ "require_signature", "use_antsroute")
+INT_FIELDS += ("antsroute_nb_delivery_photo", "invoice_count", "max_invoice_age")
+NUMERIC_FIELDS += ("amount_currency", "amount_total_in_currency_signed", "amount_total_signed",
+ "antsroute_shipping_value", "commission_total", "customer_lead",
+ "inventory_diff_quantity", "margin_percent", "packaging_price",
+ "price_reduce", "price_reduce_taxexcl", "price_reduce_taxinc", "price_total",
+ "product_packaging_qty", "qty_delivered", "qty_invoiced", "qty_to_invoice",
+ "total_invoiced", "unit_cost", "untaxed_amount_invoiced",
+ "untaxed_amount_to_invoice", "untaxed_amount_to_invoice_credit_limit")
+
+# Live fields_get confirms these exact comodels (S72-T43). No other comodel data is
+# needed to name the audited relations; archived names remain resolvable too.
+ENTITIES.update({
+ 'account_account_tag': {'model': 'account.account.tag', 'archivable': True,
+ 'fields': ['name', 'active', 'write_date']},
+ 'fulfillment_status': {'model': 'fulfillment.status', 'archivable': True,
+ 'fields': ['name', 'active', 'write_date']},
+})
+AUDIT_M2M_ADDITIONS = {
+ 'account_account': ['tag_ids'],
+ 'sale_order': ['fulfillment_status_ids'],
+ 'stock_picking': ['fulfillment_status_ids'],
+}
+for _entity, _added in AUDIT_M2M_ADDITIONS.items():
+ _spec = ENTITIES[_entity]
+ _spec['m2m'] = list(dict.fromkeys([*_spec.get('m2m', []), *_added]))
+# Each m2m declaration uses _backfill_m2m's own durable per-field completion marker.
+
def _cols(spec):
cols = ["id BIGINT PRIMARY KEY"]
diff --git a/platform/harness/evals.py b/platform/harness/evals.py
index ca40b00e677e54c847743eccb05adfaf30fdf521..85dce7348edc5a5b8326e10745e5377020a2c938 100644
--- a/platform/harness/evals.py
+++ b/platform/harness/evals.py
@@ -79,8 +79,30 @@ def _check(item, result):
return (not reasons), reasons
+def _cost_since(A, start):
+ """Ledger calls and USD cost written since `start`, or None when ANALYST_CALL_LOG is unset."""
+ import os as _os
+ if not _os.environ.get("ANALYST_CALL_LOG"):
+ return None
+ now = A.CALL_TOTALS
+ return {"calls": now["calls"] - start["calls"],
+ "cost_usd": round(now["cost"] - start["cost"], 6),
+ "cost_missing": now["cost_missing"] - start["cost_missing"]}
+
+
+def _print_cost(cost):
+ if cost is not None:
+ print(f"COST: {cost['calls']} model call(s), ${cost['cost_usd']:.4f}"
+ + (f" ({cost['cost_missing']} call(s) returned no cost)"
+ if cost["cost_missing"] else ""))
+
+
def run(chat_fn=None, model=None, only=None, bar=0.8, verbose=True):
- """Run the golden set. Returns {passed, total, pass_rate, gate_ok, results}."""
+ """Run the golden set. Returns {passed, total, pass_rate, gate_ok, results, cost}.
+
+ ANALYST_CALL_LOG names a JSONL cost ledger; `cost` is None when it is unset.
+ ANALYST_EVAL_PACE_S sets the sleep before each item (default 6 s).
+ """
import harness.analyst as A
items = yaml.safe_load(GOLDEN.read_text(encoding="utf-8"))["items"]
if only:
@@ -91,8 +113,11 @@ def run(chat_fn=None, model=None, only=None, bar=0.8, verbose=True):
_os.environ["ANALYST_PATIENT"] = "1" # batch mode: wait out rate windows, don't fail fast
infra_fails = 0
aborted = False
+ pace = float(_os.environ.get("ANALYST_EVAL_PACE_S") or 6)
+ start = dict(A.CALL_TOTALS)
for item in items:
- _time.sleep(6) # pace the free-tier per-minute windows (Groq/Cerebras)
+ _time.sleep(pace) # pace the free-tier per-minute windows (Groq/Cerebras)
+ A.CALL_ITEM = item["id"]
kw = {"chat_fn": chat_fn} if chat_fn else {}
if model:
kw["model"] = model
@@ -109,6 +134,8 @@ def run(chat_fn=None, model=None, only=None, bar=0.8, verbose=True):
infra_fails += 1
if infra_fails >= 2:
aborted = True
+ finally:
+ A.CALL_ITEM = None
passed += ok
results.append({"id": item["id"], "ok": ok, "reasons": reasons,
"usage": res.get("usage"), "iterations": res.get("iterations")})
@@ -117,6 +144,9 @@ def run(chat_fn=None, model=None, only=None, bar=0.8, verbose=True):
print(f" {mark}{item['id']:18s}" + ("" if ok else f" — {'; '.join(reasons)[:90]}"))
if aborted:
break
+ cost = _cost_since(A, start)
+ if verbose:
+ _print_cost(cost)
if aborted:
ran = [r for r in results if not str(r["reasons"])[:60].startswith("['RUN ERROR")]
if verbose:
@@ -124,11 +154,11 @@ def run(chat_fn=None, model=None, only=None, bar=0.8, verbose=True):
f"{passed}/{len(ran) or 1} of the items that actually ran passed. "
"Gate is INCONCLUSIVE (not a model failure); re-run when quota recovers.")
return {"passed": passed, "total": len(items), "pass_rate": None, "gate_ok": False,
- "inconclusive": True, "results": results}
+ "inconclusive": True, "results": results, "cost": cost}
rate = passed / len(items) if items else 0.0
gate = rate >= bar
if verbose:
print(f"\nEVAL: {passed}/{len(items)} = {rate:.0%} GATE({bar:.0%}): "
f"{'PASS' if gate else 'FAIL'}")
return {"passed": passed, "total": len(items), "pass_rate": rate, "gate_ok": gate,
- "results": results}
+ "results": results, "cost": cost}
diff --git a/platform/harness/field_audit.py b/platform/harness/field_audit.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d5da20fad04f261fd93fcc8a65d07e5f832b2e3
--- /dev/null
+++ b/platform/harness/field_audit.py
@@ -0,0 +1,794 @@
+#!/usr/bin/env python
+"""Read-only field audit: every Odoo field and Amazon report column Loopable reads, measured and decided.
+
+`python platform/harness/field_audit.py` (default `--check`) measures and prints the counts, then
+diffs them against `platform/model/audit/field-audit.md`. `--write` regenerates that file.
+
+Decision rule (R107): a field is added if it is stored, filled on more than 5 percent of records,
+and not exposed. Every Odoo call is `fields_get`, `search_count` or `search_read`. The store is
+read inside a READ ONLY transaction. Nothing here writes Odoo, the store or the Amazon mirror.
+"""
+import argparse
+import datetime as _dt
+import os
+import re
+import socket
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+PLATFORM = Path(__file__).resolve().parents[1]
+if str(PLATFORM) not in sys.path:
+ sys.path.insert(0, str(PLATFORM))
+
+MD_PATH = PLATFORM / "model" / "audit" / "field-audit.md"
+THRESHOLD = 0.05
+#: A model whose full count times out is counted on its newest SAMPLE_N records by id.
+SAMPLE_N = 100_000
+TENANT = os.environ.get("AIOS_TENANT") or "royal-imports"
+
+# ---------------------------------------------------------------------------------------------
+# ODOO: the models Loopable reads, and the population each fill rate is counted over.
+# ---------------------------------------------------------------------------------------------
+_ACTIVE_BOTH = ("active", "in", [True, False])
+ODOO_MODELS = {
+ "account.move": {
+ "domain": [("state", "=", "posted"),
+ ("move_type", "in", ["out_invoice", "out_refund", "in_invoice", "in_refund"])],
+ "population": "posted invoices, credit notes, vendor bills and vendor refunds "
+ "(union of the invoices and bills databases)"},
+ "account.move.line": {
+ "domain": [], "population": "every line (the GL lines database applies no filter)"},
+ "account.invoice.line.agent": {
+ "domain": [], "population": "every row (feeds the invoices agent columns)"},
+ "account.account": {"domain": [], "population": "every account"},
+ "sale.order": {
+ "domain": [("state", "in", ["sale", "done"])], "population": "confirmed orders"},
+ "sale.order.line": {
+ "domain": [("order_id.state", "in", ["sale", "done"])],
+ "population": "lines of confirmed orders"},
+ "res.partner": {
+ "domain": ["&", _ACTIVE_BOTH, "|", "|", ("customer_rank", ">", 0),
+ ("supplier_rank", ">", 0), ("agent", "=", True)],
+ "population": "active and archived partners with customer_rank > 0, supplier_rank > 0 "
+ "or the agent flag (union of the customers, vendors and agents databases; "
+ "supplier_rank stands in for the vendors database's posted-bill test)"},
+ "product.product": {
+ "domain": [("active", "=", True)], "population": "active products (the Products database)"},
+ "stock.picking": {
+ "domain": [("picking_type_code", "=", "outgoing")], "population": "outgoing pickings"},
+ "stock.move": {"domain": [], "population": "every stock move"},
+ "stock.location": {"domain": [_ACTIVE_BOTH], "population": "active and archived locations"},
+ "stock.valuation.layer": {"domain": [], "population": "every valuation layer"},
+ "stock.quant": {
+ "domain": [("location_id.usage", "=", "internal")], "population": "quants in internal locations"},
+ "purchase.order": {
+ "domain": [("state", "in", ["purchase", "done"])], "population": "confirmed purchase orders"},
+ "purchase.order.line": {
+ "domain": [("order_id.state", "in", ["purchase", "done"])],
+ "population": "lines of confirmed purchase orders"},
+}
+
+#: Loopable database -> (Odoo model, {column key: Odoo field path}). A dotted path is a join: it
+#: exposes the last field on the related model. None means Loopable derives the column itself.
+DATABASES = (
+ ("invoices", "account.move", {
+ "invoice_no": "name", "odoo_id": "id", "customer": "partner_id.name",
+ "partner_id": "partner_id", "invoice_date": "invoice_date", "due_date": "invoice_date_due",
+ "residual": "amount_residual_signed", "amount_untaxed": "amount_untaxed_signed",
+ "payment_state": "payment_state", "move_type": "move_type", "origin_order": "invoice_origin",
+ "agent": None, "agent_id": None, "wholesale_scope": None, "customer_link": None,
+ "agent_link": None, "order_link": None}),
+ ("bills", "account.move", {
+ "bill_no": "name", "odoo_id": "id", "vendor": "partner_id.name", "vendor_id": "partner_id",
+ "invoice_date": "invoice_date", "due_date": "invoice_date_due",
+ "amount_untaxed": "amount_untaxed_signed", "residual": "amount_residual_signed",
+ "payment_state": "payment_state", "move_type": "move_type", "vendor_link": None}),
+ ("orders", "sale.order", {
+ "order_no": "name", "odoo_id": "id", "customer": "partner_id.name",
+ "partner_id": "partner_id", "order_date": "date_order",
+ "commitment_date": "commitment_date", "delivery_status": "delivery_status",
+ "amount_untaxed": "amount_untaxed", "team": "team_id", "pricelist": "pricelist_id",
+ "state": "state", "invoice_status": "invoice_status", "invoices": None}),
+ ("order_lines", "sale.order.line", {
+ "order_no": "order_id.name", "odoo_id": "id", "order_id": "order_id",
+ "customer": "order_partner_id.name", "partner_id": "order_partner_id",
+ "product": "product_id", "product_id": "product_id", "qty": "product_uom_qty",
+ "price_subtotal": "price_subtotal", "margin": "margin",
+ "purchase_price": "purchase_price", "order_date": "order_id.date_order",
+ "pricelist": "order_id.pricelist_id", "state": "order_id.state"}),
+ ("gl_lines", "account.move.line", {
+ "entry": "move_name", "odoo_id": "id", "move_id": "move_id", "account": "account_id",
+ "account_code": "account_id.code", "customer": "partner_id.name",
+ "partner_id": "partner_id", "product": "product_id", "sku": "product_id.default_code",
+ "date": "date", "debit": "debit", "credit": "credit", "balance": "balance",
+ "line_type": "display_type", "move_type": "move_type", "parent_state": "parent_state"}),
+ ("shipments", "stock.picking", {
+ "picking_no": "name", "odoo_id": "id", "origin": "origin", "order_no": "sale_id.name",
+ "order_id": "sale_id", "customer": "partner_id.name", "partner_id": "partner_id",
+ "state": "state", "scheduled_date": "scheduled_date", "date_done": "date_done",
+ "order_date": "sale_id.date_order", "delivery_days": None, "order_link": None,
+ "customer_link": None}),
+ ("agents", "res.partner", {
+ "agent": "name", "odoo_id": "id", "agent_id": "id", "flagged": "agent",
+ "commissioned": None}),
+ ("vendors", "res.partner", {
+ "vendor": "name", "odoo_id": "id", "vendor_id": "id", "country": "country_id",
+ "email": "email", "phone": "phone", "mobile": "mobile", "vat": "vat", "vendor_ref": "ref",
+ "website": "website", "street": "street", "street2": "street2", "city": "city",
+ "zip": "zip", "bills": None}),
+ ("customers", "res.partner", {
+ "customer": "name", "partner_id": "id", "archived": "active", "odoo_status": "active",
+ "agent": "agent_ids", "agent_id": "agent_ids", "street": "street", "street2": "street2",
+ "city": "city", "state": "state_id", "country": "country_id", "zip": "zip",
+ "customer_since": "create_date", "created_on": "create_date", "tags": "category_id",
+ "pricelist": "property_product_pricelist", "payment_terms": "property_payment_term_id"}),
+ ("accounts", "account.account", {
+ "account_code": "code", "account_name": "name", "odoo_id": "id",
+ "account_type": "account_type", "is_expense": None}),
+ ("stock_moves", "stock.move", {
+ "move": "name", "odoo_id": "id", "product": "product_id", "product_id": "product_id",
+ "sku": "product_id.default_code", "uom": "product_id.uom_id",
+ "standard_price": "product_id.standard_price", "category": "product_id.categ_id",
+ "qty": "quantity_done", "move_uom": "product_uom", "date": "date", "state": "state",
+ "picking_id": "picking_id", "source_location_id": "location_id",
+ "source_location": "location_id.complete_name",
+ "source_location_usage": "location_id.usage",
+ "source_location_fba": "location_id.parent_path",
+ "destination_location_id": "location_dest_id",
+ "destination_location": "location_dest_id.complete_name",
+ "destination_location_usage": "location_dest_id.usage",
+ "destination_location_fba": "location_dest_id.parent_path"}),
+ ("stock_valuation", "stock.valuation.layer", {
+ "odoo_id": "id", "product": "product_id", "product_id": "product_id",
+ "sku": "product_id.default_code", "uom": "product_id.uom_id",
+ "standard_price": "product_id.standard_price", "category": "product_id.categ_id",
+ "qty": "quantity", "value": "value", "date": "create_date",
+ "stock_move_id": "stock_move_id",
+ "source_location_id": "stock_move_id.location_id",
+ "destination_location_id": "stock_move_id.location_dest_id"}),
+ ("stock_quant", "stock.quant", {
+ "odoo_id": "id", "product": "product_id", "product_id": "product_id",
+ "sku": "product_id.default_code", "uom": "product_id.uom_id",
+ "standard_price": "product_id.standard_price", "category": "product_id.categ_id",
+ "location_id": "location_id", "location": "location_id.complete_name",
+ "location_usage": "location_id.usage", "location_fba": "location_id.parent_path",
+ "qty": "quantity", "reserved_qty": "reserved_quantity"}),
+ ("purchase_orders", "purchase.order", {
+ "order_no": "name", "odoo_id": "id", "vendor": "partner_id.name",
+ "vendor_id": "partner_id", "confirmation_date": "date_approve", "order_date": "date_order",
+ "state": "state", "currency": "currency_id", "amount_untaxed": "amount_untaxed",
+ "amount_total": "amount_total"}),
+ ("purchase_lines", "purchase.order.line", {
+ "order_no": "order_id.name", "odoo_id": "id", "order_id": "order_id",
+ "vendor": "order_id.partner_id", "vendor_id": "order_id.partner_id",
+ "confirmation_date": "order_id.date_approve", "state": "order_id.state",
+ "currency": "order_id.currency_id", "product": "product_id", "product_id": "product_id",
+ "sku": "product_id.default_code", "uom": "product_id.uom_id",
+ "purchase_uom": "product_uom", "standard_price": "product_id.standard_price",
+ "category": "product_id.categ_id", "qty": "product_uom_qty", "purchase_qty": "product_qty",
+ "received_qty": "qty_received", "price_unit": "price_unit",
+ "price_subtotal": "price_subtotal", "planned_date": "date_planned"}),
+ ("products", "product.product", {
+ "code": "default_code", "product_id": "id", "product": "display_name",
+ "category": "categ_id", "upc": "barcode", "created_on": "create_date",
+ "incoming": "incoming_qty", "discontinued": "product_tag_ids", "available": "free_qty",
+ "forecasted": "virtual_available", "on_hand": "qty_available",
+ "unit_cost": "standard_price"}),
+)
+
+#: Fields a Loopable column reads that no field path above reaches.
+EXTRA_EXPOSED = {
+ ("account.invoice.line.agent", "agent_id"): ["invoices.agent", "invoices.agent_id"],
+}
+
+#: Fields whose value an exposed column already carries under another name.
+DUPLICATES = {
+ ("account.invoice.line.agent", "invoice_id"): "invoices.odoo_id",
+ ("account.invoice.line.agent", "object_id"): "gl_lines.odoo_id",
+ ("account.move", "invoice_partner_display_name"): "invoices.customer",
+ ("account.move", "sequence_number"): "invoices.invoice_no (its numeric part)",
+ ("account.move", "sequence_prefix"): "invoices.invoice_no (its prefix)",
+ ("res.partner", "email_normalized"): "vendors.email",
+ ("res.partner", "phone_sanitized"): "vendors.phone",
+ ("res.partner", "contact_address_complete"): "customers.street, city, state, zip, country",
+ ("purchase.order", "date_calendar_start"): "purchase_orders.confirmation_date",
+ # Filtered views of one collection: the base collection is the one audited for add.
+ ("stock.picking", "move_line_ids_without_package"): "stock.picking.move_line_ids",
+ ("stock.picking", "move_line_nosuggest_ids"): "stock.picking.move_line_ids",
+ ("stock.picking", "package_level_ids_details"): "stock.picking.package_level_ids",
+ ("stock.move", "move_line_nosuggest_ids"): "stock.move.move_line_ids",
+}
+
+_SECRET = re.compile(r"password|passwd|token|secret|api_key|signup|totp|oauth", re.I)
+_TECHNICAL = re.compile(
+ r"^(id|__last_update|display_name|write_date|write_uid|has_message|website_message_ids"
+ r"|message_.*|activity_.*|my_activity_.*|rating_.*|access_url|access_warning"
+ r"|extract_.*|printnode_.*|quick_edit_.*|color|partner_share|partner_gid"
+ r"|combination_indices|create_uid|sequence|x_studio_related_field_.*|posx|posy|posz"
+ r"|removal_prio|analytic_distribution|tax_audit)$")
+
+#: A many2many to one of these links documents, so it is a relation and not a column. A
+#: many2many to a small label model (tags, statuses, categories) stays a candidate.
+DOCUMENT_MODELS = frozenset((
+ "account.move", "account.move.line", "sale.order", "sale.order.line", "stock.picking",
+ "stock.move", "stock.move.line", "purchase.order", "purchase.order.line", "stock.quant",
+ "stock.valuation.layer", "res.partner", "product.product", "account.analytic.line",
+ "account.partial.reconcile", "account.full.reconcile"))
+_NUMERIC = frozenset(("integer", "float", "monetary"))
+
+
+# ---------------------------------------------------------------------------------------------
+# Decision
+# ---------------------------------------------------------------------------------------------
+def relation_reason(meta):
+ """`relation (...)` for a one2many or a document many2many, else None."""
+ ftype, comodel = meta.get("type"), meta.get("relation") or "?"
+ if ftype == "one2many":
+ inverse = meta.get("relation_field")
+ return f"relation (inverse of {comodel}.{inverse})" if inverse else f"relation (inverse on {comodel})"
+ if ftype == "many2many" and comodel in DOCUMENT_MODELS:
+ return f"relation (links to {comodel})"
+ return None
+
+
+def decide(name, ftype, stored, fill, exposed, duplicate_of, relation=None):
+ """Return (decision, reason) for one field under R107; `constant` is applied by the caller."""
+ if exposed:
+ return "exposed", ""
+ if not stored:
+ return "skip", "computed, not stored"
+ if _SECRET.search(name):
+ return "skip", "secret"
+ if ftype in ("binary", "image"):
+ return "skip", "binary"
+ if _TECHNICAL.match(name) or name.startswith("_") or ftype == "json":
+ return "skip", "technical"
+ if relation:
+ return "skip", relation
+ if duplicate_of:
+ return "skip", f"duplicate of {duplicate_of}"
+ if fill is None:
+ return "add", "fill not measured, stored and not exposed"
+ if fill <= THRESHOLD:
+ return "skip", "filled <= 5%"
+ return "add", "stored, filled > 5%, not exposed"
+
+
+# ---------------------------------------------------------------------------------------------
+# Odoo
+# ---------------------------------------------------------------------------------------------
+def _odoo():
+ from core.odoo import get_odoo
+ return get_odoo()
+
+
+def _exposure(fields_by_model):
+ """{(model, field): [db.key, ...]} from DATABASES and EXTRA_EXPOSED."""
+ end, via = {}, {}
+ for db, model, keys in DATABASES:
+ for key, path in keys.items():
+ if not path:
+ continue
+ current, hops = model, path.split(".")
+ for i, hop in enumerate(hops):
+ bucket = end if i == len(hops) - 1 else via
+ bucket.setdefault((current, hop), []).append(f"{db}.{key}")
+ meta = (fields_by_model.get(current) or {}).get(hop) or {}
+ current = meta.get("relation") or ""
+ if not current:
+ break
+ for pair, keys in EXTRA_EXPOSED.items():
+ end.setdefault(pair, []).extend(keys)
+ # A column that ends on a field names it first; a join that passes through it comes after.
+ return {pair: end.get(pair, []) + [k for k in via.get(pair, []) if k not in end.get(pair, [])]
+ for pair in set(end) | set(via)}
+
+
+def _related_target(fields_by_model, model, related):
+ """Walk a related path to its (model, field), or None when a hop leaves the audited set."""
+ hops = str(related or "").split(".")
+ current = model
+ for hop in hops[:-1]:
+ meta = (fields_by_model.get(current) or {}).get(hop) or {}
+ current = meta.get("relation") or ""
+ if current not in fields_by_model:
+ return None
+ return (current, hops[-1]) if hops and hops[-1] else None
+
+
+def _is_timeout(exc):
+ return isinstance(exc, (socket.timeout, TimeoutError)) or "timed out" in str(exc).lower()
+
+
+def _sample_domain(client, model, domain):
+ """The newest SAMPLE_N records by id, as a domain term list, plus the sample size."""
+ rows = client.search_read(model, domain, ["id"], limit=1, offset=SAMPLE_N - 1, order="id desc")
+ if not rows:
+ return domain, client.search_count(model, domain)
+ return domain + [("id", ">=", rows[0]["id"])], SAMPLE_N
+
+
+#: Counted one field per `search_count`: a collection has no column, a boolean needs share True,
+#: and an attachment-backed binary is not in the table.
+_PER_FIELD_TYPES = {"one2many", "many2many", "boolean", "binary"}
+_GROUP_BY = "create_uid"
+
+
+def _uncounted(name, meta):
+ """Chatter collections stay technical whatever their fill, and one count can take minutes."""
+ return meta.get("type") in ("one2many", "many2many") and bool(_TECHNICAL.match(name))
+
+
+def _batch_counts(client, model, domain, names):
+ """Non-null counts for many scalar fields in ONE read_group; splits the batch on a refusal."""
+ if not names:
+ return {}, []
+ try:
+ groups = client.read_group(model, domain, [f"{n}:count" for n in names], [_GROUP_BY],
+ lazy=False)
+ return {n: sum(int(g.get(n) or 0) for g in groups) for n in names}, []
+ except Exception as exc: # noqa: BLE001
+ if len(names) == 1:
+ return {}, [(names[0], exc)]
+ half = len(names) // 2
+ a, ea = _batch_counts(client, model, domain, names[:half])
+ b, eb = _batch_counts(client, model, domain, names[half:])
+ return {**a, **b}, ea + eb
+
+
+def _field_count(client, model, domain, name, ftype):
+ term = (name, "=", True) if ftype == "boolean" else (name, "!=", False)
+ return client.search_count(model, domain + [term])
+
+
+def _count_model(client, model, domain, fields, log):
+ """({field: filled}, {field: non-null}, [(field, error)]) over `domain`.
+
+ Filled is non-null for a scalar, non-zero for a number, True for a boolean."""
+ stored = [n for n, m in fields.items() if m.get("store") and not _uncounted(n, m)]
+ batch = [n for n in stored if fields[n].get("type") not in _PER_FIELD_TYPES and n != _GROUP_BY]
+ nonnull, failed = _batch_counts(client, model, domain, batch)
+ counts = {n: v for n, v in nonnull.items() if fields[n].get("type") not in _NUMERIC}
+ single = [n for n in stored if n not in counts]
+ errors = []
+ for name in single:
+ started = time.monotonic()
+ ftype = fields[name].get("type") if name not in dict(failed) else ""
+ try:
+ if ftype in _NUMERIC:
+ # Non-zero, written as two ranges: a negative operator also matches NULL in Odoo.
+ counts[name] = client.search_count(
+ model, domain + ["|", (name, ">", 0), (name, "<", 0)])
+ else:
+ counts[name] = _field_count(client, model, domain, name, ftype)
+ except Exception as exc: # noqa: BLE001
+ errors.append((name, exc))
+ if time.monotonic() - started > 10:
+ log(f" slow: {model}.{name} {time.monotonic() - started:.0f} s")
+ return counts, nonnull, errors
+
+
+def _is_constant(client, model, domain, name, ftype, fill, nonnull, total):
+ """True when every record of the population carries one and the same value."""
+ if ftype == "boolean":
+ return fill is not None and fill >= 1.0
+ if nonnull.get(name) != total or not total:
+ return False
+ first = client.search_read(model, domain, [name], limit=1, order="id asc")
+ if not first:
+ return False
+ value = first[0].get(name)
+ if isinstance(value, (list, tuple)):
+ value = value[0] if value else False
+ if value is False or value is None:
+ return False
+ return client.search_count(model, domain + [(name, "!=", value)]) == 0
+
+
+def audit_odoo(log=print):
+ """Measure every field of every model in ODOO_MODELS. Read-only."""
+ client = _odoo()
+ fields_by_model, report = {}, {}
+ for model in ODOO_MODELS:
+ fields_by_model[model] = client.fields_get(
+ model, attributes=("string", "type", "store", "relation", "related",
+ "relation_field"))
+ exposure = _exposure(fields_by_model)
+ for model, spec in ODOO_MODELS.items():
+ started = time.monotonic()
+ domain = list(spec["domain"])
+ fields = fields_by_model[model]
+ total = client.search_count(model, domain)
+ sample, denom = None, total
+ counts, nonnull, errs = (_count_model(client, model, domain, fields, log)
+ if total else ({}, {}, []))
+ timed_out = [n for n, e in errs if _is_timeout(e)]
+ if timed_out:
+ sdom, size = _sample_domain(client, model, domain)
+ sample = {"size": size, "cause": "the full count of " + ", ".join(timed_out)
+ + " exceeded the RPC timeout"}
+ sub = {n: fields[n] for n in timed_out}
+ more, more_nn, errs2 = _count_model(client, model, sdom, sub, log)
+ counts.update({n: v * total / size for n, v in more.items()} if size else {})
+ nonnull.update({n: v * total / size for n, v in more_nn.items()} if size else {})
+ errs = [(n, e) for n, e in errs if n not in timed_out] + errs2
+ errors = [f"{n}: {type(e).__name__}" for n, e in errs]
+ failed = {n for n, _ in errs}
+ rows = []
+ for name in sorted(fields):
+ meta = fields[name]
+ ftype, stored = str(meta.get("type") or ""), bool(meta.get("store"))
+ fill = None
+ uncounted = stored and _uncounted(name, meta)
+ if stored and not total:
+ fill = 0.0
+ elif stored and name not in failed and name in counts:
+ fill = counts[name] / denom
+ exposed = exposure.get((model, name)) or []
+ dup = DUPLICATES.get((model, name))
+ if not dup and meta.get("related") and stored:
+ target = _related_target(fields_by_model, model, meta.get("related"))
+ if target and exposure.get(target) and target != (model, name):
+ dup = exposure[target][0]
+ decision, reason = decide(name, ftype, stored, fill, exposed, dup,
+ relation_reason(meta))
+ if decision == "add":
+ try:
+ if _is_constant(client, model, domain, name, ftype, fill, nonnull, total):
+ decision, reason = "skip", "constant"
+ except Exception as exc: # noqa: BLE001
+ errors.append(f"{name} constant test: {type(exc).__name__}")
+ rows.append({"field": name, "type": ftype, "stored": stored, "fill": fill,
+ "boolean": ftype == "boolean", "numeric": ftype in _NUMERIC,
+ "exposed": exposed,
+ "decision": decision, "reason": reason,
+ "unmeasured": stored and fill is None and not uncounted,
+ "uncounted": uncounted})
+ report[model] = {"total": total, "rows": rows, "errors": errors, "sample": sample,
+ "population": spec["population"], "domain": spec["domain"],
+ "seconds": round(time.monotonic() - started, 1)}
+ log(f"odoo {model}: {len(rows)} fields, {report[model]['seconds']} s"
+ + (f", sample {sample['size']}" if sample else ""))
+ return report
+
+
+# ---------------------------------------------------------------------------------------------
+# Amazon
+# ---------------------------------------------------------------------------------------------
+def _store_connect():
+ import psycopg
+ from core.store_pg import _database_ca_file
+ url = os.environ.get("DATABASE_URL")
+ if not url:
+ raise RuntimeError("DATABASE_URL is not set")
+ kwargs = {"connect_timeout": 20}
+ ca = os.environ.get("AIOS_DATABASE_CA_PEM_B64")
+ if ca:
+ kwargs["sslrootcert"] = str(_database_ca_file(ca))
+ conn = psycopg.connect(url, **kwargs)
+ conn.read_only = True # every transaction is BEGIN READ ONLY
+ return conn
+
+
+def _schema():
+ return "t_" + TENANT.replace("-", "_")
+
+
+_AMZ_NUMERIC = ("BIGINT", "INTEGER", "DOUBLE", "FLOAT", "DECIMAL", "HUGEINT", "SMALLINT", "TINYINT")
+
+
+def _merge_span(spans, name, lo, hi):
+ """Keep the overall (min, max) text of a column across parts; equal means one value."""
+ if lo is None:
+ return
+ old = spans.get(name)
+ spans[name] = (lo, hi) if old is None else (min(old[0], lo), max(old[1], hi))
+
+
+def _parquet_fill(cur, keys, scratch):
+ """Per-column filled, non-null and (min, max) over the parquet parts named by `keys`.
+
+ Filled is non-blank text, or non-zero for a numeric column."""
+ import duckdb
+ filled, nonnull, spans, types, total = {}, {}, {}, {}, 0
+ for key in keys:
+ cur.execute(f"SELECT bytes FROM {_schema()}.store_blobs WHERE path = %s",
+ ("amazon_mirror/" + key,))
+ row = cur.fetchone()
+ if row is None:
+ raise RuntimeError(f"mirror part {key} is missing from store_blobs")
+ path = Path(scratch) / "part.parquet"
+ path.write_bytes(bytes(row[0]))
+ con = duckdb.connect()
+ try:
+ cols = con.execute(f"DESCRIBE SELECT * FROM read_parquet('{path}')").fetchall()
+ filled_x, nonnull_x, span_x = [], [], []
+ for name, ctype, *_ in cols:
+ q = '"' + name.replace('"', '""') + '"'
+ if str(ctype).startswith(_AMZ_NUMERIC):
+ filled_x.append(f"count(*) FILTER (WHERE {q} <> 0)")
+ nonnull_x.append(f"count({q})")
+ elif str(ctype) == "VARCHAR":
+ filled_x.append(f"count(*) FILTER (WHERE trim({q}) <> '')")
+ nonnull_x.append(None) # same as filled
+ else:
+ filled_x.append(f"count({q})")
+ nonnull_x.append(None)
+ # Raw min and max, no per-row cast. Equal means one value.
+ span_x += [f"CAST(min({q}) AS VARCHAR)", f"CAST(max({q}) AS VARCHAR)"]
+ types.setdefault(name, ctype)
+ # Three small queries: one query mixing all three shapes ran 10x slower in DuckDB.
+ src = f"FROM read_parquet('{path}')"
+ n_rows = con.execute(f"SELECT count(*) {src}").fetchone()[0]
+ got_f = con.execute(f"SELECT {', '.join(filled_x)} {src}").fetchone() if cols else ()
+ numeric = [x for x in nonnull_x if x]
+ got_num = iter(con.execute(f"SELECT {', '.join(numeric)} {src}").fetchone() if numeric else ())
+ got_n = [next(got_num) if x else got_f[i] for i, x in enumerate(nonnull_x)]
+ got_s = con.execute(f"SELECT {', '.join(span_x)} {src}").fetchone() if cols else ()
+ finally:
+ con.close()
+ path.unlink(missing_ok=True)
+ total += n_rows
+ for i, (name, *_) in enumerate(cols):
+ filled[name] = filled.get(name, 0) + got_f[i]
+ nonnull[name] = nonnull.get(name, 0) + got_n[i]
+ _merge_span(spans, name, got_s[2 * i], got_s[2 * i + 1])
+ return filled, nonnull, spans, types, total
+
+
+def _store_fill(cur, table):
+ """Per-key non-empty counts over the rows held inside the user_tables document."""
+ cur.execute(
+ f"SELECT kv.key, count(*) FILTER (WHERE kv.value IS NOT NULL AND trim(kv.value) <> ''), "
+ f"min(trim(kv.value)) FILTER (WHERE trim(kv.value) <> ''), "
+ f"max(trim(kv.value)) FILTER (WHERE trim(kv.value) <> '') "
+ f"FROM {_schema()}.store_kv s, jsonb_each(s.value -> %s -> 'rows') r, "
+ f"jsonb_each_text(r.value) kv WHERE s.key = 'user_tables' GROUP BY kv.key", (table,))
+ filled, spans = {}, {}
+ for key, n, lo, hi in cur.fetchall():
+ filled[key] = n
+ _merge_span(spans, key, lo, hi)
+ cur.execute(
+ f"SELECT count(*) FROM {_schema()}.store_kv s, jsonb_object_keys(s.value -> %s -> 'rows') k "
+ f"WHERE s.key = 'user_tables'", (table,))
+ return filled, dict(filled), spans, cur.fetchone()[0]
+
+
+def audit_amazon(log=print):
+ """Measure every column of every Amazon table Loopable declares. Read-only."""
+ import json
+ from harness import amazon_schema as S
+ report, store_error, manifest, defs = {}, None, {}, {}
+ try:
+ conn = _store_connect()
+ except Exception as exc: # noqa: BLE001
+ conn, store_error = None, f"store not reachable: {type(exc).__name__}"
+ cur = conn.cursor() if conn else None
+ if cur is not None:
+ cur.execute(f"SELECT bytes FROM {_schema()}.store_blobs WHERE path = 'amazon_mirror/manifest.json'")
+ row = cur.fetchone()
+ manifest = json.loads(bytes(row[0])) if row else {}
+ cur.execute(
+ f"SELECT t.key, jsonb_path_query_array(t.value -> 'fields', '$[*].key') "
+ f"FROM {_schema()}.store_kv s, jsonb_each(s.value) t "
+ f"WHERE s.key = 'user_tables' AND t.key LIKE 'ut\\_amzn\\_%%'")
+ defs = {k: list(v or []) for k, v in cur.fetchall()}
+ mtables = manifest.get("tables") or {}
+ with tempfile.TemporaryDirectory(prefix="field_audit_") as scratch:
+ for short in sorted(S.TABLE_SPECS):
+ store_key = S.DATABASE_PREFIX + short
+ declared = dict(S.columns_for(short))
+ exposed = set(defs.get(store_key) or [])
+ entry = mtables.get("amzn_" + short)
+ filled, nonnull, spans, types, total, source, cause = {}, {}, {}, {}, None, "", store_error
+ try:
+ if entry and cur is not None:
+ keys = [entry["key"]] if entry.get("key") else [p["key"] for p in entry.get("parts") or []]
+ filled, nonnull, spans, types, total = _parquet_fill(cur, keys, scratch)
+ source = f"Amazon mirror, {len(keys)} parquet part(s)"
+ elif cur is not None and store_key in defs:
+ filled, nonnull, spans, total = _store_fill(cur, store_key)
+ source = "rows inside the user_tables document"
+ if cur is not None and not total:
+ cause = "no rows loaded in the mirror or the store"
+ except Exception as exc: # noqa: BLE001
+ cause = f"read failed: {type(exc).__name__}"
+ conn.rollback()
+ columns = sorted(set(declared) | set(types) | (set(filled) if not types else set()))
+ rows = []
+ for name in columns:
+ fill = (filled.get(name, 0) / total) if total else None
+ ctype = types.get(name) or declared.get(name) or ""
+ is_exposed = name in exposed
+ decision, reason = decide(name, ctype, True, fill, [f"{short}.{name}"] if is_exposed else [], None)
+ if fill is None and decision == "add":
+ decision = "skip"
+ failed = str(cause or "").startswith(("read failed", "store not reachable"))
+ reason = f"not measured: {cause}" if failed else "not measured: 0 rows loaded"
+ elif decision == "add" and total and nonnull.get(name) == total:
+ span = spans.get(name)
+ if span and span[0] == span[1]:
+ decision, reason = "skip", "constant"
+ rows.append({"field": name, "type": ctype, "stored": True, "fill": fill,
+ "boolean": False, "numeric": str(ctype).startswith(_AMZ_NUMERIC),
+ "exposed": [f"{short}.{name}"] if is_exposed else [],
+ "decision": decision, "reason": reason, "unmeasured": fill is None})
+ report[short] = {"total": total, "rows": rows, "source": source, "cause": cause,
+ "defined": store_key in defs, "declared": len(declared)}
+ log(f"amazon {short}: {len(rows)} columns, rows {total}")
+ if conn is not None:
+ conn.close()
+ return report, manifest.get("written_at") or ""
+
+
+# ---------------------------------------------------------------------------------------------
+# Counts and the markdown
+# ---------------------------------------------------------------------------------------------
+def counts(odoo, amazon):
+ def _c(rep):
+ rows = [r for m in rep.values() for r in m["rows"]]
+ return {"models": len(rep), "seen": len(rows),
+ "exposed": sum(1 for r in rows if r["decision"] == "exposed"),
+ "add": sum(1 for r in rows if r["decision"] == "add")}
+ o = _c(odoo)
+ a = _c({k: v for k, v in amazon.items() if v["rows"]})
+ return {"odoo": o, "amazon": a, "total": {k: o[k] + a[k] for k in o}}
+
+
+def _counts_line(c):
+ return (f"models read {c['total']['models']}, fields seen {c['total']['seen']}, "
+ f"fields exposed {c['total']['exposed']}, fields to add {c['total']['add']}")
+
+
+def _pct(row):
+ if row.get("uncounted"):
+ return "not counted (chatter)"
+ if row["fill"] is None:
+ return "not measured" if row["stored"] else "n/a"
+ pct = f"{row['fill'] * 100:.1f}%"
+ if row["boolean"]:
+ return pct + " True"
+ return pct + " non-zero" if row.get("numeric") else pct
+
+
+def _cell(text):
+ return str(text).replace("|", "/").replace("\n", " ")
+
+
+def _table(rows):
+ out = ["| field | type | stored | fill rate | exposed | decision | reason |",
+ "|---|---|---|---|---|---|---|"]
+ for r in rows:
+ exp = ", ".join(r["exposed"][:3]) + (f" +{len(r['exposed']) - 3}" if len(r["exposed"]) > 3 else "")
+ out.append(f"| `{_cell(r['field'])}` | {_cell(r['type'])} | {'yes' if r['stored'] else 'no'} | "
+ f"{_pct(r)} | {_cell(exp) if exp else 'no'} | {r['decision']} | {_cell(r['reason'])} |")
+ return out
+
+
+def _domain_text(domain):
+ return "`" + _cell(repr(domain)) + "`" if domain else "none"
+
+
+def render(odoo, amazon, mirror_written):
+ c = counts(odoo, amazon)
+ today = _dt.date.today().isoformat()
+ L = ["# Field audit: Odoo and Amazon", "",
+ f"Generated by `python platform/harness/field_audit.py --write` on {today}, read-only, "
+ f"tenant `{TENANT}`. Ticket S72-T42, ruling R107.", "",
+ f"**Counts:** {_counts_line(c)}.", "",
+ f"- Odoo: {c['odoo']['models']} models, {c['odoo']['seen']} fields seen, "
+ f"{c['odoo']['exposed']} exposed, {c['odoo']['add']} to add.",
+ f"- Amazon: {c['amazon']['models']} tables with columns, {c['amazon']['seen']} columns seen, "
+ f"{c['amazon']['exposed']} exposed, {c['amazon']['add']} to add.", "",
+ "## Decision rule", "",
+ "A field is **add** if it is stored, filled on more than 5 percent of the population, and "
+ "not exposed. The owner strikes any add from this list (R107). A field a Loopable "
+ "database already shows as a column is **exposed**. Every other field is **skip** with "
+ "one reason:", "",
+ "| reason | meaning |", "|---|---|",
+ "| `filled <= 5%` | 5 percent or less of the population carries a value (non-zero for a number, True for a boolean) |",
+ "| `constant` | one value on every record of the population, for example a single company or currency, or a boolean True on 100 percent |",
+ "| `relation (...)` | a one2many, which is the inverse of a many2one on the named comodel and has no column, or a many2many to a document model |",
+ "| `not measured: 0 rows loaded` | an Amazon column on a table with no rows in the mirror or the store, so no fill can be measured |",
+ "| `computed, not stored` | Odoo computes it on read, so it has no stored value to count or mirror |",
+ "| `secret` | a password, token, key or signup secret |",
+ "| `binary` | an attachment or image |",
+ "| `technical` | the record `id` where no database shows it, chatter, followers, activities, access URLs, `__last_update`, `display_name`, the `write_*` sync stamps, OCR `extract_*` state, print-routing flags, UI helpers (`color`, `quick_edit_*`, `partner_share`, `partner_gid`, `combination_indices`), `create_uid`, `sequence`, Studio `x_studio_related_field_*` helpers, `posx`/`posy`/`posz`, `removal_prio`, `analytic_distribution`, `tax_audit`, any `json` field, or a mirror bookkeeping column (leading `_`) |",
+ "| `duplicate of ` | the same value an exposed column already carries under another name, or a filtered view of a collection this audit already lists |",
+ "", "Fill rate for Odoo is filled records over `search_count(domain)`. A text, date, "
+ "selection or many2one field is counted non-null in one batched `read_group(domain, "
+ "[':count', ...], ['create_uid'])` per model. An integer, float or monetary field "
+ "is counted non-zero with `search_count(domain + ['|', (field, '>', 0), (field, '<', 0)])`, "
+ "marked `non-zero`. A collection is counted with `search_count(domain + [(field, '!=', "
+ "False)])`. A boolean is the share that is True, marked `True`. A candidate is `constant` "
+ "when every record is non-null and `search_count(domain + [(field, '!=', )])` "
+ "is 0. For Amazon, fill is the share of mirror rows whose cell is not blank, or non-zero "
+ "for a numeric column, and a column is `constant` when every row carries a value and its "
+ "minimum equals its maximum. No record value, name or "
+ "partner data is in this file: field names, types and percentages only.", "",
+ "Chatter collections (`message_*`, `activity_*`, `website_message_ids`) show `not counted "
+ "(chatter)`. They are technical whatever their fill, and one count of "
+ "`stock.picking.message_ids` took 361 s when this audit was built.", ""]
+ L += ["## Summary", "", "| source | model or table | records | fields seen | exposed | to add |",
+ "|---|---|---|---|---|---|"]
+ for model, rep in odoo.items():
+ rows = rep["rows"]
+ L.append(f"| Odoo | `{model}` | {rep['total']} | {len(rows)} | "
+ f"{sum(r['decision'] == 'exposed' for r in rows)} | {sum(r['decision'] == 'add' for r in rows)} |")
+ for short, rep in amazon.items():
+ if not rep["rows"]:
+ continue
+ rows = rep["rows"]
+ L.append(f"| Amazon | `{short}` | {rep['total'] if rep['total'] is not None else 'not measured'} | "
+ f"{len(rows)} | {sum(r['decision'] == 'exposed' for r in rows)} | "
+ f"{sum(r['decision'] == 'add' for r in rows)} |")
+ L.append("")
+ for model, rep in odoo.items():
+ L += [f"## Odoo · {model}", "",
+ f"Population: {rep['population']}. Domain: {_domain_text(rep['domain'])}. "
+ f"Records: {rep['total']}.", ""]
+ if rep["sample"]:
+ L += [f"Counted by sample: the newest {rep['sample']['size']} records by id, because "
+ f"{rep['sample']['cause']}.", ""]
+ if rep["errors"]:
+ L += [f"Not measured ({len(rep['errors'])}): " + ", ".join(_cell(e) for e in rep["errors"]) + ".", ""]
+ L += _table(rep["rows"]) + [""]
+ empty = [s for s, r in amazon.items() if not r["rows"]]
+ for short, rep in amazon.items():
+ if not rep["rows"]:
+ continue
+ rows_note = (f"Records: {rep['total']} ({rep['source']})." if rep["total"]
+ else f"Fill not measured: {rep['cause']}.")
+ L += [f"## Amazon · {short}", "",
+ f"Loopable database `ut_amzn_{short}`"
+ f"{'' if rep['defined'] else ' (not defined in the store)'}. {rows_note}"
+ + (f" Mirror manifest written {mirror_written}." if rep["total"] and mirror_written else ""), ""]
+ L += _table(rep["rows"]) + [""]
+ if empty:
+ L += ["## Amazon tables with no columns to audit", "",
+ "These tables declare no columns in `amazon-report-schemas.json` and have no rows in "
+ "the mirror or the store, so there is no column list to audit until a sync loads them: "
+ + ", ".join(f"`{s}`" for s in empty) + ".", ""]
+ return "\n".join(L), c
+
+
+def _md_counts(text):
+ m = re.search(r"\*\*Counts:\*\* models read (\d+), fields seen (\d+), fields exposed (\d+), "
+ r"fields to add (\d+)", text)
+ return tuple(int(x) for x in m.groups()) if m else None
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ mode = ap.add_mutually_exclusive_group()
+ mode.add_argument("--write", action="store_true", help="regenerate the markdown")
+ mode.add_argument("--check", action="store_true", help="print counts and diff the markdown (default)")
+ ap.add_argument("--quiet", action="store_true", help="no per-model progress lines")
+ args = ap.parse_args(argv)
+ log = (lambda *_: None) if args.quiet else (lambda m: print(m, file=sys.stderr, flush=True))
+ odoo = audit_odoo(log)
+ amazon, written = audit_amazon(log)
+ text, c = render(odoo, amazon, written)
+ print(_counts_line(c))
+ for src in ("odoo", "amazon"):
+ print(f"{src}: models {c[src]['models']}, seen {c[src]['seen']}, "
+ f"exposed {c[src]['exposed']}, add {c[src]['add']}")
+ if args.write:
+ MD_PATH.parent.mkdir(parents=True, exist_ok=True)
+ with open(MD_PATH, "w", encoding="utf-8", newline="") as fh:
+ fh.write(text + "\n")
+ print(f"wrote {MD_PATH.relative_to(PLATFORM.parent)}")
+ return 0
+ have = _md_counts(MD_PATH.read_text(encoding="utf-8")) if MD_PATH.exists() else None
+ want = (c["total"]["models"], c["total"]["seen"], c["total"]["exposed"], c["total"]["add"])
+ if have != want:
+ print(f"DIFF: the markdown says {have}, the live audit says {want}. Run --write.")
+ return 1
+ print("markdown counts match")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/platform/harness/semantic.py b/platform/harness/semantic.py
index 446198d19e536e24c17af33aa26dc51eb4bacc56..54dbb9a9b46cab9e668c750e1bbf5e0f4de0d24f 100644
--- a/platform/harness/semantic.py
+++ b/platform/harness/semantic.py
@@ -413,7 +413,7 @@ def _eval_expr(expr, resolve):
raise ModelError(f"unparseable derived expr {expr!r}: {e}")
-def metric(key, date_from=None, date_to=None, team_id=None, _seen=None):
+def metric(key, date_from=None, date_to=None, team_id=None, _seen=None, *, runtime=None, user=None):
"""Resolve a registered metric to a number for a window (+optional BU). The only public
compute path — every surface that shows this metric goes through here."""
_seen = _seen or set()
@@ -423,6 +423,9 @@ def metric(key, date_from=None, date_to=None, team_id=None, _seen=None):
m = _model()["metrics"].get(key)
if not m:
raise ModelError(f"unknown metric {key!r}")
+ if key == 'amazon_order_count':
+ return store_query('amazon_orders', [key], date_from=date_from, date_to=date_to,
+ team_id=team_id, runtime=runtime, user=user)['rows'][0][key]
agg = m.get("agg")
if agg == "ratio":
num = metric(m["numerator"], date_from, date_to, team_id, _seen)
@@ -585,7 +588,13 @@ def _v_line_vs_move_grain(date_from, date_to, team_id):
return ours, (gross or 0) - (refunds or 0)
+def _v_amazon_sales_order_count(date_from, date_to, team_id, *, runtime=None, user=None):
+ from harness import amazon_semantic
+ return amazon_semantic.validate(date_from, date_to, team_id, runtime=runtime, user=user)
+
+
_VALIDATORS = {
+ "amazon_sales_order_count": _v_amazon_sales_order_count,
"returns_sign": _v_returns_sign,
"line_vs_move_grain": _v_line_vs_move_grain,
"order_level_revenue": _v_order_level_revenue,
@@ -600,7 +609,7 @@ from modules.finance_spine import FINANCE_VALIDATORS
_VALIDATORS.update(FINANCE_VALIDATORS)
-def validate_metric(key, date_from=None, date_to=None, team_id=None, tol=0.01):
+def validate_metric(key, date_from=None, date_to=None, team_id=None, tol=0.01, *, runtime=None, user=None):
"""Run a metric's declared independent cross-check. Returns the standard check dict
(the validate.py convention: check/ok/gap)."""
m = _model()["metrics"].get(key)
@@ -613,7 +622,15 @@ def validate_metric(key, date_from=None, date_to=None, team_id=None, tol=0.01):
fn = _VALIDATORS.get(contract["method"])
if not fn:
raise ModelError(f"metric {key!r}: unknown validate method {contract['method']!r}")
- ours, independent = fn(date_from, date_to, team_id)
+ if key == 'amazon_order_count':
+ try:
+ ours, independent = fn(date_from, date_to, team_id, runtime=runtime, user=user)
+ except ModelError as exc:
+ return {"check": f"semantic.{key}: source proof unavailable", "ok": False,
+ "gap": None, "state": "unproven", "reason": str(exc)}
+ tol = 0 # Order counts reconcile exactly; a money tolerance cannot forgive missing orders.
+ else:
+ ours, independent = fn(date_from, date_to, team_id)
if m.get('format') == 'date':
gap = 0 if str(ours or '')[:10] == str(independent or '')[:10] else 1
else:
@@ -1068,12 +1085,20 @@ def _scope_for_binding(store, scope_variant=None):
def store_query(topic, measures, group_by=None, grain=None, date_from=None, date_to=None,
team_id=None, filters=None, sort=None, limit=1000, exclude_services=False,
- filter_tree=None, filter_conj="and", today=None, scope_variant=None, related=None):
+ filter_tree=None, filter_conj="and", today=None, scope_variant=None, related=None,
+ *, runtime=None, user=None):
"""The semantic query over the tenant store — the engine behind the Analyst's
run_semantic_query tool and the saved-view re-runner. All keys whitelisted against the model."""
t = _model()["topics"].get(topic)
if not t or "store" not in t:
raise ModelError(f"topic {topic!r} has no store binding")
+ if topic == 'amazon_orders':
+ if (list(measures or []) != ['amazon_order_count'] or team_id is not None or filters
+ or filter_tree or scope_variant is not None or related is not None or exclude_services):
+ raise ModelError('Amazon Sales summary cannot validate a different measure or restricted scope')
+ from harness import amazon_semantic
+ return amazon_semantic.query(date_from, date_to, runtime=runtime, user=user,
+ group_by=group_by, grain=grain, sort=sort, limit=limit)
s = t["store"]
pin_predicate, pin_params = None, []
if related is not None:
@@ -1285,6 +1310,8 @@ def store_rows(topic, date_from=None, date_to=None, team_id=None, filter_tree=No
t = _model()["topics"].get(topic)
if not t or "store" not in t:
raise ModelError(f"topic {topic!r} has no store binding")
+ if topic == 'amazon_orders':
+ raise ModelError('Amazon semantic rows require a scoped database reader; use the Data row door')
from harness import filter_sql as _fs
s = t["store"]
alias = s["alias"]
@@ -1385,6 +1412,8 @@ def store_field_values(topic, dim, search=None, limit=25):
t = _model()["topics"].get(topic)
if not t or "store" not in t:
raise ModelError(f"topic {topic!r} has no store binding")
+ if topic == 'amazon_orders':
+ raise ModelError('Amazon field values require a scoped database reader; use the Data field door')
d = (t["store"].get("dims") or {}).get(dim)
if not d:
raise UnknownColumnError(f"unknown dim {dim!r} for topic {topic!r}", column=dim)
diff --git a/platform/harness/tools.py b/platform/harness/tools.py
index abe20f02086f3dd6f9e242cf6928fdc9776365a4..3d9b768d8517658ee1299759b6db6c65d9996f04 100644
--- a/platform/harness/tools.py
+++ b/platform/harness/tools.py
@@ -14,6 +14,7 @@ are explicit and confirm-gated by recipe. Errors return a uniform envelope the m
import json
import time
import uuid
+from contextvars import ContextVar
from pathlib import Path
import harness.semantic as SEM
@@ -22,6 +23,9 @@ VIEWS_PATH = Path(__file__).resolve().parents[1] / "data" / "store" / "views.jso
_RESULTS = {} # result_id -> query result (session-scoped working memory for chart tools)
_RESULTS_CAP = 40
+# Set only by a server-side dispatch caller, never by tool arguments or saved query JSON.
+_REQUEST_CONTEXT = ContextVar('semantic_request_context', default=(None, None))
+_RESULT_CALLERS = {}
# The exhaustive chart vocabulary (2026-07-16): every Zelazny comparison form has a kind, so the
# Analyst never lacks a shape. The model picks by the CHART PICKER guide (analyst.py) + the
@@ -49,11 +53,28 @@ _QUERY_KEYS = ("topic", "measures", "group_by", "grain", "date_from", "date_to",
def _remember(res):
rid = uuid.uuid4().hex[:10]
_RESULTS[rid] = res
+ if res.get('topic') == 'amazon_orders':
+ runtime, user = _REQUEST_CONTEXT.get()
+ _RESULT_CALLERS[rid] = (runtime, user.get('username'))
while len(_RESULTS) > _RESULTS_CAP:
- _RESULTS.pop(next(iter(_RESULTS)))
+ oldest = next(iter(_RESULTS))
+ _RESULTS.pop(oldest)
+ _RESULT_CALLERS.pop(oldest, None)
return rid
+def _result(result_id):
+ res = _RESULTS.get(result_id)
+ if res and res.get('topic') == 'amazon_orders':
+ runtime, user = _REQUEST_CONTEXT.get()
+ if (runtime is None or not isinstance(user, dict)
+ or _RESULT_CALLERS.get(result_id) != (runtime, user.get('username'))):
+ raise SEM.ModelError('Amazon result requires its requesting runtime and caller')
+ # Fresh permission/source checks also apply to cached artifacts and transforms.
+ SEM.store_query(**res['query'], runtime=runtime, user=user)
+ return res
+
+
def _ok(data):
return {"ok": True, "data": data}
@@ -127,7 +148,8 @@ def run_semantic_query(topic, measures, group_by=None, grain=None, date_from=Non
# (the BELLA FLORIST wrong-decliner incident, 2026-07-17).
res = SEM.store_query(topic, measures, group_by=group_by, grain=grain, date_from=date_from,
date_to=date_to, team_id=team_id, filters=filters, sort=sort,
- limit=limit, exclude_services=exclude_services)
+ limit=limit, exclude_services=exclude_services,
+ runtime=_REQUEST_CONTEXT.get()[0], user=_REQUEST_CONTEXT.get()[1])
# Echo the full query onto the result: chart specs built from it carry the query, so a SAVED
# view is a re-runnable QUERY (the OM-3 viewer re-executes it live), never a stale snapshot.
res["query"] = {"topic": topic, "measures": list(measures or []), "group_by": group_by,
@@ -163,7 +185,7 @@ def get_field_values(topic, dim, search=None):
def transform_result(result_id, transforms):
"""Apply governed ANALYTICS TRANSFORMS to a query result -> a NEW result_id to chart/table.
The chain is recorded on the derived result, so saved views replay query -> transforms live."""
- res = _RESULTS.get(result_id)
+ res = _result(result_id)
if not res:
raise SEM.ModelError(f"unknown result_id {result_id!r}; run run_semantic_query first")
import harness.transforms as TR
@@ -177,7 +199,9 @@ def transform_result(result_id, transforms):
def _run_query(q):
- return SEM.store_query(**{k: q.get(k) for k in _QUERY_KEYS if q.get(k) is not None})
+ runtime, user = _REQUEST_CONTEXT.get()
+ return SEM.store_query(**{k: q.get(k) for k in _QUERY_KEYS if q.get(k) is not None},
+ runtime=runtime, user=user)
# ------------------------------------------------------------------ viz tools (emit OUR specs)
@@ -188,7 +212,7 @@ def make_chart(result_id, kind, x, y=None, title=None, series=None, y2=None, siz
enforced — the model never emits HTML/vega). Extra encodings per kind: combo/bullet need y2
(line/target), bubble needs size, heatmap needs value (the colour measure); facet (a dim
column) turns line|bar|area|scatter into small multiples."""
- res = _RESULTS.get(result_id)
+ res = _result(result_id)
if not res:
raise SEM.ModelError(f"unknown result_id {result_id!r}; run run_semantic_query first")
if kind not in CHART_KINDS:
@@ -227,7 +251,7 @@ def make_chart(result_id, kind, x, y=None, title=None, series=None, y2=None, siz
def make_table(result_id, columns=None, title=None):
"""First-class TABLE artifact: the exact rows, house-formatted (sortable, totals row, the
drill IS the table). columns (optional) picks and orders a subset."""
- res = _RESULTS.get(result_id)
+ res = _result(result_id)
if not res:
raise SEM.ModelError(f"unknown result_id {result_id!r}; run run_semantic_query first")
rows = res["rows"]
@@ -243,7 +267,7 @@ def make_table(result_id, columns=None, title=None):
def make_kpi_card(result_id, metric, compare_result_id=None):
- res = _RESULTS.get(result_id)
+ res = _result(result_id)
if not res or not res["rows"]:
raise SEM.ModelError("result_id missing/empty; run a scalar run_semantic_query first")
val = res["rows"][0].get(metric)
@@ -251,8 +275,9 @@ def make_kpi_card(result_id, metric, compare_result_id=None):
raise SEM.ModelError(f"{metric!r} not in result")
card = {"kpi": {"metric": metric, "value": val, "result_id": result_id,
"query": res.get("query")}}
- if compare_result_id and _RESULTS.get(compare_result_id, {}).get("rows"):
- prev = _RESULTS[compare_result_id]["rows"][0].get(metric)
+ comparison = _result(compare_result_id) if compare_result_id else None
+ if comparison and comparison.get("rows"):
+ prev = comparison["rows"][0].get(metric)
if prev:
card["kpi"]["delta_pct"] = (val - prev) / abs(prev)
card["kpi"]["compare_result_id"] = compare_result_id
@@ -521,14 +546,18 @@ def openai_tools():
for k, v in TOOLS.items()]
-def dispatch(name, arguments):
+def dispatch(name, arguments, *, runtime=None, user=None):
"""Uniform tool execution for the Analyst loop: JSON-safe result or a readable error the
- model can act on. Never raises."""
+ model can act on. Runtime/user are trusted request arguments; unbound callers refuse
+ tenant-bound metrics. Never take identity from model JSON. Never raises."""
t = TOOLS.get(name)
if not t:
return _err(f"unknown tool {name!r} (tools: {list(TOOLS)})")
+ token = _REQUEST_CONTEXT.set((runtime, user))
try:
args = json.loads(arguments) if isinstance(arguments, str) else dict(arguments or {})
+ if {'runtime', 'user', 'session'} & args.keys():
+ return _err('request identity cannot be supplied in tool arguments')
missing = [r for r in t["parameters"].get("required", []) if r not in args]
if missing:
return _err(f"missing required arguments: {missing}")
@@ -537,3 +566,5 @@ def dispatch(name, arguments):
return _err(e)
except Exception as e:
return _err(f"{type(e).__name__}: {e}")
+ finally:
+ _REQUEST_CONTEXT.reset(token)
diff --git a/platform/model/knowledge/amazon.yml b/platform/model/knowledge/amazon.yml
new file mode 100644
index 0000000000000000000000000000000000000000..c08a15df416234b989bf0be18b2c4813404f89c8
--- /dev/null
+++ b/platform/model/knowledge/amazon.yml
@@ -0,0 +1,169 @@
+# Amazon knowledge pack: what the assistant reads before it queries an Amazon database.
+# loopy_skills.py serves it, filtered to the databases the caller can open.
+# Amazon columns are measured from each report header at sync (amazon_schema PROVENANCE), so no
+# static column list exists. Field keys here are names the code already types: amazon_schema
+# TABLE_SPECS identities and relationships, connector_spec links, and amazon_relational's
+# date, money and quantity name sets. verify_agent_knowledge.py gates this.
+# Plain ASCII only. The assistant repeats this text to users.
+source: amazon
+connector: amazon_sp
+title: Amazon
+
+scope:
+ orders:
+ database: ut_amzn_orders
+ date_field: purchase_date
+ rule: "For orders by day, week or month, count rows of ut_amzn_orders grouped by the day of purchase_date. One row is one order."
+ cancelled:
+ field: order_status
+ values: [Cancelled]
+ rule: "Exclude rows whose order_status is Cancelled when you count orders or sum sales."
+ read_only:
+ rule: "Amazon data is read only. Never create, change or send anything to Amazon."
+
+traps:
+ - id: field_list_first
+ text: "Read the database's field list before a query. A field missing from the list does not exist in this workspace yet, because Amazon columns appear at the first sync."
+ - id: dates_are_text
+ text: "Amazon dates such as purchase_date are ISO 8601 text in UTC. The day is the first 10 characters. Say the days are UTC days."
+ - id: currency
+ text: "Amounts are in the currency field of each row. Do not add amounts across currencies."
+ - id: sku_keys
+ text: "The seller SKU is sku on orders, order items, settlements and fee estimates, msku on inventory, and seller_sku on listings and referral fees. Join on these, not on the product name."
+ - id: amazon_vs_odoo
+ text: "Odoo also carries the Amazon channel as the GIFTWARE DEALS partner. For an Amazon order or fee question use these databases, not Odoo."
+
+databases:
+ ut_amzn_orders:
+ label: Amazon orders
+ row: "One Amazon order, from the all orders report. The first line of the order supplies its item columns."
+ fields:
+ money: [item_price, item_tax, shipping_price]
+ quantity: [quantity]
+ date: [purchase_date, last_updated_date]
+ status: [order_status]
+ joins:
+ - {database: ut_amzn_order_items, from: amazon_order_id, to: amazon_order_id}
+ - {database: ut_amzn_settlements, from: amazon_order_id, to: order_id}
+ - {database: ut_amzn_listings, from: sku, to: seller_sku}
+ traps:
+ - id: orders_by_day
+ text: "This is the database for how many orders arrived per day. Count rows by the day of purchase_date and exclude order_status Cancelled."
+ - id: first_line_only
+ text: "item_price, quantity and sku here belong to the order's first line only. For units or sales of a whole order use ut_amzn_order_items."
+ - id: pending_price
+ text: "A Pending order has no item_price yet. Do not read a blank price as zero sales."
+
+ ut_amzn_order_items:
+ label: Amazon order items
+ row: "One line of one Amazon order: one SKU with its quantity and price."
+ fields:
+ money: [item_price, item_tax, shipping_price, item_promotion_discount]
+ quantity: [quantity]
+ date: [purchase_date, last_updated_date]
+ status: [order_status, item_status]
+ joins:
+ - {database: ut_amzn_orders, from: amazon_order_id, to: amazon_order_id}
+ - {database: ut_amzn_listings, from: sku, to: seller_sku}
+ traps:
+ - id: line_total
+ text: "item_price is the total for the line's quantity, not a unit price. Sum item_price for sales and quantity for units."
+ - id: count_distinct
+ text: "amazon_order_id repeats on every line of an order. Count distinct amazon_order_id for an order count, or use ut_amzn_orders."
+
+ ut_amzn_settlements:
+ label: Amazon settlements
+ row: "One line of an Amazon settlement report: one charge, fee or payment inside one payout."
+ fields:
+ money: [amount, total_amount]
+ quantity: [quantity_purchased]
+ date: [posted_date, settlement_start_date, settlement_end_date, deposit_date]
+ status: [amount_type, amount_description]
+ joins:
+ - {database: ut_amzn_orders, from: order_id, to: amazon_order_id}
+ - {database: ut_amzn_listings, from: sku, to: seller_sku}
+ traps:
+ - id: signed_amounts
+ text: "amount is signed. Fees and refunds are negative, so the sum of amount is net proceeds. Group by amount_type and amount_description to split sales from fees."
+ - id: summary_line
+ text: "The first line of each settlement carries total_amount and deposit_date and no order. Never add total_amount to amount."
+ - id: payout_date
+ text: "posted_date is when a line was posted. deposit_date is when the payout reached the bank. Use posted_date for activity by day."
+
+ ut_amzn_inventory:
+ label: Amazon inventory
+ row: "One product at one disposition and location for one day, from the FBA inventory ledger summary."
+ fields:
+ money: []
+ quantity: [starting_warehouse_balance, receipts, customer_shipments, customer_returns, ending_warehouse_balance]
+ date: [date]
+ status: []
+ joins:
+ - {database: ut_amzn_listings, from: msku, to: seller_sku}
+ - {database: ut_amzn_listings, from: asin, to: asin1}
+ traps:
+ - id: one_day_only
+ text: "Each day repeats the stock. Sum ending_warehouse_balance for one date only, never across dates."
+ - id: sellable
+ text: "Filter disposition SELLABLE for stock a customer can buy. Other dispositions are damaged or held stock."
+
+ ut_amzn_fba_fee_estimates:
+ label: Amazon FBA fee estimates
+ row: "One SKU in one Amazon store on one snapshot day, with Amazon's estimated fees per unit."
+ fields:
+ money: [estimated_fee_total, estimated_referral_fee_per_unit, expected_fulfillment_fee_per_unit, your_price]
+ quantity: []
+ date: [_snapshot_date]
+ status: []
+ joins:
+ - {database: ut_amzn_listings, from: sku, to: seller_sku}
+ - {database: ut_amzn_listings, from: asin, to: asin1}
+ traps:
+ - id: latest_snapshot
+ text: "Each sync adds a new _snapshot_date. Use the latest _snapshot_date for current fees."
+ - id: estimate_not_charge
+ text: "These are estimates per unit, not fees Amazon charged. Charged fees are in ut_amzn_settlements."
+
+ ut_amzn_referral_fees:
+ label: Amazon referral fee preview
+ row: "One seller SKU on one snapshot day, with its price and Amazon's referral fee preview."
+ fields:
+ money: [price]
+ quantity: []
+ date: [_snapshot_date]
+ status: []
+ joins:
+ - {database: ut_amzn_listings, from: seller_sku, to: seller_sku}
+ - {database: ut_amzn_listings, from: asin, to: asin1}
+ traps:
+ - id: latest_snapshot
+ text: "Each sync adds a new _snapshot_date. Use the latest _snapshot_date for current fees."
+
+ ut_amzn_storage_fees:
+ label: Amazon storage fees
+ row: "One product at one fulfillment center for one month, with its estimated monthly storage fee."
+ fields:
+ money: [estimated_monthly_storage_fee]
+ quantity: []
+ date: [month]
+ status: []
+ joins:
+ - {database: ut_amzn_listings, from: asin, to: asin1}
+ traps:
+ - id: per_center
+ text: "A product has one row per fulfillment_center each month. Sum across centers for its monthly fee."
+
+ ut_amzn_listings:
+ label: Amazon listings
+ row: "One active or inactive listing for one seller SKU."
+ fields:
+ money: [price]
+ quantity: [quantity]
+ date: [open_date]
+ status: []
+ joins:
+ - {database: ut_amzn_orders, from: seller_sku, to: sku}
+ - {database: ut_amzn_inventory, from: seller_sku, to: msku}
+ traps:
+ - id: one_snapshot
+ text: "Listings keeps one copy per snapshot day. Use the latest day for the current catalogue."
diff --git a/platform/model/knowledge/odoo.yml b/platform/model/knowledge/odoo.yml
new file mode 100644
index 0000000000000000000000000000000000000000..c743475fa9170ec964a26449d2be72f45e967c17
--- /dev/null
+++ b/platform/model/knowledge/odoo.yml
@@ -0,0 +1,314 @@
+# Odoo knowledge pack: what the assistant reads before it queries an Odoo database.
+# loopy_skills.py serves it, filtered to the databases the caller can open.
+# Field keys must exist in each database's contract (odoo_relational.TABLES field functions,
+# aios_grid_fields.json for customer_data and product_data). verify_agent_knowledge.py gates this.
+# Plain ASCII only. The assistant repeats this text to users.
+source: odoo
+connector: odoo
+title: Odoo
+
+scope:
+ confirmed_orders:
+ field: state
+ values: [sale, done]
+ rule: "A confirmed sale order has state sale or done. Count only those rows as orders or sales."
+ wholesale:
+ field: wholesale_scope
+ excluded_partner: GIFTWARE DEALS
+ rule: "The GIFTWARE DEALS partner is the Amazon channel and is out of wholesale scope. For a wholesale figure, keep only rows where wholesale_scope is ticked."
+ inventory:
+ rule: "Inventory, SKU and dead stock analysis uses all channels, including the Amazon channel. Do not apply the wholesale filter to stock."
+ business_units:
+ values: [Fisch, Royal]
+ rule: "The Business Units are Fisch and Royal. A user scoped to one Business Unit sees only that unit. Never infer the other unit's figures."
+ read_only:
+ rule: "Odoo is read only. Never create, change, post or send an Odoo record."
+
+traps:
+ - id: field_list_first
+ text: "Read the database's field list before a query. A field missing from the list does not exist for this user."
+ - id: sku_key
+ text: "The product code is the code field on product_data and the sku field on every other Odoo database. Join on product_id, not on the code."
+ - id: validated_figures
+ text: "A figure from a raw row sum is not a validated metric. Use a validated metric when one answers the question."
+
+generated_tables:
+ prefix: ut_odoo_model_
+ note: "A ut_odoo_model_ database mirrors one Odoo model a workspace added itself. Its field list is the only contract. One row is one record of that model. The scope rules above still apply when it carries state or wholesale_scope."
+
+databases:
+ customer_data:
+ label: Customers
+ row: "One Odoo customer (res.partner) with its contact, AR and buying summary."
+ fields:
+ money: [ar_open, ar_overdue, ar_outstanding, ar_exposure, ar_aged_1_30, ar_aged_31_60, ar_aged_61_90, ar_aged_90_plus]
+ quantity: [sku_count]
+ date: [customer_since, last_order, created_on]
+ status: [odoo_status, archived]
+ joins:
+ - {database: ut_odoo_invoices, from: partner_id, to: partner_id}
+ - {database: ut_odoo_orders, from: partner_id, to: partner_id}
+ - {database: ut_odoo_order_lines, from: partner_id, to: partner_id}
+ - {database: ut_odoo_shipments, from: partner_id, to: partner_id}
+ - {database: ut_odoo_gl_lines, from: partner_id, to: partner_id}
+ traps:
+ - id: archived_customers
+ text: "Archived customers stay in this database. Filter archived when you count active customers."
+
+ product_data:
+ label: Products
+ row: "One Odoo product variant (product.product) with prices, stock and sales summary."
+ fields:
+ money: [first_cost, unit_cost, price_1, price_2, price_3, rev_ytd, rev_ly, inv_value, inventory_value_per_quantity]
+ quantity: [on_hand, fba, incoming, pre_book_qty, open_backlog_qty, qty_ytd, qty_ltm, orders_ytd, demand_fwd, cover_gap_units]
+ date: [created_on]
+ status: [stock_bucket, discontinued, needs_pricing, inventory_value_per_quantity_state]
+ joins:
+ - {database: ut_odoo_order_lines, from: product_id, to: product_id}
+ - {database: ut_odoo_stock_quant, from: product_id, to: product_id}
+ - {database: ut_odoo_stock_moves, from: product_id, to: product_id}
+ - {database: ut_odoo_stock_valuation, from: product_id, to: product_id}
+ - {database: ut_odoo_purchase_lines, from: product_id, to: product_id}
+ traps:
+ - id: fba_locations
+ text: "on_hand includes FBA stock, and fba holds that FBA part. FBA stock sits in Odoo locations 18423 and 18424 in the reference workspace. Subtract fba from on_hand for stock you can ship from the warehouse."
+ - id: all_channels
+ text: "Stock and SKU figures here cover all channels. Do not apply the wholesale filter to them."
+
+ ut_odoo_invoices:
+ label: Odoo invoices
+ row: "One customer invoice or credit note (account.move)."
+ fields:
+ money: [amount_untaxed, residual]
+ quantity: []
+ date: [invoice_date, due_date, refreshed]
+ status: [payment_state, move_type, wholesale_scope]
+ joins:
+ - {database: customer_data, from: partner_id, to: partner_id}
+ - {database: ut_odoo_agents, from: agent_id, to: agent_id}
+ - {database: ut_odoo_orders, from: origin_order, to: order_no}
+ traps:
+ - id: credit_notes
+ text: "move_type out_refund rows are credit notes. Net them against invoices or exclude them on purpose, never by accident."
+ - id: signed_residual
+ text: "residual is signed and exactly 0 on a settled document, so an AR sum needs no payment filter."
+ - id: many_agents
+ text: "agent_id is blank when an invoice has more than one agent. The agent field lists every name."
+
+ ut_odoo_orders:
+ label: Odoo orders
+ row: "One sale order (sale.order)."
+ fields:
+ money: [amount_untaxed]
+ quantity: []
+ date: [order_date, commitment_date, refreshed]
+ status: [state, delivery_status, invoice_status, team, wholesale_scope]
+ joins:
+ - {database: customer_data, from: partner_id, to: partner_id}
+ - {database: ut_odoo_order_lines, from: odoo_id, to: order_id}
+ - {database: ut_odoo_invoices, from: order_no, to: origin_order}
+ - {database: ut_odoo_shipments, from: odoo_id, to: order_id}
+ traps:
+ - id: confirmed_state
+ text: "Count an order only when state is sale or done."
+ - id: wholesale_filter
+ text: "Keep wholesale_scope ticked for a wholesale figure. Unticked rows are the Amazon channel."
+
+ ut_odoo_agents:
+ label: Odoo agents
+ row: "One sales agent (res.partner) found by its agent flag or its commission lines."
+ fields:
+ money: []
+ quantity: []
+ date: [refreshed]
+ status: [flagged, commissioned]
+ joins:
+ - {database: ut_odoo_invoices, from: agent_id, to: agent_id}
+ traps:
+ - id: agent_union
+ text: "This database is the union of flagged agents and agents with commission lines. An unflagged agent is still real."
+
+ ut_odoo_accounts:
+ label: Odoo GL accounts
+ row: "One general ledger account (account.account)."
+ fields:
+ money: []
+ quantity: []
+ date: [refreshed]
+ status: [account_type, is_expense]
+ joins:
+ - {database: ut_odoo_gl_lines, from: account_code, to: account_code}
+ traps: []
+
+ ut_odoo_vendors:
+ label: Odoo vendors
+ row: "One vendor (res.partner) with contact details."
+ fields:
+ money: []
+ quantity: []
+ date: [refreshed]
+ status: []
+ joins:
+ - {database: ut_odoo_bills, from: vendor_id, to: vendor_id}
+ - {database: ut_odoo_purchase_orders, from: vendor_id, to: vendor_id}
+ - {database: ut_odoo_purchase_lines, from: vendor_id, to: vendor_id}
+ traps: []
+
+ ut_odoo_bills:
+ label: Odoo vendor bills
+ row: "One vendor bill or vendor refund (account.move)."
+ fields:
+ money: [amount_untaxed, residual]
+ quantity: []
+ date: [invoice_date, due_date, refreshed]
+ status: [payment_state, move_type]
+ joins:
+ - {database: ut_odoo_vendors, from: vendor_id, to: vendor_id}
+ traps:
+ - id: vendor_refunds
+ text: "move_type in_refund rows are vendor refunds. Net them against bills or exclude them on purpose."
+ - id: bill_date
+ text: "The bill date is the invoice_date field."
+
+ ut_odoo_order_lines:
+ label: Odoo order lines
+ row: "One sale order line (sale.order.line)."
+ fields:
+ money: [price_subtotal, margin, purchase_price]
+ quantity: [qty]
+ date: [order_date]
+ status: [state, wholesale_scope]
+ joins:
+ - {database: ut_odoo_orders, from: order_id, to: odoo_id}
+ - {database: customer_data, from: partner_id, to: partner_id}
+ - {database: product_data, from: product_id, to: product_id}
+ traps:
+ - id: fractional_returns
+ text: "qty can be fractional and is negative on a return. Do not round it or drop negative lines."
+ - id: section_lines
+ text: "Section and note lines have no product. Exclude a blank product from SKU counts."
+ - id: unit_cost
+ text: "purchase_price is a cost per unit. Multiply by qty for a line cost."
+ - id: confirmed_state
+ text: "Count a line only when state is sale or done, and keep wholesale_scope ticked for a wholesale figure."
+
+ ut_odoo_gl_lines:
+ label: Odoo GL lines
+ row: "One journal item (account.move.line)."
+ fields:
+ money: [debit, credit, balance]
+ quantity: []
+ date: [date]
+ status: [parent_state, line_type, wholesale_scope]
+ joins:
+ - {database: ut_odoo_accounts, from: account_code, to: account_code}
+ - {database: customer_data, from: partner_id, to: partner_id}
+ traps:
+ - id: posted_only
+ text: "Keep parent_state posted for reported figures. Draft and cancelled entries are not in the books."
+ - id: balance_nets
+ text: "balance is debit minus credit and sums to zero over a whole entry. Sum it per account, never per entry."
+ - id: blank_account
+ text: "account_code is blank on some lines. A join to ut_odoo_accounts drops them."
+
+ ut_odoo_stock_moves:
+ label: Odoo stock moves
+ row: "One stock move (stock.move) of one product between two locations."
+ fields:
+ money: [standard_price]
+ quantity: [qty]
+ date: [date]
+ status: [state, source_location_fba, destination_location_fba]
+ joins:
+ - {database: product_data, from: product_id, to: product_id}
+ - {database: ut_odoo_stock_valuation, from: odoo_id, to: stock_move_id}
+ - {database: ut_odoo_shipments, from: picking_id, to: odoo_id}
+ traps:
+ - id: fba_locations
+ text: "FBA stock sits in Odoo locations 18423 and 18424 in the reference workspace. Use source_location_fba and destination_location_fba, which find FBA in each workspace's own location tree."
+ - id: move_unit
+ text: "qty is in move_uom, which can differ from the product unit in uom."
+
+ ut_odoo_stock_valuation:
+ label: Odoo stock valuation
+ row: "One stock valuation layer (stock.valuation.layer) for one product."
+ fields:
+ money: [value, standard_price]
+ quantity: [qty]
+ date: [date]
+ status: [source_location_fba, destination_location_fba]
+ joins:
+ - {database: product_data, from: product_id, to: product_id}
+ - {database: ut_odoo_stock_moves, from: stock_move_id, to: odoo_id}
+ traps:
+ - id: fba_locations
+ text: "FBA stock sits in Odoo locations 18423 and 18424 in the reference workspace. Use the location FBA fields, not the ids."
+
+ ut_odoo_stock_quant:
+ label: Odoo stock on hand
+ row: "One quantity of one product at one location (stock.quant)."
+ fields:
+ money: [standard_price]
+ quantity: [qty, reserved_qty]
+ date: []
+ status: [location_usage, location_fba]
+ joins:
+ - {database: product_data, from: product_id, to: product_id}
+ traps:
+ - id: fba_locations
+ text: "FBA stock sits in Odoo locations 18423 and 18424 in the reference workspace. Use location_fba to split FBA stock from warehouse stock."
+ - id: location_usage
+ text: "Filter location_usage before you sum on-hand stock. Not every location holds sellable stock."
+ - id: reserved
+ text: "reserved_qty is part of qty. Available stock is qty minus reserved_qty."
+
+ ut_odoo_purchase_orders:
+ label: Odoo purchase orders
+ row: "One purchase order (purchase.order)."
+ fields:
+ money: [amount_untaxed, amount_total]
+ quantity: []
+ date: [order_date, confirmation_date]
+ status: [state]
+ joins:
+ - {database: ut_odoo_vendors, from: vendor_id, to: vendor_id}
+ - {database: ut_odoo_purchase_lines, from: odoo_id, to: order_id}
+ traps:
+ - id: confirmed_purchase
+ text: "A confirmed purchase order has state purchase or done. Draft and sent rows are requests for quotation."
+ - id: order_currency
+ text: "Amounts are in the order's own currency field. Do not add amounts across currencies."
+
+ ut_odoo_purchase_lines:
+ label: Odoo purchase order lines
+ row: "One purchase order line (purchase.order.line)."
+ fields:
+ money: [price_unit, price_subtotal, standard_price]
+ quantity: [qty, purchase_qty, received_qty]
+ date: [confirmation_date, planned_date]
+ status: [state]
+ joins:
+ - {database: ut_odoo_purchase_orders, from: order_id, to: odoo_id}
+ - {database: ut_odoo_vendors, from: vendor_id, to: vendor_id}
+ - {database: product_data, from: product_id, to: product_id}
+ traps:
+ - id: purchase_units
+ text: "A purchase order quantity is in purchase units (packs), not product units. purchase_qty and received_qty count purchase_uom units. qty is the same quantity in product units."
+ - id: order_currency
+ text: "Amounts are in the order's own currency field. Do not add amounts across currencies."
+
+ ut_odoo_shipments:
+ label: Odoo shipments
+ row: "One delivery (stock.picking) for a sale order."
+ fields:
+ money: []
+ quantity: []
+ date: [scheduled_date, date_done, order_date, refreshed]
+ status: [state]
+ joins:
+ - {database: ut_odoo_orders, from: order_id, to: odoo_id}
+ - {database: customer_data, from: partner_id, to: partner_id}
+ - {database: ut_odoo_stock_moves, from: odoo_id, to: picking_id}
+ traps:
+ - id: done_only
+ text: "Only state done shipments have a ship date. delivery_days is blank when either date is missing."
diff --git a/platform/model/metrics/amazon_orders.yml b/platform/model/metrics/amazon_orders.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8d1aad5e0987b3c6c0e1b742b36bee5b29cd7f17
--- /dev/null
+++ b/platform/model/metrics/amazon_orders.yml
@@ -0,0 +1,17 @@
+topic: amazon_orders
+metrics:
+ - key: amazon_order_count
+ label: Amazon orders
+ agg: count_distinct
+ field: amazon_order_id
+ format: int
+ empty: zero
+ description: Distinct non-cancelled Amazon orders placed in the complete UTC date window.
+ ai_context: >
+ Count distinct Amazon order ids by purchase date in UTC. Exclude Cancelled and Canceled.
+ This is the tenant seller's Amazon marketplace scope, not Odoo's GIFTWARE channel.
+ Both dates must match the completed Amazon Sales getOrderMetrics summary interval.
+ Missing or empty mirrors, missing summaries and restricted callers are refused.
+ validate:
+ method: amazon_sales_order_count
+ independent: Amazon Sales getOrderMetrics orderCount from the completed source summary
diff --git a/platform/model/metrics/invoice_lines.yml b/platform/model/metrics/invoice_lines.yml
index 59bbb45da84463138ad5bea59e3e68963cb1b937..461a4db71f4ceb50650085c1f5807fc0c789d490 100644
--- a/platform/model/metrics/invoice_lines.yml
+++ b/platform/model/metrics/invoice_lines.yml
@@ -76,8 +76,9 @@ metrics:
ai_context: >-
Two defensible readings and this is the WIDER one (salesperson-covered business counts as
unallocated). The narrower "no commission row at all" figure is this metric sliced to
- allocation = 'none'. On Fisch 2025 the two are $1,447,579.59 vs $1,086,381.35 — a material
- gap, so state which reading you gave.
+ allocation = 'none'. This metric is gross invoice-line sales before credit notes.
+ Refund subtotals are stored positive. The net sales metric subtracts them.
+ State which reading you gave and derive its value for the requested scope.
- key: agent_line_customers
label: Customers with an agent on the line
diff --git a/platform/model/topics/amazon_fees.yml b/platform/model/topics/amazon_fees.yml
new file mode 100644
index 0000000000000000000000000000000000000000..0a0fc16844206fa723de94f24b91fdc158bf4d87
--- /dev/null
+++ b/platform/model/topics/amazon_fees.yml
@@ -0,0 +1,68 @@
+# An ENTITY topic for Amazon's FBA fee estimates (one row per SKU per Amazon store per snapshot
+# day). Charged fees are in ut_amzn_settlements. Amazon rows live in the connector store, not the
+# DuckDB mirror, so this topic has no `store:` block and no validated measure yet.
+key: amazon_fees
+semantic:
+ approved: [_snapshot_date, sku, asin, amazon_store, your_price, estimated_fee_total, estimated_referral_fee_per_unit, expected_fulfillment_fee_per_unit, currency]
+ date_field: _snapshot_date
+ scope: "Amazon's estimated fees per unit for each SKU, one snapshot per sync day. Use the latest _snapshot_date for current fees. Fees Amazon charged are in Amazon settlements."
+ measure_not_yet:
+ - key: estimated_fee_total
+ cause: "Amazon fee estimates live in the connector store, not the semantic mirror, and no metric reconciles them yet."
+ fix: "Add a fee metric in model/metrics with a validate method that ties the stored rows to the report row count, and register its validator in harness/semantic.py."
+ purposes:
+ _snapshot_date: "The sync day of the estimate. Use the latest one for current fees."
+ estimated_fee_total: "Amazon's estimated total fee per unit."
+ estimated_referral_fee_per_unit: "Amazon's estimated referral fee per unit."
+ expected_fulfillment_fee_per_unit: "Amazon's expected FBA fulfillment fee per unit."
+ synonyms:
+ estimated_fee_total: [total fee, Amazon fee, fees]
+ estimated_referral_fee_per_unit: [referral fee, commission]
+ expected_fulfillment_fee_per_unit: [FBA fee, fulfillment fee, pick and pack fee]
+ sku: [seller sku]
+ choices: {}
+label: "Amazon FBA fee estimates"
+entity: amazon.fba_fee_estimate
+grid: ut_amzn_fba_fee_estimates
+subject: "amazon:fba_fee_estimate"
+grain: "one row per SKU per Amazon store per snapshot day"
+fields:
+ - key: _snapshot_date
+ label: "Snapshot date"
+ type: date
+ kind: data
+ - key: sku
+ label: "Sku"
+ type: text
+ kind: data
+ - key: asin
+ label: "Asin"
+ type: text
+ kind: data
+ - key: amazon_store
+ label: "Amazon store"
+ type: text
+ kind: data
+ - key: your_price
+ label: "Your price"
+ type: currency
+ kind: data
+ - key: estimated_fee_total
+ label: "Estimated fee total"
+ type: currency
+ kind: data
+ - key: estimated_referral_fee_per_unit
+ label: "Estimated referral fee per unit"
+ type: currency
+ kind: data
+ - key: expected_fulfillment_fee_per_unit
+ label: "Expected fulfillment fee per unit"
+ type: currency
+ kind: data
+ - key: currency
+ label: "Currency"
+ type: text
+ kind: data
+ai_context: >
+ Amazon's estimated fees per unit by SKU. Use the latest _snapshot_date. These are estimates, not
+ charges: for fees Amazon charged, use Amazon settlements and sum the negative amount lines.
diff --git a/platform/model/topics/amazon_inventory.yml b/platform/model/topics/amazon_inventory.yml
new file mode 100644
index 0000000000000000000000000000000000000000..fb0ccdfb6cbf5b82bdb573a08b215ae5df0fc683
--- /dev/null
+++ b/platform/model/topics/amazon_inventory.yml
@@ -0,0 +1,75 @@
+# An ENTITY topic for the Amazon inventory database (FBA inventory ledger summary, one row per
+# product, disposition and location per day). Amazon rows live in the connector store, not the
+# DuckDB mirror, so this topic has no `store:` block and no validated measure yet.
+key: amazon_inventory
+semantic:
+ approved: [date, msku, fnsku, asin, disposition, location, starting_warehouse_balance, receipts, customer_shipments, customer_returns, ending_warehouse_balance]
+ date_field: date
+ scope: "FBA inventory ledger summary by day. Each day repeats the stock, so sum ending_warehouse_balance for one date only. Filter disposition SELLABLE for stock a customer can buy."
+ measure_not_yet:
+ - key: fba_units_on_hand
+ cause: "Amazon inventory lives in the connector store, not the semantic mirror, and no metric reconciles it yet."
+ fix: "Add an FBA units metric in model/metrics with a validate method that ties the ledger summary to the ledger detail, and register its validator in harness/semantic.py."
+ purposes:
+ date: "The ledger day of the row."
+ msku: "The seller SKU. Join it to Amazon listings seller_sku."
+ ending_warehouse_balance: "Units at the end of the day. Sum it for one date only."
+ disposition: "SELLABLE is stock a customer can buy. Other values are damaged or held stock."
+ synonyms:
+ msku: [sku, seller sku]
+ ending_warehouse_balance: [on hand, stock, units in stock]
+ customer_shipments: [units shipped]
+ choices: {}
+label: "Amazon inventory"
+entity: amazon.inventory_ledger_summary
+grid: ut_amzn_inventory
+subject: "amazon:inventory"
+grain: "one row per product, disposition and location per day"
+fields:
+ - key: date
+ label: "Date"
+ type: date
+ kind: data
+ - key: msku
+ label: "Msku"
+ type: text
+ kind: data
+ - key: fnsku
+ label: "Fnsku"
+ type: text
+ kind: data
+ - key: asin
+ label: "Asin"
+ type: text
+ kind: data
+ - key: disposition
+ label: "Disposition"
+ type: text
+ kind: data
+ - key: location
+ label: "Location"
+ type: text
+ kind: data
+ - key: starting_warehouse_balance
+ label: "Starting warehouse balance"
+ type: int
+ kind: data
+ - key: receipts
+ label: "Receipts"
+ type: int
+ kind: data
+ - key: customer_shipments
+ label: "Customer shipments"
+ type: int
+ kind: data
+ - key: customer_returns
+ label: "Customer returns"
+ type: int
+ kind: data
+ - key: ending_warehouse_balance
+ label: "Ending warehouse balance"
+ type: int
+ kind: data
+ai_context: >
+ Amazon FBA stock by day. Sum ending_warehouse_balance on the latest date only, with disposition
+ SELLABLE, for units a customer can buy. Never sum it across dates.
diff --git a/platform/model/topics/amazon_orders.yml b/platform/model/topics/amazon_orders.yml
new file mode 100644
index 0000000000000000000000000000000000000000..f52fa7f952cbcb2131ce91eef1c9a533f5a74d88
--- /dev/null
+++ b/platform/model/topics/amazon_orders.yml
@@ -0,0 +1,77 @@
+# Amazon's order-head mirror and its independent Sales summary share the tenant-bound file.
+# Runtime reads require an explicit runtime, unrestricted caller and matching summary interval.
+# Field keys are snake_case Amazon report headers (amazon_store._snake), the same keys the grid shows.
+key: amazon_orders
+semantic:
+ approved: [amazon_order_id, purchase_date, last_updated_date, order_status, sku, asin, quantity, item_price, currency]
+ date_field: purchase_date
+ scope: "Distinct Amazon order ids in this tenant seller's connected marketplace and complete UTC purchase-date window. Exclude order_status Cancelled and Canceled. Both dates must match the completed Amazon Sales summary interval. This is not the Odoo wholesale or GIFTWARE scope."
+ measure:
+ key: amazon_order_count
+ source: amazon_orders
+ validate: amazon_sales_order_count
+ purposes:
+ amazon_order_id: "The Amazon order number. One row per order, so count rows for an order count."
+ purchase_date: "When the buyer placed the order, ISO 8601 text in UTC. Use it for orders by day, week or month."
+ order_status: "Pending, Unshipped, Shipped or Cancelled. Exclude both Cancelled and Canceled from order counts and sales."
+ item_price: "The first line's price for its quantity. Use Amazon order items for whole order sales."
+ synonyms:
+ amazon_order_id: [order number, order id, Amazon order]
+ purchase_date: [order date, purchase date, ordered on]
+ order_status: [status]
+ choices:
+ order_status: [Pending, Unshipped, Shipped, Cancelled]
+label: "Amazon orders"
+entity: amazon.order
+grid: ut_amzn_orders
+subject: "amazon:order"
+grain: "one row per Amazon order (document grain)"
+store:
+ source: amazon_sp
+ table: amzn_orders
+ alias: o
+ date_col: o.purchase_date
+ scope_sql: "lower(COALESCE(o.order_status, '')) NOT IN ('cancelled', 'canceled')"
+ dims:
+ purchase_date: {col: "CAST(CAST(o.purchase_date AS TIMESTAMPTZ) AT TIME ZONE 'UTC' AS DATE)", type: date}
+fields:
+ - key: amazon_order_id
+ label: "Amazon order id"
+ type: text
+ kind: data
+ - key: purchase_date
+ label: "Purchase date"
+ type: date
+ kind: data
+ - key: last_updated_date
+ label: "Last updated date"
+ type: date
+ kind: data
+ - key: order_status
+ label: "Order status"
+ type: text
+ kind: data
+ - key: sku
+ label: "Sku"
+ type: text
+ kind: data
+ - key: asin
+ label: "Asin"
+ type: text
+ kind: data
+ - key: quantity
+ label: "Quantity"
+ type: int
+ kind: data
+ - key: item_price
+ label: "Item price"
+ type: currency
+ kind: data
+ - key: currency
+ label: "Currency"
+ type: text
+ kind: data
+ai_context: >
+ Amazon orders at document grain. For how many orders arrived per day, count rows grouped by the
+ UTC day of purchase_date and exclude order_status Cancelled and Canceled. The order count must
+ reconcile to Amazon Sales for the same full interval. For units or sales use Amazon order items.
diff --git a/platform/model/topics/invoice_lines.yml b/platform/model/topics/invoice_lines.yml
index 07358d6844865f711d40e9ad7156983f39901f53..d92806f3b6c4b24400bf5b6830ed0160ef1b47e8 100644
--- a/platform/model/topics/invoice_lines.yml
+++ b/platform/model/topics/invoice_lines.yml
@@ -15,7 +15,7 @@ semantic:
approved: []
date_field: ""
date_col_note: "l.date"
- scope: "Product lines on posted customer invoices and credit notes only, by line date; untaxed subtotals with refunds negated; business unit comes from the originating sales order, direct invoices retain a null unit, and no partner is excluded."
+ scope: "Product lines on posted customer invoices and credit notes only, by line date; stored untaxed subtotals are positive for both populations, and net invoiced line sales subtracts the credit-note component; business unit comes from the originating sales order, direct invoices retain a null unit, and no partner is excluded."
measure: {key: invoiced_line_sales, validate: line_vs_move_grain}
label: Customer invoice lines (with commission agent)
entity: account.move.line
@@ -41,7 +41,7 @@ scope:
excluded: >-
Nothing is excluded by partner. GIFTWARE DEALS (Amazon) sits on its own team (7), so a
Fisch or Royal filter already excludes it — no partner-name exclusion needed here.
- basis: "untaxed line subtotals (price_subtotal); credit-note lines are NEGATED by the metric"
+ basis: "untaxed line subtotals (price_subtotal); net sales subtracts positive credit-note subtotals from invoice subtotals"
date_field: "line date (= invoice date)"
grain: >-
@@ -135,8 +135,9 @@ ai_context: >
figure is, because the two readings differ materially and the questioner may mean either.
BUSINESS UNIT comes from the originating sale order, so a line with no sale order has a NULL
business unit — present that as "no sale order (direct invoice)" and keep it in company totals.
- Fisch is team 5. CREDIT NOTES are included and the revenue metric negates them; a positive
- refund total means the negation was lost.
+ Fisch is team 5. CREDIT NOTES are included. Stored refund subtotals and the refund component
+ are positive; invoiced_line_sales subtracts that component. Gross allocation metrics use
+ invoices only. State which population and metric the answer uses.
MEASURED BASELINE for FISCH 2025 (use to sanity-check any answer): total $4,443,244.34 over
68,540 lines and 979 customers, splitting exactly into $2,995,664.75 allocated to agents,
$361,198.24 salesperson-only, and $1,086,381.35 not allocated. 518 customers have a real agent
diff --git a/platform/model/topics/odoo_customers.yml b/platform/model/topics/odoo_customers.yml
index 768bdca6dc19de62a55357cc718323c32b2c7c93..6ad64e1428f54bb93e724f367f7c1fe23ee978b4 100644
--- a/platform/model/topics/odoo_customers.yml
+++ b/platform/model/topics/odoo_customers.yml
@@ -7,12 +7,12 @@
# trained on a schema the product does not have.
key: odoo_customers
semantic:
- approved: [customer, agent, dba, salesperson, city, state, country, customer_since, last_order, pricelist, payment_terms]
+ approved: [customer, agent, dba, salesperson, city, state, country, customer_since, last_order, pricelist, payment_terms, source_notes, company_name, commercial_partner, customer_rank, doing_business_as, invoice_age_limit, reminders, is_company, max_invoice_age, online_payment, parent_company, sales_warning, supplier_rank, sales_team, address_type, timezone, hubspot_company_id]
date_field: ""
date_col_note: "sales_lines.o.date_order"
scope: "One row per customer in the customer book who ordered in the last 24 months; this registry has no date dimension, and dated wholesale revenue uses sales_lines joined by order_partner."
measure: {key: revenue, source: sales_lines, validate: order_level_revenue}
- sensitive: [street, street2, zip, lat, lon, notes]
+ sensitive: [street, street2, zip, lat, lon, notes, source_notes, hubspot_company_id]
purposes:
customer: "The customer account in the customer book, identified by partner_id."
partner_id: "The Odoo res.partner id used to join this customer to sales orders and invoices."
@@ -292,6 +292,24 @@ fields:
sensitivity: restricted
means: "Your notes on this customer. Saved in this app only, visible only to you."
+ - {key: source_notes, label: "Source notes", type: text, kind: data, means: "Customer notes from res.partner.comment, with HTML removed.", semantic: {role: private_note, sensitivity: restricted}}
+ - {key: company_name, label: "Company name", type: text, kind: data, means: "The commercial company name from res.partner.commercial_company_name."}
+ - {key: commercial_partner, label: "Commercial entity", type: text, kind: data, means: "The resolved name of res.partner.commercial_partner_id."}
+ - {key: customer_rank, label: "Customer rank", type: int, kind: data, means: "The source customer rank from res.partner.customer_rank; a setting, not sales revenue."}
+ - {key: doing_business_as, label: "Doing business as", type: text, kind: data, means: "The resolved res.partner.dba_id name; distinct from the sales-derived brand column dba."}
+ - {key: invoice_age_limit, label: "Invoice age limit on", type: checkbox, kind: data, means: "The boolean res.partner.enable_max_invoice_age setting."}
+ - {key: reminders, label: "Reminders", type: text, kind: data, means: "The res.partner.followup_reminder_type selection."}
+ - {key: is_company, label: "Company", type: checkbox, kind: data, means: "The boolean res.partner.is_company flag."}
+ - {key: max_invoice_age, label: "Max invoice age", type: int, kind: data, means: "The res.partner.max_invoice_age limit in days; not an additive financial measure."}
+ - {key: online_payment, label: "Online payment", type: checkbox, kind: data, means: "The boolean res.partner.online_payment setting."}
+ - {key: parent_company, label: "Related company", type: text, kind: data, means: "The resolved name of res.partner.parent_id."}
+ - {key: sales_warning, label: "Sales warning", type: text, kind: data, means: "The res.partner.sale_warn selection."}
+ - {key: supplier_rank, label: "Supplier rank", type: int, kind: data, means: "The source supplier rank from res.partner.supplier_rank; a setting, not purchases."}
+ - {key: sales_team, label: "Sales team", type: text, kind: data, means: "The resolved name of res.partner.team_id."}
+ - {key: address_type, label: "Address type", type: text, kind: data, means: "The res.partner.type selection."}
+ - {key: timezone, label: "Timezone", type: text, kind: data, means: "The res.partner.tz selection."}
+ - {key: hubspot_company_id, label: "HubSpot company ID", type: text, kind: data, means: "The res.partner.x_hubspot_company_id identifier, preserved as text.", semantic: {role: entity_id, sensitivity: restricted}}
+
ai_context: >
The customer REGISTRY as a person sees it in the app — the database labelled 'Odoo customers'.
Use it to answer 'who is this customer', 'which customers exist', 'which agent owns them', 'where are they', and for the AR columns it carries (ar_open, ar_overdue, days_to_pay), which are reconciled by modules/ar.py.
diff --git a/platform/model/topics/odoo_products.yml b/platform/model/topics/odoo_products.yml
index 1aa808d155d91d9b1b5f6c5b4cb54dbea45839fc..feb2999cf3904053f732e7f6394d6b967226ab7b 100644
--- a/platform/model/topics/odoo_products.yml
+++ b/platform/model/topics/odoo_products.yml
@@ -1,26 +1,19 @@
# ⭐⭐ W33-T49 (owner item 13) — an ENTITY topic: the semantic layer can finally see
# the databases a person actually opens, not only the line and document grains.
#
-# ⛔ THE `fields:` BLOCK IS A HAND-MAINTAINED, CURATED SUBSET OF THE GRID'S FIELD
-# CONTRACT, AND NOTHING ENFORCES IT. This comment used to say the block was GENERATED
-# and "held to it by `verify_query.py::section_entity_topics`. Do not hand-edit a field
-# row." MEASURED 2026-08-24: `section_entity_topics` does not exist anywhere in the tree
-# and no gate compares this file to `aios_grid_fields.json`, so that sentence was an
-# unchecked claim forbidding the only edit anyone can actually make
-# ([[a-declared-gate-is-an-unchecked-claim]]).
+# ⛔ THE `fields:` BLOCK IS A HAND-MAINTAINED SUBSET OF THE GRID'S FIELD CONTRACT. No
+# generator writes it ([[a-declared-gate-is-an-unchecked-claim]]).
#
-# What is TRUE: 9 of the product contract's keys are deliberately absent (D-400 —
-# incoming, cover_gap_units, demand_fwd, discontinued, needs_pricing, march_pricelist,
-# price_changes, closeouts, notes), and no key here is absent from the contract. So a
-# field row IS hand-edited, and the rule is the honest one: the key, type and label must
-# match `aios_grid_fields.json`, because the agent is otherwise trained on a schema the
-# product does not have. ⭐ D-400 GATE, 2026-09-16: `platform/verify_product_pool.py::
-# section_product_field_contract` now holds this file, the json and `pd_fields` in step.
-# Its `YML_ABSENT_KEYS` also lists 11 keys absent here WITHOUT a documented reason (fba and
-# the ten category/attribute columns); whether they belong here is a decision still owed.
+# What is TRUE: a field row IS hand-edited. Its key, type and label must match
+# `aios_grid_fields.json` in the json's order, because the agent is otherwise trained on a
+# schema the product does not have. `platform/verify_product_pool.py::
+# section_product_field_contract` holds this file, the json and `pd_fields` in step.
+# S72-T41 (R107, D-766): a contract key absent from this file must carry a written reason in
+# that gate's `YML_ABSENT_REASONS`. A key the Assistant names in a governed query must also be
+# in `semantic.approved`, or `semantic_registry.require_approved` refuses it.
key: odoo_products
semantic:
- approved: [code, product_id, product, category, supplier, origin_country, lead_days, first_cost, price_1, unit_1, price_2, unit_2, price_3, unit_3]
+ approved: [code, product_id, product_tmpl_id, volume, product, category, supplier, origin_country, lead_days, first_cost, price_1, unit_1, price_2, unit_2, price_3, unit_3, upc, on_hand, available, forecasted]
date_field: ""
date_col_note: "sales_lines.o.date_order"
scope: "Every active product, including unsold products; SKU code is the business key with a product-id fallback for missing codes. The catalogue has no date dimension; product movement uses sales_lines across all channels."
@@ -28,11 +21,16 @@ semantic:
purposes:
code: "The product SKU code, with a product-id fallback when Odoo has no code."
product_id: "The Odoo product.product id used by order, invoice and stock-move relations."
+ product_tmpl_id: "The product template name."
+ volume: "Volume per unit, not a sales quantity or a stock total."
first_cost: "The product's first cost per unit, not a validated cost-of-goods-sold aggregate."
synonyms:
code: [sku, product code, item code]
product: [item, product name]
supplier: [vendor]
+ upc: [barcode, upc code]
+ product_tmpl_id: [template, product template]
+ volume: [unit volume, product volume]
label: "Odoo products"
entity: product.product
# The database this topic DESCRIBES — the same store key the nav opens (W33-T46).
@@ -170,12 +168,22 @@ fields:
label: "SKU"
type: text
kind: data
- means: "The SKU code — the product's real business key. `pid` is a stable CRC32 of it because the grid keys on an integer."
+ means: "The SKU code, the product's real business key. `pid` is a stable CRC32 of it because the grid keys on an integer."
- key: product_id
label: "Odoo ID"
type: int
kind: data
means: "The Odoo product.product id, the key every Odoo document joins on. Carried on the row rather than derived, because a product's pid is a CRC32 of its SKU and the id cannot be recovered from it."
+ - key: product_tmpl_id
+ label: "Template"
+ type: text
+ kind: data
+ means: "The product template name. Products sharing a SKU use the first product record."
+ - key: volume
+ label: "Volume"
+ type: int
+ kind: data
+ means: "Volume per unit. Products sharing a SKU use the first product record."
- key: product
label: "Product"
type: text
@@ -345,7 +353,7 @@ fields:
label: "Revenue LY"
type: currency
kind: data
- means: "Same period last year — seasonal wholesale compares like for like."
+ means: "Revenue for the same period last year. Seasonal wholesale compares like for like."
- key: yoy_pct
label: "YoY %"
type: pct
@@ -365,17 +373,32 @@ fields:
label: "On hand"
type: int
kind: data
- means: "Units in stock. CONSOLIDATED — one physical warehouse, not brand-tagged, so this column is ABSENT for a BU-scoped caller rather than silently company-wide."
+ means: "Units in stock. Company-wide: one physical warehouse, not brand-tagged, so every caller sees the same figure, business-unit scoped or not."
+ - key: available
+ label: "Available"
+ type: int
+ kind: data
+ means: "Units in stock minus units reserved for orders: Odoo's free quantity on the product. Company-wide, the same figure for every caller."
+ - key: forecasted
+ label: "Forecasted"
+ type: int
+ kind: data
+ means: "Units in stock plus pending inbound minus pending outbound: Odoo's forecasted quantity on the product. Company-wide, the same figure for every caller."
+ - key: fba
+ label: "FBA"
+ type: int
+ kind: data
+ means: "Units of this SKU held at the Amazon FBA warehouse, part of On hand. Company-wide, the same figure for every caller. 0 is a measured zero. Blank means the FBA stock read failed or the tenant has no FBA warehouse."
- key: unit_cost
label: "Unit cost"
type: currency
kind: data
- means: "Inventory unit cost. Consolidated; absent for a BU-scoped caller."
+ means: "Inventory unit cost. Company-wide, the same figure for every caller."
- key: inv_value
label: "Stock value"
type: currency
kind: data
- means: "On-hand value at cost. Consolidated; absent for a BU-scoped caller."
+ means: "On-hand value at cost. Company-wide, the same figure for every caller."
- key: inventory_value_per_quantity
label: "Inventory value / quantity"
type: currency
@@ -390,7 +413,12 @@ fields:
label: "Units LTM"
type: int
kind: data
- means: "Units sold in the last twelve months. Consolidated; absent for a BU-scoped caller."
+ means: "Units sold in the last twelve months. A business unit view counts that unit's sales only."
+ - key: incoming
+ label: "Inbound units"
+ type: int
+ kind: data
+ means: "Units on pending inbound moves into the warehouse, from Odoo's incoming quantity on the product. Company-wide, the same figure for every caller. 0 means nothing is inbound."
- key: dos
label: "Days of supply"
type: int
@@ -401,18 +429,99 @@ fields:
type: int
kind: data
means: "Days of cover at the forward 8-month forecast rate minus supplier lead time. Negative means stock runs out before a reorder arrives. Counts on-hand and inbound units, excluding Amazon FBA warehouse stock. Blank if FBA stock cannot be read."
+ - key: cover_gap_units
+ label: "Cover gap (units)"
+ type: int
+ kind: data
+ means: "Units to buy. Forecast demand over the supplier lead time, at the forward 8-month rate, minus on-hand stock excluding Amazon FBA and minus inbound units. Positive is a shortfall to buy, negative is a surplus. Blank with no forecast demand, no lead time, or no readable stock."
+ - key: demand_fwd
+ label: "Forecast units (8 mo)"
+ type: int
+ kind: data
+ means: "Forecast units this SKU sells over the next 8 months, read from the units it sold in the same 8 calendar months one year ago, with a fallback for newer SKUs. A business unit view uses that unit's sales. Blank when the forecast is zero."
- key: stock_bucket
label: "Stock status"
type: select
kind: data
means: "Stock status from trailing-rate days of supply, including inbound units and excluding Amazon FBA warehouse stock. Coverage is blank if FBA stock cannot be read. 'Out of stock' uses on-hand stock excluding FBA, before inbound. 'No stock record' means no inventory row was returned. Business unit views use that unit's sales rate."
+ - key: discontinued
+ label: "Discontinued"
+ type: select
+ kind: data
+ means: "Yes when the product carries Odoo's Discontinued tag, otherwise No. Never blank."
- key: created_on
label: "Record created"
type: date
kind: data
means: "The date this product record was created in Odoo. The same uniform records-created column the customer topic carries."
+ - key: march_pricelist
+ label: "March pricelist"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's March pricelist marker. Blank means nobody set it."
+ - key: price_changes
+ label: "Price changes"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: a marker for a price change on this product. Blank means nobody set it."
+ - key: notes
+ label: "Notes"
+ type: text
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: free-text notes about this product. Blank means nobody set it."
+ - key: sub_category
+ label: "Sub-Category"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's sub-category in the merchandising hierarchy, below Main Category. It is not Odoo's Category. Blank means nobody set it."
+ - key: main_category
+ label: "Main Category"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's main category in the merchandising hierarchy. It is not Odoo's Category. Blank means nobody set it."
+ - key: color
+ label: "Color"
+ type: multiselect
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's colors. A product can carry more than one. Blank means nobody set it."
+ - key: shape_style
+ label: "Shape/Style"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's shape or style. Blank means nobody set it."
+ - key: material
+ label: "Material"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the material the product is made of. Blank means nobody set it."
+ - key: finish
+ label: "Finish"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's surface finish. Blank means nobody set it."
+ - key: occassion
+ label: "Occassion"
+ type: multiselect
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the occasions the product suits, such as a holiday. A product can carry more than one. Blank means nobody set it."
+ - key: collection
+ label: "Collection"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product collection this SKU belongs to. Blank means nobody set it."
+ - key: size
+ label: "Size"
+ type: select
+ kind: data
+ means: "A user-entered column, typed in the grid and not read from Odoo: the product's size. Blank means nobody set it."
+ - key: upc
+ label: "UPC"
+ type: text
+ kind: data
+ means: "The product barcode (UPC) as Odoo stores it. Blank when Odoo has no barcode for this product."
ai_context: >
The product CATALOGUE — the database labelled 'Odoo products'.
Use it for 'what do we sell', 'what does it cost' (first_cost/unit_cost), 'who supplies it', 'what is on hand' and the stock-coverage columns.
+ Use it for 'what is the UPC or barcode' (upc), 'what is inbound' (incoming), 'what is at Amazon FBA' (fba) and 'is it discontinued' (discontinued).
⛔ Revenue and unit columns here are WINDOWED SNAPSHOTS (rev_ytd, qty_ltm); for any other window, or for line grain, go to sales_lines.
diff --git a/platform/modules/customer_data.py b/platform/modules/customer_data.py
index eb768ddfce7ccb86d1322630aa8d618e8d346437..38d0de06db01b1bf48af0d98158dd61fadd68e77 100644
--- a/platform/modules/customer_data.py
+++ b/platform/modules/customer_data.py
@@ -279,6 +279,35 @@ def _salesperson_attrs(pids=None, t=None):
return {pid: v[0] for pid, v in per.items()}
+def pool_has_audit(rows):
+ """A pre-audit snapshot cannot answer the newly declared Customer fields."""
+ required = set(cust.AUDIT_ATTRS)
+ return all(required <= set(row) for row in rows)
+
+
+def validate_audit_attrs(rows, client):
+ """Numeric attributes and booleans against independent, scoped Odoo aggregates."""
+ live = [r for r in rows if not r.get('_ledger_revived')]
+ pids = [int(r['pid']) for r in live]
+ domain = [('id', 'in', pids), ('active', 'in', [True, False])]
+ checks = []
+ for key, (field, kind) in cust.AUDIT_ATTRS.items():
+ if kind not in ('int', 'bool'):
+ continue
+ complete = all(r.get(key) is not None for r in live)
+ if kind == 'int':
+ groups = client.read_group('res.partner', domain, [field + ':sum'],
+ ['create_uid'], lazy=False) if pids else []
+ theirs = sum(g.get(field) or 0 for g in groups)
+ ours = sum(r.get(key) or 0 for r in live)
+ else:
+ theirs = client.search_count('res.partner', domain + [(field, '=', True)]) if pids else 0
+ ours = sum(r.get(key) is True for r in live)
+ checks.append({'check': 'customer audit attribute ' + key, 'ours': ours,
+ 'theirs': theirs, 'ok': complete and ours == theirs})
+ return checks
+
+
def pool(agent_name=None, team_id=None):
"""One row per customer across the scoped book: the union of YTD buyers, same-period-LY
buyers and anyone with an order in the 24-month cadence window — so lapsed/win-back
@@ -422,7 +451,7 @@ def validate(team_id=None):
'ours': sum(ws.values()), 'theirs': 0, 'ok': not ws,
'detail': {'per_field': ws, 'fields_checked': text_keys},
})
- return checks
+ return checks + validate_audit_attrs(rows, odoo)
def _dba_attrs(pids, t):
@@ -642,6 +671,7 @@ def _pool_build(agent_name, team_id, limit, fast=False):
'Growing' if rev > 0 else 'Dormant')
a = attrs.get(pid) or {}
rows.append({
+ **{key: a.get(key, default) for key, default in cust.audit_attr_defaults().items()},
'pid': pid,
'customer': tv.get('name') or lv.get('name')
or (ltm.get(pid) or {}).get('name') or extra_names.get(pid) or '?',
@@ -770,6 +800,7 @@ def _reconcile_ledger(rows, total, agent_name, team_id):
if pid in live:
continue
revived.append({
+ **cust.audit_attr_defaults(),
'pid': pid, 'customer': e.get('name') or '?', 'status': 'Dormant',
'odoo_status': 'Archived',
'archived': True, '_ledger_revived': True,
diff --git a/platform/modules/customers.py b/platform/modules/customers.py
index 95369bcd366b36555795ad6cb47b0a7f427902b2..200fff73cc5cec991e11408067fbf313d9ed1dfb 100644
--- a/platform/modules/customers.py
+++ b/platform/modules/customers.py
@@ -567,6 +567,57 @@ DIMENSIONS = {
}
+# Audited res.partner attributes. Keep source notes and the Odoo DBA distinct from the
+# authored notes and sales-derived brand columns already present on Customer rows.
+AUDIT_ATTRS = {
+ 'source_notes': ('comment', 'html'),
+ 'company_name': ('commercial_company_name', 'text'),
+ 'commercial_partner': ('commercial_partner_id', 'name'),
+ 'customer_rank': ('customer_rank', 'int'),
+ 'doing_business_as': ('dba_id', 'name'),
+ 'invoice_age_limit': ('enable_max_invoice_age', 'bool'),
+ 'reminders': ('followup_reminder_type', 'text'),
+ 'is_company': ('is_company', 'bool'),
+ 'max_invoice_age': ('max_invoice_age', 'int'),
+ 'online_payment': ('online_payment', 'bool'),
+ 'parent_company': ('parent_id', 'name'),
+ 'sales_warning': ('sale_warn', 'text'),
+ 'supplier_rank': ('supplier_rank', 'int'),
+ 'sales_team': ('team_id', 'name'),
+ 'address_type': ('type', 'text'),
+ 'timezone': ('tz', 'text'),
+ 'hubspot_company_id': ('x_hubspot_company_id', 'text'),
+}
+
+
+def audit_attr_defaults():
+ """Unknown source values for a missing partner; never assert false or zero for it."""
+ return {key: None if kind in ('bool', 'int') else '(none)'
+ for key, (_field, kind) in AUDIT_ATTRS.items()}
+
+
+def _audit_attrs(record):
+ import html
+ import re
+ out = audit_attr_defaults()
+ for key, (field, kind) in AUDIT_ATTRS.items():
+ if field not in record or record[field] is None:
+ continue
+ value = record[field]
+ if kind == 'bool':
+ out[key] = bool(value)
+ elif kind == 'int':
+ out[key] = int(value or 0)
+ elif kind == 'name':
+ out[key] = O.m2o_name(value) or '(none)'
+ else:
+ text = str(value or '').strip()
+ if kind == 'html':
+ text = ' '.join(html.unescape(re.sub(r'<[^>]*>', ' ', text)).split())
+ out[key] = text or '(none)'
+ return out
+
+
def _partner_attrs(pids):
"""{pid: {street, street2, city, state, country, agent, zip, payment_terms, customer_since,
tags, pricelist}} — the customer attributes the sum-level rollups slice by and the Customer
@@ -591,7 +642,8 @@ def _partner_attrs(pids):
('active', 'in', [True, False])],
['street', 'street2', 'city', 'state_id', 'country_id', 'agent_ids',
'zip', 'property_payment_term_id', 'create_date', 'category_id',
- 'property_product_pricelist', 'active'])
+ 'property_product_pricelist', 'active']
+ + [field for field, _kind in AUDIT_ATTRS.values()])
aids = {a for r in rows for a in (r.get('agent_ids') or [])}
anames = ({p['id']: p['name'] for p in O.search_read('res.partner', [('id', 'in', list(aids))], ['name'])}
if aids else {})
@@ -610,6 +662,7 @@ def _partner_attrs(pids):
# compares dates ISO-LEXICALLY, so a trailing time would sort and filter as text noise.
since = (r.get('create_date') or '')
out[r['id']] = {
+ **_audit_attrs(r),
'archived': not bool(r.get('active', True)),
# ⭐ W30-T33 (carried W29-T51) — the STREET half of the address. `city`/`state`/`zip`/
# `country` were already here; the two street lines were read nowhere on the customer
diff --git a/platform/modules/finance_apps.py b/platform/modules/finance_apps.py
index 8d74a73311f5403474ebd822c32fb60c0cd10307..68708070c4f7db74f61f2441ef7c58d3c3b1f632 100644
--- a/platform/modules/finance_apps.py
+++ b/platform/modules/finance_apps.py
@@ -192,8 +192,8 @@ def finance_group():
return deepcopy(FINANCE_GROUP)
-# SDLC 64 / R6: also feeds GET /nav/applications through
-# application_registry.py::finance_application_records. platform/core/registry.py has no Finance
+# R102: feeds the Finance templates and the one-time per-user copy migration
+# (application_registry.py::ensure_user_app_copies). platform/core/registry.py has no Finance
# row, so may_open here is the ONLY grant between a session and a Finance application.
def finance_applications(may_open=None):
"""Return immutable descriptors, optionally filtered through the request permission wall."""
diff --git a/platform/modules/product_data.py b/platform/modules/product_data.py
index 90f621402de59bf157e9d250a5ce1d359e58422b..c4c2839f56336316e0f5e1e0b5c70f5c998f4c20 100644
--- a/platform/modules/product_data.py
+++ b/platform/modules/product_data.py
@@ -748,6 +748,8 @@ def pool(team_id=None, t=None, raw_fields=()):
# it and it has to be carried from `products.catalogue()`.
# ⚠ `None`, never 0, when the catalogue somehow has no id — 0 is a real Odoo id.
"product_id": meta.get("id"),
+ "product_tmpl_id": meta.get("product_tmpl_id") or "",
+ "volume": meta.get("volume"),
# ⭐⭐ W40-T08 (owner I24, "a records created date on all of our databases") — the
# record's birth date, in BOTH of the two shapes the grid reads, because they are two
# different things and only one of them is a column:
@@ -859,6 +861,11 @@ def pool(team_id=None, t=None, raw_fields=()):
row.update({
# UNSCOPED on purpose (owner 2026-08-11): one warehouse, no per-brand shelf.
"on_hand": e.get("on_hand"),
+ # S72-T40 (R104): Odoo's own per-record `free_qty` and `virtual_available`, summed per
+ # code by `products.catalogue()`. Unscoped like `on_hand`: set on every pull, never
+ # re-scoped. Blank, never zero, when the catalogue row carries no figure.
+ "available": meta.get("available"),
+ "forecasted": meta.get("forecasted"),
# ⭐⭐ W49-T24 — of those units, the ones sitting at Amazon. SAME BU BEHAVIOUR AS
# `on_hand` DELIBERATELY: set on every pull, warehouse wide, never re-scoped.
# ⚠ A REAL 0.0 IS AN OBSERVED ZERO, exactly like `pre_book_qty` above: the warehouse
@@ -1443,11 +1450,42 @@ def validate(team_id=None, t=None):
checks.extend(validate_price_and_unit_cells(rows))
checks.extend(validate_stock_measures(t=t))
checks.extend(validate_fba(rows))
+ checks.extend(validate_available_forecasted(rows))
+ checks.extend(validate_catalogue_audit_fields(rows))
checks.extend(validate_linked_metric(team_id=team_id))
checks.extend(validate_coverage(rows, t=t, team_id=team_id))
return checks
+def validate_catalogue_audit_fields(rows, sample=6):
+ """Compare template names and per-unit volumes to a fresh Odoo record sample."""
+ selected = [r for r in rows if r.get('product_id') is not None][:sample]
+ ids = [r['product_id'] for r in selected]
+ try:
+ records = O.get_odoo().search_read('product.product', [('id', 'in', ids)],
+ ['id', 'product_tmpl_id', 'volume']) if ids else []
+ oracle = {r['id']: r for r in records}
+ problems = {key: [] for key in ('product_tmpl_id', 'volume')}
+ for row in selected:
+ record = oracle.get(row['product_id'])
+ template = (record or {}).get('product_tmpl_id')
+ expected = {'product_tmpl_id': template[1] if isinstance(template, list)
+ and len(template) > 1 else '',
+ 'volume': (record or {}).get('volume')}
+ if isinstance(expected['volume'], bool):
+ expected['volume'] = None
+ for key in problems:
+ if record is None or row.get(key) != expected[key]:
+ problems[key].append(row['code'])
+ return [dict(check=f'{key} == independent Odoo record sample',
+ ours=len(selected) - len(wrong), theirs=len(selected),
+ ok=bool(selected) and not wrong, detail={'wrong_codes': wrong})
+ for key, wrong in problems.items()]
+ except Exception as exc:
+ return [dict(check=f'{key} == independent Odoo record sample', ok=False,
+ detail=type(exc).__name__) for key in ('product_tmpl_id', 'volume')]
+
+
def coverage_quant_oracle():
"""Read signed internal stock.quant totals outside and inside the independently resolved FBA subtree."""
try:
@@ -1637,6 +1675,96 @@ def validate_linked_metric(customer_id=None, product_id=None, team_id=None,
detail=f'Validation could not read both sources ({type(exc).__name__}). Check source readiness and rerun.')]
+#: Odoo 16's pending `stock.move` states, the ones `incoming_qty` and `outgoing_qty` count.
+PENDING_MOVE_STATES = ('waiting', 'confirmed', 'assigned', 'partially_available')
+
+#: Relative tolerance for the Available and Forecasted total legs. The pool and the oracle are
+#: separate reads up to a minute apart, so a stock move landing between them shifts both totals.
+#: MEASURED 2026-10-09 on tenant #0 with no move in between: a gap of 0.00 units on both legs.
+STOCK_POSITION_TOLERANCE = 0.001
+
+
+def stock_position_oracle():
+ """`{on_hand, reserved, incoming, outgoing}` unit totals over active products, from aggregates.
+
+ Independent of the columns: the columns are per-record computed fields on `product.product`,
+ while this totals `stock.quant` over internal locations and pending `stock.move.product_qty`
+ across the warehouse boundary (destination inside a warehouse and source outside it, or the
+ reverse). `product_qty` is in the product unit of measure, the same unit as the quants.
+ """
+ o = O.get_odoo()
+ active = [('product_id.active', '=', True)]
+ q = o.read_group('stock.quant', [('location_id.usage', '=', 'internal')] + active,
+ ['quantity:sum', 'reserved_quantity:sum'], [], lazy=False)
+ pending = [('state', 'in', list(PENDING_MOVE_STATES))]
+ inc = o.read_group('stock.move', pending + active
+ + [('location_dest_id.warehouse_id', '!=', False),
+ ('location_id.warehouse_id', '=', False)],
+ ['product_qty:sum'], [], lazy=False)
+ out = o.read_group('stock.move', pending + active
+ + [('location_id.warehouse_id', '!=', False),
+ ('location_dest_id.warehouse_id', '=', False)],
+ ['product_qty:sum'], [], lazy=False)
+
+ def total(groups, key):
+ return float(sum((g or {}).get(key) or 0.0 for g in (groups or [])))
+
+ return {'on_hand': total(q, 'quantity'), 'reserved': total(q, 'reserved_quantity'),
+ 'incoming': total(inc, 'product_qty'), 'outgoing': total(out, 'product_qty')}
+
+
+def validate_available_forecasted(rows, oracle=None):
+ """S72-T40: the Available and Forecasted columns against `stock_position_oracle()`.
+
+ Three legs: each column's total against its aggregate, and Available <= On hand per row.
+ An unreadable oracle is a failing leg that names the cause, never a skipped one.
+ """
+ if oracle is None:
+ try:
+ oracle = stock_position_oracle()
+ except Exception as e: # noqa: BLE001
+ return [{"check": "Available and Forecasted: the stock.quant and stock.move oracle "
+ "is readable",
+ "ours": None, "theirs": None, "ok": False,
+ "detail": {"source_refusal": type(e).__name__ + ": " + str(e)[:200]}}]
+
+ def num(v):
+ return isinstance(v, (int, float)) and not isinstance(v, bool)
+
+ def leg(name, key, theirs, formula):
+ vals = [float(r[key]) for r in rows if num(r.get(key))]
+ ours = sum(vals)
+ gap = abs(ours - theirs)
+ return {"check": name, "ours": round(ours, 2), "theirs": round(theirs, 2),
+ "ok": bool(vals) and gap <= max(0.01, STOCK_POSITION_TOLERANCE * abs(theirs)),
+ "detail": {"rows_with_a_value": len(vals), "rows_blank": len(rows) - len(vals),
+ "gap": round(gap, 2), "tolerance": STOCK_POSITION_TOLERANCE,
+ "oracle": formula}}
+
+ checks = [
+ leg("Available: Σ grid units == Σ stock.quant (quantity minus reserved_quantity) over "
+ "internal locations, active products", "available",
+ oracle["on_hand"] - oracle["reserved"],
+ "stock.quant read_group quantity:sum minus reserved_quantity:sum"),
+ leg("Forecasted: Σ grid units == internal stock.quant quantity plus pending incoming "
+ "minus pending outgoing stock.move product_qty", "forecasted",
+ oracle["on_hand"] + oracle["incoming"] - oracle["outgoing"],
+ "stock.quant quantity:sum + stock.move product_qty:sum in - out, states "
+ + ", ".join(PENDING_MOVE_STATES)),
+ ]
+ viol = [{"sku": r.get("code"), "on_hand": round(float(r["on_hand"]), 2),
+ "available": round(float(r["available"]), 2)}
+ for r in rows if num(r.get("on_hand")) and num(r.get("available"))
+ and float(r["available"]) > float(r["on_hand"]) + 0.01]
+ checks.append({
+ "check": "Available <= On hand on every row carrying both (reserved units are never "
+ "negative)",
+ "ours": len(viol), "theirs": 0, "ok": not viol,
+ "detail": {"violations": viol[:10], "n_violations": len(viol)},
+ })
+ return checks
+
+
def fba_quant_oracle():
"""`(warehouse | None, {product_id: units}, detail)` — the FBA column's INDEPENDENT oracle.
diff --git a/platform/modules/products.py b/platform/modules/products.py
index 46ffebc1567ad83c839c4744f94da99f935e8a6c..9e3fac51133a09ff167522273eb76b848d489967 100644
--- a/platform/modules/products.py
+++ b/platform/modules/products.py
@@ -302,7 +302,7 @@ def inventory_value_per_quantity(inv_value, quantity):
def catalogue():
"""`{sku_code: {'product', 'category', 'id', 'created_at', 'upc', 'discontinued',
- 'incoming'}}` — EVERY ACTIVE product, sold or not.
+ 'incoming', 'available', 'forecasted', 'product_tmpl_id', 'volume'}}` — EVERY ACTIVE product, sold or not.
⚠ `created_at` has been in the returned row since W40-T08 and was missing from this line;
W41-T26 adds `upc` and corrects the omission rather than compounding it. The keys listed
@@ -362,7 +362,8 @@ def catalogue():
# Odoo answers 3,877 real barcodes and carries NEITHER sentinel (measured: zero `-`, zero `0`).
prods = O.search_read('product.product', dom,
['id', 'default_code', 'display_name', 'name', 'create_date',
- 'product_tag_ids', 'incoming_qty', 'barcode'],
+ 'product_tag_ids', 'incoming_qty', 'barcode', 'free_qty',
+ 'virtual_available', 'product_tmpl_id', 'volume'],
limit=50000)
n = O.get_odoo().search_count('product.product', dom)
if len(prods) != n:
@@ -399,12 +400,23 @@ def catalogue():
row = out.setdefault(code, {'product': p.get('display_name') or p.get('name') or code,
'category': code_cat.get(code, '(uncategorized)'),
'id': p['id'], 'created_at': '', 'upc': '',
- 'discontinued': 'No', 'incoming': 0.0})
+ 'product_tmpl_id': O.m2o_name(p.get('product_tmpl_id')),
+ 'volume': (float(p['volume']) if isinstance(p.get('volume'),
+ (int, float)) and not isinstance(p['volume'], bool)
+ else None),
+ 'discontinued': 'No', 'incoming': 0.0,
+ 'available': 0.0, 'forecasted': 0.0})
# ⛔ ACROSS EVERY RECORD SHARING THE CODE, not just the first one that won above. A SKU
# whose variants are separate records carries its inbound on whichever record the PO named,
# and 'first record wins' would drop the rest — a buy list that under-counts what is
# already on the water tells you to re-order stock you have already bought.
row['incoming'] += float(p.get('incoming_qty') or 0.0)
+ # S72-T40 (R104): Available is Odoo's `free_qty` (on hand minus reserved) and Forecasted is
+ # `virtual_available` (on hand plus incoming minus outgoing). Both are unstored computed
+ # fields Odoo refuses to aggregate, so they ride this read and accumulate per code like
+ # `incoming`. `validate_available_forecasted` ties the totals to stock.quant and stock.move.
+ row['available'] += float(p.get('free_qty') or 0.0)
+ row['forecasted'] += float(p.get('virtual_available') or 0.0)
# ⭐ W40-T08 — the EARLIEST create_date across the records sharing this code, not the
# first record's. A row here is a SKU, and the honest answer to "when was this record
# created" for a merged SKU is when the earliest of its records appeared. Only `2112-12`
diff --git a/platform/static/fonts/FONT-LICENSE.txt b/platform/static/fonts/FONT-LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f3229e96426a75ec2cbc07a9af3f9be11a6b6cd5
--- /dev/null
+++ b/platform/static/fonts/FONT-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION AND CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+
diff --git a/platform/static/fonts/Inter-var.woff2 b/platform/static/fonts/Inter-var.woff2
new file mode 100644
index 0000000000000000000000000000000000000000..d15208de03cd1ad7c5199f0a0ce915fe841e4722
Binary files /dev/null and b/platform/static/fonts/Inter-var.woff2 differ
diff --git a/web/package-lock.json b/web/package-lock.json
index 27d8c2414764e7fe8de457e2e831f68d4f865c0f..5ce70eacdce18de5fa9d988738a65780c7c06adf 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -9,6 +9,7 @@
"version": "0.0.0",
"dependencies": {
"@glideapps/glide-data-grid": "^6.0.3",
+ "@phosphor-icons/react": "2.1.10",
"lodash": "^4.18.1",
"marked": "^4.3.0",
"overlayscrollbars": "^2.16.0",
@@ -888,6 +889,19 @@
"node": "^20.19.0 || >=22.12.0"
}
},
+ "node_modules/@phosphor-icons/react": {
+ "version": "2.1.10",
+ "resolved": "https://registry.npmjs.org/@phosphor-icons/react/-/react-2.1.10.tgz",
+ "integrity": "sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "peerDependencies": {
+ "react": ">= 16.8",
+ "react-dom": ">= 16.8"
+ }
+ },
"node_modules/@redocly/ajv": {
"version": "8.11.2",
"resolved": "https://registry.npmjs.org/@redocly/ajv/-/ajv-8.11.2.tgz",
diff --git a/web/package-lock.linux.sha256 b/web/package-lock.linux.sha256
index e83a682e3c7a4cd2e7f46f1e572715bba04580b7..daa34af70b65b397fc83a12fdcec3ae911ff70a3 100644
--- a/web/package-lock.linux.sha256
+++ b/web/package-lock.linux.sha256
@@ -1,2 +1,2 @@
-934b2e46585e97338bd4791d0cb388418d98eac2c0ff19c1b58d2236b3b7605a package-lock.json
-# resolved on linux/x64 by HF job 6ac5bea7404719ba37664c59 on 2026-10-07, npm ci passed there before upload. Regenerate ONLY with lockfile_linux.py (W-170).
+31cb494538043db42bdf698846c2262f5eb234fb686aa03d9cf3ab1cbfdbe2b8 package-lock.json
+# resolved on linux/x64 in the SDLC 72 lane A HF container on 2026-10-09 (S72-T05, npm install --save-exact @phosphor-icons/react@2.1.10); npm ci --ignore-scripts passed there (228 packages). Regenerate ONLY with lockfile_linux.py (W-170).
diff --git a/web/package.json b/web/package.json
index 31ca22558e1b8fd642823de550c4dab1d5b40ca6..899f0c9da672b6ff210e4762a6a020881243a048 100644
--- a/web/package.json
+++ b/web/package.json
@@ -18,6 +18,7 @@
},
"dependencies": {
"@glideapps/glide-data-grid": "^6.0.3",
+ "@phosphor-icons/react": "2.1.10",
"lodash": "^4.18.1",
"marked": "^4.3.0",
"overlayscrollbars": "^2.16.0",
diff --git a/web/public/AIOS_DEPLOY_RECEIPT b/web/public/AIOS_DEPLOY_RECEIPT
index c73199306ae19537b27c0d6a6cbfaf4537054786..56da2bf2c252f907b3310b9c2fd78922598cae7c 100644
--- a/web/public/AIOS_DEPLOY_RECEIPT
+++ b/web/public/AIOS_DEPLOY_RECEIPT
@@ -1 +1 @@
-29f563a5545e74e09cdc6d1036cd5cc53214a97f9cdd16ca6cd7a216683bacd4
+4aea7da93adedfb5b77e4f7ae1e110fad5217acf6ecb5b4210a0d16a0b610fc2
diff --git a/web/public/brand/SOURCES.md b/web/public/brand/SOURCES.md
index b124ce254afb44fba0df95e8c1b4acf41ff1e02f..90654b35e58d0124dd4e51cef83fb769d32528ee 100644
--- a/web/public/brand/SOURCES.md
+++ b/web/public/brand/SOURCES.md
@@ -47,6 +47,13 @@ hand-drawn set was built for.
| `stripe` | `stripe.png` | https://stripe.com/newsroom/brand-assets | `https://images.ctfassets.net/fzn2n1nzq965/HTTOloNPhisV9P4hlMPNA/…/Stripe_icon_-_square.svg` (400×400, rasterised at 1024) | trim + fit only |
| `shopify` | `shopify.png` | https://www.shopify.com/brand-assets | `shopify-shopping-bag.zip` → `02 - Glyph/png/shopify_glyph.png` (600×683) | trim + fit only |
| `amazon` | `amazon.svg` | the approved lowercase `a` and smile supplied for W58-T08 (owner instruction 19) | vector, no raster cut needed | none — shipped as the vendor SVG. **Its geometry is digest-pinned** in `src/connectors/_directory_render.cjs`, which asserts the served file and `brandMarks.tsx`'s inline fallback are the same artwork |
+| `whatsapp` | `whatsapp.svg` | https://www.meta.com/brand/resources/whatsapp/whatsapp-brand/ | Official `WhatsApp-Brand-Resource-Center.zip`, `01_Glyph/01_Digital RGB/03_SVG/Digital_Glyph_Green_RGB_2026.svg`, downloaded from the page's Meta-controlled fbcdn.net link on 2026-10-09 | unchanged vendor artwork; only a final newline added. Archive SVG SHA-256 `f7b1311db718533e671645f57cd94b92f0e006e61d7e6581a80675fc5a478fc4`; repository file `46d8d8acf2cf2bee7618db0924c6b53329cd70c919e763e7c77f0c12d03b53be` |
+
+## S72-T47 terms checked on 2026-10-09
+
+WhatsApp use follows the [official brand guidelines](https://www.meta.com/brand/resources/whatsapp/whatsapp-brand/): use the supplied assets, preserve their design and colours, scale proportionately, and avoid implying sponsorship. This mark identifies the WhatsApp connector and remains smaller than the product identity. Its failure fallback is a generic phone glyph, not an altered WhatsApp logo.
+
+The iMessage official mark is blocked. [Apple's third-party trademark guidelines](https://www.apple.com/legal/intellectual-property/guidelinesfor3rdparties.html), Unauthorized Use of Apple Trademarks, item 2, require an express written trademark license to use Apple-owned graphic symbols or icons on a website or product. No such license is recorded for Loopable. Per S72-T47, no imessage.svg is added and the card retains its existing generic mark. T47 requires the owner to resolve the license restriction before the official iMessage mark can ship.
## ⚠ The one judgement call, stated rather than buried — `odoo`
diff --git a/web/public/brand/whatsapp.svg b/web/public/brand/whatsapp.svg
new file mode 100644
index 0000000000000000000000000000000000000000..b63887ecc2f0f8c30cf71a89efb5cfbc16ed9470
--- /dev/null
+++ b/web/public/brand/whatsapp.svg
@@ -0,0 +1,12 @@
+
+
diff --git a/web/public/sample_customers.json b/web/public/sample_customers.json
index cbe9355f646ad6316c521e1a356960fed2ac5a5b..f69ae3f5d25487c883eff84fe7b825f9f9d12a60 100644
--- a/web/public/sample_customers.json
+++ b/web/public/sample_customers.json
@@ -325,6 +325,142 @@
"source": "overlay",
"default": false,
"description": "Your notes on this customer. Saved in this app only, visible only to you."
+ },
+ {
+ "key": "source_notes",
+ "label": "Source notes",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The customer notes recorded in Odoo."
+ },
+ {
+ "key": "company_name",
+ "label": "Company name",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The customer's commercial company name in Odoo."
+ },
+ {
+ "key": "commercial_partner",
+ "label": "Commercial entity",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The commercial account this customer belongs to."
+ },
+ {
+ "key": "customer_rank",
+ "label": "Customer rank",
+ "type": "int",
+ "source": "odoo",
+ "default": false,
+ "description": "The customer's rank recorded in Odoo."
+ },
+ {
+ "key": "doing_business_as",
+ "label": "Doing business as",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The doing business as name assigned in Odoo."
+ },
+ {
+ "key": "invoice_age_limit",
+ "label": "Invoice age limit on",
+ "type": "checkbox",
+ "source": "odoo",
+ "default": false,
+ "description": "Whether Odoo enforces the maximum invoice age."
+ },
+ {
+ "key": "reminders",
+ "label": "Reminders",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The customer's follow-up reminder setting in Odoo."
+ },
+ {
+ "key": "is_company",
+ "label": "Company",
+ "type": "checkbox",
+ "source": "odoo",
+ "default": false,
+ "description": "Whether Odoo identifies this customer as a company."
+ },
+ {
+ "key": "max_invoice_age",
+ "label": "Max invoice age",
+ "type": "int",
+ "source": "odoo",
+ "default": false,
+ "description": "The maximum invoice age in days configured in Odoo."
+ },
+ {
+ "key": "online_payment",
+ "label": "Online payment",
+ "type": "checkbox",
+ "source": "odoo",
+ "default": false,
+ "description": "Whether online payment is enabled for this customer."
+ },
+ {
+ "key": "parent_company",
+ "label": "Related company",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The customer's parent company in Odoo."
+ },
+ {
+ "key": "sales_warning",
+ "label": "Sales warning",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The sales warning setting recorded in Odoo."
+ },
+ {
+ "key": "supplier_rank",
+ "label": "Supplier rank",
+ "type": "int",
+ "source": "odoo",
+ "default": false,
+ "description": "The supplier rank recorded on this customer in Odoo."
+ },
+ {
+ "key": "sales_team",
+ "label": "Sales team",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The sales team assigned to this customer in Odoo."
+ },
+ {
+ "key": "address_type",
+ "label": "Address type",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The contact address type recorded in Odoo."
+ },
+ {
+ "key": "timezone",
+ "label": "Timezone",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The customer's timezone recorded in Odoo."
+ },
+ {
+ "key": "hubspot_company_id",
+ "label": "HubSpot company ID",
+ "type": "text",
+ "source": "odoo",
+ "default": false,
+ "description": "The HubSpot company identifier linked in Odoo."
}
],
"rows": [
diff --git a/web/src/account/account.css b/web/src/account/account.css
index 7197fd573ebe5d0349b4c16314368a24670451a1..d70ca7bdfd5cbdaed11403e34680ba0b40a0e4ff 100644
--- a/web/src/account/account.css
+++ b/web/src/account/account.css
@@ -32,7 +32,7 @@
.acct-title {
margin: 0 0 20px;
font-size: var(--lp-fs-lg);
- font-weight: 650;
+ font-weight: var(--lp-fw-semibold);
color: var(--lp-ink);
}
diff --git a/web/src/app/FinanceWorkspace.tsx b/web/src/app/FinanceWorkspace.tsx
index 1243649b4aef26e532b26f888cdfcaabe1378de6..c3ea2488dab8669e3d6bba91b03f3c17f0e144c4 100644
--- a/web/src/app/FinanceWorkspace.tsx
+++ b/web/src/app/FinanceWorkspace.tsx
@@ -1,6 +1,7 @@
-import { useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEscapeClose } from "../ui/useEscapeClose";
import "./finance.css";
+import "../styles/sdlc72/app-fullscreen.css";
type FactState = "ready" | "warming" | "missing" | "unavailable" | "restricted" | "requires_sku";
@@ -196,6 +197,62 @@ type PageState =
const CREDENTIALS: RequestCredentials = "include";
+/** S72-T62 (R108 k): the class on `` that hides the shell rail and top bar. It matches
+ * `CustomerGrid.tsx::APP_FULLSCREEN_CLASS`, so grid and Finance Apps share one rule. */
+const APP_FULLSCREEN_CLASS = "is-app-fullscreen";
+/** The App root wears this while full screen. The root class leaves when no root wears it. */
+const APP_FULLSCREEN_MARK = "data-app-fullscreen";
+const APP_FULLSCREEN_TABBABLE = "button:not([disabled]),input:not([disabled]),"
+ + "select:not([disabled]),textarea:not([disabled]),[href],[tabindex]:not([tabindex=\"-1\"])";
+
+/**
+ * Full screen for one App root. Component state only, so a reload never restores it. Escape
+ * leaves through the shared arbiter, and Tab wraps inside the root while the chrome is hidden.
+ */
+function useAppFullscreen(rootRef: { current: HTMLElement | null }) {
+ const [fullscreen, setFullscreen] = useState(false);
+ const toggleFullscreen = useCallback(() => setFullscreen(on => !on), []);
+ const exitFullscreen = useCallback(() => setFullscreen(false), []);
+ const fullscreenContainer = useCallback(() => rootRef.current, [rootRef]);
+ useEscapeClose(fullscreen, exitFullscreen, {
+ cancelEditFirst: true, container: fullscreenContainer });
+ useEffect(() => {
+ if (!fullscreen) return;
+ const html = document.documentElement;
+ html.classList.add(APP_FULLSCREEN_CLASS);
+ const onTab = (event: KeyboardEvent) => {
+ const root = rootRef.current;
+ if (event.key !== "Tab" || !root) return;
+ const active = document.activeElement;
+ const outside = !active || active === document.body || active === html;
+ if (!outside && !root.contains(active)) return;
+ const stops = Array.from(root.querySelectorAll(APP_FULLSCREEN_TABBABLE))
+ .filter(element => element.getClientRects().length > 0);
+ if (!stops.length) return;
+ const first = stops[0];
+ const last = stops[stops.length - 1];
+ if (outside) {
+ event.preventDefault();
+ (event.shiftKey ? last : first).focus();
+ } else if (event.shiftKey && active === first) {
+ event.preventDefault();
+ last.focus();
+ } else if (!event.shiftKey && active === last) {
+ event.preventDefault();
+ first.focus();
+ }
+ };
+ document.addEventListener("keydown", onTab, true);
+ return () => {
+ document.removeEventListener("keydown", onTab, true);
+ // Runs after React removed this root's mark, on exit and on unmount alike.
+ if (!document.querySelector(`[${APP_FULLSCREEN_MARK}]`))
+ html.classList.remove(APP_FULLSCREEN_CLASS);
+ };
+ }, [fullscreen, rootRef]);
+ return { fullscreen, toggleFullscreen };
+}
+
function pathApplicationKey() {
if (typeof window === "undefined") return "";
const match = `${window.location.pathname}${window.location.hash}`.match(/\/finance\/([^/?#]+)/);
@@ -755,6 +812,9 @@ function FinanceApplication({
const [drillError, setDrillError] = useState("");
const [worklist, setWorklist] = useState({ kind: "idle" });
const [workItem, setWorkItem] = useState(null);
+ const workspaceRef = useRef(null);
+ const { fullscreen, toggleFullscreen } = useAppFullscreen(workspaceRef);
+ const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
useEffect(() => {
if (!resolvedKey) { setPage({ kind: "missing" }); return; }
@@ -900,10 +960,27 @@ function FinanceApplication({
? facts.find(fact => fact.key === application.worklist?.sourceFact)
: undefined;
return (
-
+
@@ -258,9 +360,7 @@ export default function ArtifactsPage({ granted }: { granted: NavEntry[] }) {
+ {/* An empty list shows the logo loader centred over the panel, where Shell's navLoader sits. role="img": nothing is loading. */}
+ {/* Only over an empty detail pane: a saved query, a refused deep link or a load error renders there. */}
+ {loaded && !items.length && !queryId && !selection.item && !problem ?
: }
;
}
@@ -237,85 +321,132 @@ async function draftRequest(database: string, fields?: string[], question?: stri
return response.json();
}
-/**
- * R47 / R6 — the answer names its own source, and the override lives here rather than in front of
- * the question. One line: "Answered from · Change".
- *
- * ⛔ CHANGE IS A SELECT, NOT A ROW OF BUTTONS, AND THAT WAS MEASURED ON A RUNNING TENANT. This
- * first shipped as one quiet button per alternative; tenant #0 can read 28 databases, so opening
- * Change pushed the answer six rows down the screen behind a wall of names, eleven of which read
- * "Formula contract". A select collapses the whole override into the one word the ruling names,
- * hands the browser the scrolling, the keyboard and the screen reader, and is the same control
- * the model picker one line below already is. Its value is held at "" so the word Change survives
- * every switch, and `onChange` ignores that empty value.
- *
- * ⚠ A refusal renders the control ALONE: the refusal sentence under it already names the database
- * it could not answer from, so "Answered from" would be the one thing on the surface that is not
- * true. The override still has to be reachable there, which is the state that needs it most.
- */
-function RoutingLine({ disclosure, onSwitch, busy }: {
- disclosure?: RoutingDisclosure | null; onSwitch?: (database: string) => void; busy?: boolean;
-}) {
- if (!disclosure?.database || !disclosure.alternatives.length) return null;
- return
- {disclosure.answered ? <>
- Answered from {disclosure.label}
- {onSwitch ? · : null}
- > : null}
- {onSwitch ? (
-
- ) : null}
- ;
-}
-
-
// R13 (moved from S68-T45): Time-series is retired, so it has no label here.
const KIND_LABEL: Record = {
grid: "table", list: "list", chart: "chart", kanban: "board", calendar: "calendar", map: "map",
};
-/**
- * ⭐⭐ THE MODEL NAMES THE OWNER PICKS FROM (owner item 2, 2026-08-15). Verbatim: *"the user can
- * choose which model to use since we have a selections of them."*
- *
- * ⛔ THE WIRE VALUE IS THE PROVIDER KEY AND MUST STAY THE PROVIDER KEY. `routes_query.model_choices`
- * derives the list from `QUERY_PROVIDER_ORDER`, and `_call_model` looks the choice up in
- * `harness.analyst.PROVIDERS` by that exact name. This map is a DISPLAY name only, applied to
- * whatever the server sent — an unknown key falls through to itself rather than being hidden, so a
- * provider added server-side appears here the day it is added instead of the day someone
- * remembers to edit this file [[a-flag-can-ship-without-its-writer]].
- *
- * ⛔ `anthropic: "Claude"` AND `openai: "OpenAI"` ARE GONE, and the reason is worth keeping because
- * the ticket that removed them described the defect backwards. They were never OFFERED: the picker
- * renders `index.models`, which is `model_choices()` = `[auto, *QUERY_PROVIDER_ORDER]`, so no
- * reader ever saw "Claude" in this control. They were labels for providers that do not exist in
- * the platform ladder, i.e. dead weight, and the fall-through above already covers a provider
- * added server-side. The REAL defect the ticket named lives one layer down and is fixed by
- * `modelStatus`: a model that IS offered and whose key this deployment does not hold.
- */
-const MODEL_LABEL: Record = {
- // ⭐ `anthropic` JOINS THE MAP (W36 · ASK E-11, ruling R4). Not a fifth option nobody wanted.
- // E measured all three side rungs refusing live today (cerebras 402, groq 404, openrouter 402),
- // so Anthropic is the only rung that answers at all, and C5 makes it the tool-calling path by
- // ruling rather than by accident. The fall-through below still covers a provider added
- // server-side; this row exists so the ONE rung that works is not the one rendered as a raw key.
- // ⚠ NO `word` FOLLOWED BY A COLON IN THIS COMMENT, and that is not fussiness. `verify_query`
- // reads this map with a regex over the block, comments included, so a phrase like "asked for"
- // with a colon after it registered as a SIXTH key named `for` and reddened the check that
- // exists to keep this map equal to the server's list [[prose-that-becomes-its-own-marker]].
- auto: "Auto", anthropic: "Anthropic", cerebras: "Cerebras", groq: "Groq",
- openrouter: "OpenRouter",
-};
-const modelLabel = (key: string) => MODEL_LABEL[key] ?? key;
+/** S72-T16 (C7, R98): the made-file kinds an answer shows as a chip. Any other kind keeps today's answer. */
+export const ARTIFACT_KIND_LABEL: Record = { xlsx: "Excel file", image: "Image", snapshot: "Snapshot" };
+// The pop-up also names a PDF, because its record carries a file the same way.
+const ITEM_KIND_LABEL: Record = { ...ARTIFACT_KIND_LABEL, pdf: "PDF file" };
+
+export type ArtifactRecord = { id: string; kind: string; title: string; fileId?: string; mime?: string };
+
+/** A C7 record, or a stored record of today's shape. Null when it has no id or kind. */
+export function readArtifactRecord(value: unknown): ArtifactRecord | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const row = value as Record;
+ const text = (key: string) => typeof row[key] === "string" ? (row[key] as string).trim() : "";
+ const id = text("id");
+ const kind = text("kind");
+ if (!id || !kind) return null;
+ // C7 names `file_id`. Today's PDF record keeps its file id in `ref`.
+ const fileId = text("file_id") || text("fileId") || text("ref");
+ const mime = text("mime");
+ return { id, kind, title: text("title") || ITEM_KIND_LABEL[kind] || "Artifact",
+ ...(fileId ? { fileId } : {}), ...(mime ? { mime } : {}) };
+}
+
+/** C7: the in-app link of one artifact record. */
+export function artifactItemHash(id: string): string {
+ return `#/artifacts?item=${encodeURIComponent(id)}`;
+}
+
+export type ArtifactReader = () => Promise>;
+const readArtifactIndex: ArtifactReader = () => fetchArtifacts();
+
+// One shared `/artifacts` read per page session. A failed read clears it, so the next use retries.
+let artifactRead: Promise