diff --git a/RELEASES.json b/RELEASES.json
index 3bc2d22dd955f572303b78724cf8e0b321a88cda..37197088ea8f7e64e3f177d97cdd2222d2be0d09 100644
--- a/RELEASES.json
+++ b/RELEASES.json
@@ -1,4 +1,4 @@
{
- "current": "717502eb7",
+ "current": "859ae4071",
"releases": []
}
\ No newline at end of file
diff --git a/VERSION b/VERSION
index dcd7a23988312d915cfe43a8ed9e26239fddd8be..b5ab5bb684a50c51e23d630c72065687350b0e40 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-717502eb7
+859ae4071
diff --git a/api/app_guide.py b/api/app_guide.py
index d03bab7ad15cdbe229efb7259effd477f2e2f6d7..be0164331a303f20f08a4bc2c0fca24152105973 100644
--- a/api/app_guide.py
+++ b/api/app_guide.py
@@ -225,16 +225,19 @@ def _chart_guidance():
def _catalog_guidance():
"""Append the same template library as the client and the current build argument schema."""
+ from core import external_tools
from loopy_catalog_tools import build_schema
library = json.dumps(app_rules.catalog_templates(), ensure_ascii=True, indent=2)
- schema = json.dumps(build_schema(), ensure_ascii=True, indent=2)
+ collapsed, used = external_tools.guide_schema(build_schema())
+ schema = json.dumps(collapsed, ensure_ascii=True, indent=2)
+ nodes = "\n" + external_tools.filter_node_guide() + "\n" if used else ""
return ("\n# Current Catalog template library\n\n"
"These IDs, slots and design defaults also come from GET /api/v1/catalogs/templates.\n"
f"```json\n{library}\n```\n"
"\n# Current catalog_build argument schema\n\n"
"This schema describes arguments only. Put about and intent beside action and arguments.\n"
- f"```json\n{schema}\n```\n")
+ f"```json\n{schema}\n```\n{nodes}")
def read(section=None):
diff --git a/api/automation_engine.py b/api/automation_engine.py
index d4651aebe8fdcb8be6397f7dbee0d361b3e9b855..d639b6bcff8550c2dadd8dbe1ba865947d373c7e 100644
--- a/api/automation_engine.py
+++ b/api/automation_engine.py
@@ -2518,8 +2518,6 @@ def clean_definition(raw, previous=None, username="", notes=None, rt=None):
# a set the vendor is already building (and already counting against the funds gate).
"state": dict(prev.get("state") or {}),
"created": prev.get("created") or _authored_iso(),
- # S76-T37: carried here, stamped only by `create` and `patch` (a re-clean is not an update).
- "updatedAt": prev.get("updatedAt") or prev.get("created") or "",
"createdBy": prev.get("createdBy") or username,
# ⭐⭐ WAVE 35 · T37 — `system` IS STICKY ACROSS A PATCH, AND IT IS **NEVER READ FROM `raw`**.
#
@@ -3441,7 +3439,6 @@ def create(rt, raw, username="", notes=None):
f"{RETIRED_KIND_REPLACEMENT.get(defn['kind'], '')}")
# Retired run histories reserve their ids so a new definition cannot overwrite them.
defn["id"] = _new_id(rt.get(STORE_KEY) or {})
- defn["updatedAt"] = defn.get("created") or _authored_iso()
def _up(cur):
cur = cur if isinstance(cur, dict) else {}
@@ -3483,7 +3480,6 @@ def patch(rt, auto_id, raw, username="", notes=None):
if err:
return None, err
defn["id"] = str(auto_id)
- defn["updatedAt"] = _authored_iso()
def _up(cur):
cur = cur if isinstance(cur, dict) else {}
diff --git a/api/external_freshness.py b/api/external_freshness.py
index 1b525b873777b92df91a3a997867890b98d66f47..fe47226f83d5ca98f8417d166fc4f32de8fd5d5e 100644
--- a/api/external_freshness.py
+++ b/api/external_freshness.py
@@ -59,40 +59,6 @@ def _sync_date(value):
return None
-def amazon_sync_stamp(cur, table_key):
- """Read a table's last successful source pass before its legacy raw-table receipt."""
- import amazon_relational
-
- raw = amazon_relational.SOURCE.get(table_key)
- if not raw or cur is None:
- return None
- marker = "amzn_sync_mark_" + raw.removeprefix("amzn_")
- for entity in (marker, raw):
- row = cur.execute("SELECT updated_at FROM _sync_state WHERE entity = ? AND phase = 'done'",
- [entity]).fetchone()
- if row:
- return row[0]
- return None
-
-
-def _amazon_refreshes(session, keys):
- """Read only sync metadata for the authorized Amazon databases on this tenant's cursor."""
- import assistant_mirror
-
- cur, refreshed = None, {}
- for key in keys:
- try:
- if cur is None:
- cur, refusal = assistant_mirror.open_cursor(session, key)
- if refusal is not None or cur is None:
- cur = None
- continue
- refreshed[key] = amazon_sync_stamp(cur, key)
- except Exception:
- continue
- return refreshed
-
-
def _mirror_refreshes(session, definitions, keys):
"""Read authorized mirror stamps with cached successful cursors and no product-row reads."""
import assistant_mirror
@@ -183,9 +149,7 @@ def snapshot(session, databases):
except Exception:
docs[name] = {}
odoo = odoo_relational.sync_freshness(user_tables.lend(rt, **docs))
- amazon_keys = {key for key in connected if key.startswith("ut_amzn_")}
- amazon = _amazon_refreshes(session, amazon_keys) if amazon_keys else {}
- mirror_keys = {key for key in connected - amazon_keys
+ mirror_keys = {key for key in connected
if not user_tables.materialises(key, st=lent, defn=definitions[key])}
mirror = _mirror_refreshes(session, definitions, mirror_keys) if mirror_keys else {}
facts = {}
@@ -204,7 +168,7 @@ def snapshot(session, databases):
successes.append(odoo.get("lastGoodSyncAt"))
if job.get("state") == "ready":
successes.append(job.get("at"))
- values = [amazon.get(key)] if key.startswith("ut_amzn_") else [mirror.get(key), *successes]
+ values = [mirror.get(key), *successes]
stamp = next((stamp for value in values if (stamp := utc_stamp(value)) is not None), None)
synced_on = next((day for value in values if (day := _sync_date(value)) is not None), None)
if stamp is not None:
@@ -239,11 +203,6 @@ def add(result, session, *, facts=None):
result.pop("source_synced_on", None)
result.pop("last_edited_at", None)
result.update(source_synced_at=None, source_sync="never_synced")
- if str(result.get("database") or "").startswith("ut_amzn_"):
- if facts is None:
- facts = snapshot(session, [result.get("database")])
- result.update(facts.get(result.get("database"), {}))
- return result
refreshed = _refresh_value(version) if kind == "mirror_user_table" else None
if kind == "mirror_user_table" and isinstance(version, dict):
stamp = utc_stamp(refreshed)
diff --git a/api/intelligence_store.py b/api/intelligence_store.py
index 320b56eee128b0e82c2eec4aa809a2ecb4099a82..13f177dcb17f3890156a43f86a72cd2e55474fb5 100644
--- a/api/intelligence_store.py
+++ b/api/intelligence_store.py
@@ -6,7 +6,6 @@ from functools import lru_cache
from pathlib import Path
import importlib
import difflib
-import hashlib
import json
import re
@@ -268,10 +267,10 @@ def _document(raw):
return raw
-def _files(session, *, include_generated=False, wiki_only=False, raw=None):
+def _files(session, *, include_generated=False, wiki_only=False):
"""Read authored files, adding reader-scoped system pages only for Wiki requests."""
try:
- raw = _document(session.runtime.get(STORE_KEY) if raw is None else raw)
+ raw = _document(session.runtime.get(STORE_KEY))
_check_file_capacity(session, raw)
import wiki_log
files = _project_templates(session, raw)
@@ -333,9 +332,9 @@ def _database_note_record(session, key, *, stored=None, with_body=False):
if not definition or not can_read(session, {"reads": [definition["key"]]}):
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
note = user_tables.shared_note("database", key, st=session.runtime)
- if not note or note.get("deleted"):
+ if not note:
raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
- meta = {"title": note.get("title") or definition["label"], "section": "database-notes", "owner": definition["owner"],
+ meta = {"title": definition["label"], "section": "database-notes", "owner": definition["owner"],
"description": f"Shared note for {definition['label']}.", "reads": [definition["key"]],
"approvers": [], "approvals_needed": 1, "tools": [], "databaseKey": key}
text = note.get("body") or ""
@@ -392,7 +391,7 @@ def _database_note_file(session, path, *, version=0):
"latestVersion": current["version"], "history": history, "versions": len(history), "limits": limits()}
-def _put_database_note(session, key, body, actor, base_version, base_updated, *, title=None, deleted=False):
+def _put_database_note(session, key, body, actor, base_version, base_updated):
"""Let the canonical writer enforce admission and its exact base on every atomic attempt."""
from core import user_tables
@@ -410,13 +409,7 @@ def _put_database_note(session, key, body, actor, base_version, base_updated, *,
prior = (_document(raw).get("database:" + key) or {})
if int(prior.get("version") or 0) != base_version or prior.get("updated") != base_updated:
raise IntelligenceError("version_conflict", "The note changed. Reload it before saving.", 409)
- updated = callback(raw)
- note = updated["database:" + key]
- if title is not None or prior.get("title"):
- note["title"] = title if title is not None else prior["title"]
- if deleted:
- note["deleted"] = True
- return updated
+ return callback(raw)
return session.runtime.update(bucket, checked, **kwargs)
@@ -701,8 +694,6 @@ def _row(record, entry=None, *, session=None):
**{key: deepcopy(entry[key]) for key in ("agent", "onBehalfOf", "approvedBy", "proposalId", "restoredFrom") if key in entry},
"created": record["created"], "lastUsed": record.get("lastUsed"),
**{key: record[key] for key in ("databaseKey", "canEdit", "revisionHistory") if key in record},
- "canEdit": bool(session and (record.get("canEdit") if "databaseKey" in record
- else can_edit(session, _head(record)["metadata"]))),
"versions": sum(session is None or can_read(session, version["metadata"])
for version in record["versions"]), "trimmed": record.get("trimmed", 0),
**({"fieldCheck": _field_check(session, meta)} if session and meta.get("required_fields") else {})}
@@ -737,13 +728,7 @@ def list_files(session, *, section="", query="", folder="", offset=0, limit=100,
needle = str(query or "").strip().casefold()
rows = []
wiki_requested = selected == "wiki" or prefix.casefold().startswith("wiki/")
- try:
- raw = _document(session.runtime.get(STORE_KEY))
- except IntelligenceError:
- raise
- except Exception:
- raise IntelligenceError("store_unavailable", "Brain files could not be read. Try again.", 503) from None
- for path, record in sorted(_files(session, include_generated=wiki_requested, raw=raw).items()):
+ for path, record in sorted(_files(session, include_generated=wiki_requested).items()):
if not _head(record):
continue
meta = _head(record)["metadata"]
@@ -760,78 +745,7 @@ def list_files(session, *, section="", query="", folder="", offset=0, limit=100,
if direct:
rows = [row for row in rows if "/" not in row["path"][len(prefix):]]
return {"files": rows[offset:offset + limit], "total": len(rows), "offset": offset,
- "limit": limit, "sections": sections(), "folders": folders, "limits": limits(),
- "canManageFolders": bool(getattr(session, "admin", False) and not trusted_identity(session)[1].get("agent")),
- **({"folderRevision": _folder_revision(raw)} if getattr(session, "admin", False) else {})}
-
-
-def _folder_revision(raw):
- """Bind folder changes to the exact file identities and versions in their atomic update."""
- heads = [(path, record.get("created"), (_head(record) or {}).get("version", 0))
- for path, record in sorted(_document(raw).items())]
- return int(hashlib.sha256(json.dumps(heads, sort_keys=True).encode()).hexdigest()[:13], 16)
-
-
-def change_folder(caller, path, *, name=None, expected_revision):
- """Rename a folder or promote its children in one revision-checked update."""
- session, identity = trusted_identity(caller)
- _authorize(session)
- if not session.admin or identity.get("agent"):
- raise IntelligenceError("folder_admin_required", "Only an Administrator can change Brain folders.", 403)
- if type(expected_revision) is not int or expected_revision < 0:
- raise IntelligenceError("bad_revision", "Reload the folders before trying again.")
- path = normalize_path(path, folder=True)
- def reserved(folder):
- folded = folder.casefold()
- return (folded in ("database-notes", "wiki") or folded.startswith(DATABASE_NOTES_PREFIX)
- or any(folded == root or folded.startswith(root + "/")
- for root in ("wiki/log", "wiki/index", "wiki/purposes")))
-
- if reserved(path):
- raise IntelligenceError("folder_reserved", "This folder is maintained by the workspace.", 403)
- parent = path.rpartition("/")[0]
- target = parent
- if name is not None:
- name = normalize_path(name, folder=True)
- if "/" in name:
- raise IntelligenceError("bad_name", "Use one folder name without slashes.")
- target = normalize_path((parent + "/" if parent else "") + name, folder=True)
- if reserved(target):
- raise IntelligenceError("folder_reserved", "This folder name is reserved.", 403)
-
- def move(raw):
- files = dict(_document(raw))
- if _folder_revision(files) != expected_revision:
- raise IntelligenceError("folder_revision_stale", "Folders changed. Reload before trying again.", 409)
- prefix = path + "/"
- projected = _project_templates(session, files)
- if any(key.startswith(prefix) and key in _template_catalog() and _head(record)
- for key, record in projected.items()):
- raise IntelligenceError("folder_reserved", "This folder contains a maintained file.", 403)
- moving = {key: record for key, record in files.items() if key.startswith(prefix)}
- if not moving or not any(_head(record) for record in moving.values()):
- raise IntelligenceError("no_folder", "This folder is no longer available.", 404)
- if name is not None and target != path and any(key.startswith(target + "/") for key in projected):
- raise IntelligenceError("folder_exists", "A folder with that name already exists.", 409)
- destinations = {key: normalize_path((target + "/" if target else "") + key[len(prefix):]) for key in moving}
- if any((destination in files and destination not in moving) or destination in _template_catalog()
- for destination in destinations.values()):
- raise IntelligenceError("file_exists", "A child has the same path as an existing file. Rename it first.", 409)
- for key, record in moving.items():
- _assert_authored_path(key)
- if key in _template_catalog() or (_head(record) or {}).get("metadata", {}).get("generated"):
- raise IntelligenceError("folder_reserved", "This folder contains a maintained file.", 403)
- del files[key]
- for key, record in moving.items():
- destination = destinations[key]
- _assert_authored_path(destination)
- files[destination] = {**record, "path": destination,
- "proposals": {pid: {**proposal, "path": destination}
- for pid, proposal in (record.get("proposals") or {}).items()}}
- return files
-
- _update(session, move)
- return {"path": target} if name is not None else {"deleted": path}
+ "limit": limit, "sections": sections(), "folders": folders, "limits": limits()}
def _summaries(session):
@@ -1945,76 +1859,15 @@ def decide_proposal(session, proposal_id, decision):
return saved
-def rename_file(caller, path, title, *, expected_version):
- """Append a title revision at the same path through the current file edit right."""
- session, identity = trusted_identity(caller)
- _authorize(session)
- path = normalize_path(path)
- _assert_authored_path(path)
- if not isinstance(title, str) or not title.strip() or len(title.strip()) > 200:
- raise IntelligenceError("bad_title", "Use a title of 1 to 200 characters.")
- if type(expected_version) is not int or expected_version < 1:
- raise IntelligenceError("bad_version", "Reload the file before trying again.")
- if _database_note_path(path):
- if identity.get("agent"):
- raise IntelligenceError("approval_required", "An agent cannot rename a shared note.", 403)
- record = _database_note_record(session, path[len(DATABASE_NOTES_PREFIX):-3], with_body=True)
- if record["path"] != path:
- raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
- entry = _head(record)
- _put_database_note(session, record["databaseKey"], entry["body"], session.uname,
- expected_version, entry["created"], title=title.strip())
- saved = _database_note_file(session, path)
- _log_write(session, path, identity, expected_version, saved["version"])
- return saved
- saved = {}
-
- def rename(raw):
- saved.clear()
- files = _editable_files(session, raw, path)
- record = _readable_record(session, files, path)
- head = _head(record)
- if not can_edit(session, head["metadata"]):
- raise IntelligenceError("file_read_only", "Your current rights do not allow renaming this file.", 403)
- if head["version"] != expected_version:
- raise IntelligenceError("version_conflict", "The file changed. Reload it before renaming.", 409)
- if len(record["versions"]) >= MAX_VERSIONS:
- raise IntelligenceError("too_many_versions", "This file already has 100 versions.", 409)
- metadata = {**head["metadata"], "title": title.strip()}
- body, metadata = prepare_markdown("---\n" + yaml.safe_dump(metadata, sort_keys=False, allow_unicode=True)
- + "---\n" + head["body"].partition("\n---\n")[2], session.uname)
- record = {**record, "versions": [*record["versions"], _entry(body, metadata, expected_version + 1, identity)],
- "proposals": {key: {**row, "status": "stale"} if row["status"] in ("pending", "approving") else row
- for key, row in (record.get("proposals") or {}).items()}}
- files[path] = record
- saved.update(_file(record, session=session))
- return files
-
- _update(session, rename)
- _log_write(session, path, identity, expected_version, saved["version"])
- return saved
-
-
-def delete_file(caller, path, *, expected_version=None):
- """Delete an editable workspace file or clear its canonical database note."""
+def delete_file(caller, path):
+ """Delete one workspace file and its versions without touching agent files."""
session, identity = trusted_identity(caller)
_authorize(session)
path = normalize_path(path)
_assert_authored_path(path)
- if expected_version is not None and (type(expected_version) is not int or expected_version < 1):
- raise IntelligenceError("bad_version", "Reload the file before trying again.")
if _database_note_path(path):
- if identity.get("agent"):
- raise IntelligenceError("approval_required", "An agent cannot delete a shared note.", 403)
- record = _database_note_record(session, path[len(DATABASE_NOTES_PREFIX):-3], with_body=True)
- if record["path"] != path:
- raise IntelligenceError("no_file", "This workspace has no file at that path.", 404)
- entry = _head(record)
- _put_database_note(session, record["databaseKey"], "", session.uname,
- expected_version if expected_version is not None else entry["version"],
- entry["created"], deleted=True)
- _log_write(session, path, identity, entry["version"], None)
- return {"deleted": path}
+ _database_note_file(session, path)
+ raise IntelligenceError("database_note_reserved", "A Database note belongs to its database.", 403)
removed = {}
def remove(raw):
@@ -2022,10 +1875,6 @@ def delete_file(caller, path, *, expected_version=None):
files = _editable_files(session, raw, path)
record = _readable_record(session, files, path)
removed["version"] = _head(record)["version"]
- if not identity.get("agent") and not can_edit(session, _head(record)["metadata"]):
- raise IntelligenceError("file_read_only", "Your current rights do not allow deleting this file.", 403)
- if expected_version is not None and expected_version != removed["version"]:
- raise IntelligenceError("version_conflict", "The file changed. Reload it before deleting.", 409)
if identity.get("agent") and (record.get("memoryScope") != [identity["agent"], session.uname]
or not _head(record) or _head(record)["metadata"]["section"] != "agent-memory"):
raise IntelligenceError("approval_required", "An agent cannot delete a shared file.", 403)
diff --git a/api/routes_agent_harness.py b/api/routes_agent_harness.py
index e66826803af22a1dbbfb17dff29e486f389710c2..2c9e24f2423043046f40bc61d2b9c34e21b5fa93 100644
--- a/api/routes_agent_harness.py
+++ b/api/routes_agent_harness.py
@@ -197,54 +197,13 @@ def decide_intelligence_proposal(proposal_id: str, decision: str, body: dict = B
@router.delete("/intelligence/files")
-def delete_intelligence_file(path: str = "", expectedVersion: int = None,
+def delete_intelligence_file(path: str = "",
session: Session = Depends(module_gate("intelligence"))):
"""Delete a workspace file under the Intelligence module grant."""
import intelligence_store as intelligence
try:
- if type(expectedVersion) is not int or expectedVersion < 1:
- raise intelligence.IntelligenceError("bad_version", "Reload the file before trying again.")
- return {"deleted": intelligence.delete_file(session, path, expected_version=expectedVersion)["deleted"]}
- except intelligence.IntelligenceError as exc:
- raise _intelligence_error(exc) from None
-
-
-@router.patch("/intelligence/files")
-def rename_intelligence_file(body: dict = Body(default=None),
- session: Session = Depends(module_gate("intelligence"))):
- import intelligence_store as intelligence
-
- body = body or {}
- try:
- return intelligence.rename_file(session, body.get("path"), body.get("title"),
- expected_version=body.get("expectedVersion"))
- except intelligence.IntelligenceError as exc:
- raise _intelligence_error(exc) from None
-
-
-@router.patch("/intelligence/folders")
-def rename_intelligence_folder(body: dict = Body(default=None),
- session: Session = Depends(module_gate("intelligence"))):
- import intelligence_store as intelligence
-
- body = body or {}
- try:
- if "name" not in body or not isinstance(body["name"], str):
- raise intelligence.IntelligenceError("bad_name", "Enter a folder name.")
- return intelligence.change_folder(session, body.get("path"), name=body["name"],
- expected_revision=body.get("expectedRevision"))
- except intelligence.IntelligenceError as exc:
- raise _intelligence_error(exc) from None
-
-
-@router.delete("/intelligence/folders")
-def delete_intelligence_folder(path: str = "", expectedRevision: int = None,
- session: Session = Depends(module_gate("intelligence"))):
- import intelligence_store as intelligence
-
- try:
- return intelligence.change_folder(session, path, expected_revision=expectedRevision)
+ return intelligence.delete_file(session, path)
except intelligence.IntelligenceError as exc:
raise _intelligence_error(exc) from None
diff --git a/api/routes_alerts.py b/api/routes_alerts.py
index 630594e2be9e3863ae74b79451d5fa2abf27a253..8bc57edc2bb9e7b9698dbd519b969a3da5d4f1a8 100644
--- a/api/routes_alerts.py
+++ b/api/routes_alerts.py
@@ -279,48 +279,34 @@ def list_alerts(session: Session = Depends(require_session)):
st=session.runtime)}
-def _notification_visible(session, item, *, memo=None):
+def _notification_visible(session, item):
"""Apply the current database admission doors without evaluating or changing alerts."""
from assistant_feed import _target
target = _target(item)
if not target:
return True
- module = str(target.get("module") or "").strip()
- database = (str(target.get("id") or "").strip() if module == "database" else
+ module = str(target.get("module") or "")
+ database = (str(target.get("id") or "") if module == "database" else
module if module.startswith("ut_") or module in {"customer_data", "product_data"} else "")
if not database:
return module != "database"
- if memo is not None and database in memo["databases"]:
- return memo["databases"][database]
- visible = True
try:
session.require(database)
if database.startswith("ut_"):
from routes_tables import _defn_or_refuse
- if memo is None:
- _defn_or_refuse(session, database, defs_only=True, scope_applied=True)
- else:
- from core import user_tables
- if memo["definitions"] is None:
- memo["definitions"] = user_tables.lend_defs(session.runtime)
- _defn_or_refuse(session, database, st=memo["definitions"],
- defs_only=True, scope_applied=True)
+ _defn_or_refuse(session, database, defs_only=True, scope_applied=True)
except HTTPException as exc:
if exc.status_code in {403, 404, 409}:
- visible = False
- else:
- raise
- if memo is not None:
- memo["databases"][database] = visible
- return visible
+ return False
+ raise
+ return True
@router.get("/notifications")
def list_notifications(session: Session = Depends(require_session)):
items = (session.runtime.get(alerts.NOTIFICATIONS_KEY) or {}).get(str(session.uname)) or []
- memo = {"databases": {}, "definitions": None}
visible = [dict(item) for item in items if isinstance(item, dict)
- and _notification_visible(session, item, memo=memo)]
+ and _notification_visible(session, item)]
visible.sort(key=lambda item: str(item.get("at") or ""), reverse=True)
return {"unread": sum(not item.get("read") for item in visible), "items": visible}
diff --git a/api/routes_automation.py b/api/routes_automation.py
index c100952dcec45c352e3bedf66a6f603c8567c9ef..741d49a7ab54308c7aae40fa7d251171989e03b8 100644
--- a/api/routes_automation.py
+++ b/api/routes_automation.py
@@ -61,29 +61,6 @@ MODULE = "automation"
_GATE = module_gate(MODULE)
-def _item_rights(session, item):
- """Use the item's owner for writes, with Administrator authority and system exclusions."""
- if item and item.get("id") == ODOO_SYNC_ID:
- return {"edit": bool(session.admin), "delete": False}
- editable = bool(item and session.uname and not item.get("system") and not item.get("retired")
- and not str(item.get("id") or "").startswith(("field:", "system:"))
- and not item.get("retiredOnceAt") and (session.admin or session.uname ==
- (item.get("createdBy") or item.get("created_by"))))
- return {"edit": editable, "delete": editable}
-
-
-def _require_item_edit(session, item):
- if not item:
- raise err(404, "unknown_automation", "This item is no longer available.")
- if not _item_rights(session, item)["edit"]:
- raise err(403, "automation_read_only", "Your current rights do not allow changes to this item.")
-
-
-def _voice_item_rights(session, row, record):
- row["capabilities"] = {**row.get("capabilities", {}), **_item_rights(session, record)}
- return row
-
-
def _governed_query_tool(session, database=""):
"""Adapt C4 dry-runs to B's mounted C2 Query door without owning Query authority."""
def invoke(prompt, context):
@@ -271,11 +248,8 @@ def list_voice_agents(session: Session = Depends(_GATE)):
"""
rows = voice.list_browser_dtos(session.runtime)
options = _voice_options(session) if rows else None
- records = voice._store(session.runtime)["voice_agent"] if rows else {}
for row in rows:
row["audienceOptions"] = options
- voice_id = row.get("automationId") or row.get("voiceAgentId")
- _voice_item_rights(session, row, records.get(voice_id))
return {"voiceAgents": rows}
@@ -290,7 +264,6 @@ def create_voice_agent(body: dict = Body(default=None), session: Session = Depen
saved = voice.save_draft(session.runtime, body or {}, session.uname, tenant_id=session.tenant)
row = voice.get_browser_dto(session.runtime, saved["id"])
row["audienceOptions"] = _voice_options(session)
- _voice_item_rights(session, row, saved)
return {"voiceAgent": row}
except voice.VoiceRefusal as exc:
raise err(400, "voice_refused", str(exc))
@@ -299,36 +272,14 @@ def create_voice_agent(body: dict = Body(default=None), session: Session = Depen
@router.patch("/voice-agents/{voice_id}")
def patch_voice_agent(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
try:
- record = voice._store(session.runtime)["voice_agent"].get(voice_id)
- _require_item_edit(session, record)
- saved = voice.patch_draft(session.runtime, voice_id, body or {}, session.uname)
+ voice.patch_draft(session.runtime, voice_id, body or {}, session.uname)
row = voice.get_browser_dto(session.runtime, voice_id)
row["audienceOptions"] = _voice_options(session)
- _voice_item_rights(session, row, saved)
return {"voiceAgent": row}
except voice.VoiceRefusal as exc:
raise err(400 if "unknown" not in str(exc) else 404, "voice_refused", str(exc))
-@router.delete("/voice-agents/{voice_id}")
-def delete_voice_agent(voice_id: str, session: Session = Depends(_GATE)):
- """Remove a local Voice definition and disable local routes without changing provider resources."""
- def remove(doc):
- _require_item_edit(session, doc["voice_agent"].get(voice_id))
- if any(row.get("voice_agent_id") == voice_id and row.get("state") == "active"
- and row.get("expires_at", 0) > time.time()
- for row in doc["voice_outbound_lease"].values()):
- raise err(409, "voice_running", "Wait for this Voice agent's active work to finish.")
- del doc["voice_agent"][voice_id]
- for route in doc["voice_number_route"].values():
- if route.get("voice_agent_id") == voice_id:
- route["status"] = "inactive"
- return doc
-
- voice._update(session.runtime, remove)
- return {"deleted": voice_id}
-
-
@router.post("/voice-agents/{voice_id}/harness/dry-run")
def voice_dry_run(voice_id: str, body: dict = Body(default=None), session: Session = Depends(_GATE)):
body = body or {}
@@ -534,7 +485,7 @@ def _sync_schedule_or_503(tenant, defn):
f"Nothing was reported as armed: {exc}")
-def _wire(defn, tenant, rt=None, session=None):
+def _wire(defn, tenant, rt=None):
"""One automation, as the client reads it. `running` is PROCESS state, never store state —
see the engine header on why a persisted 'running' is a permanent lock."""
live = engine.running(tenant, defn.get("id"))
@@ -546,7 +497,7 @@ def _wire(defn, tenant, rt=None, session=None):
status = {**status, "state": "running", "startedAt": live.get("startedAt"),
"step": live.get("step")}
agent_contract = engine.agent_contract_dto(rt, defn.get("id")) if rt else None
- row = {
+ return {
"id": defn.get("id"), "name": defn.get("name"), "kind": defn.get("kind"),
"config": defn.get("config") or {}, "schedule": sched, "status": status,
"runs": list(defn.get("runs") or [])[:engine.MAX_RUNS],
@@ -649,9 +600,6 @@ def _wire(defn, tenant, rt=None, session=None):
"This system Agent is configured at its source."}
}),
}
- row["capabilities"] = {**row.get("capabilities", {}),
- **(_item_rights(session, defn) if session else {"edit": False, "delete": False})}
- return row
#: ⭐⭐ WAVE 34 · CONTRACTS C3 + C4 — WHY A ROW CANNOT BE DELETED, as a slug.
@@ -753,7 +701,7 @@ def _field_agent_rows(session):
# — the exact way `awaitingResults` shipped inert for a whole wave. Passing the
# synthetic DEFINITION through the same function makes them identical by
# construction; only `system` is stamped afterwards, because no stored row has it.
- row = _wire(defn_syn, session.tenant, rt=session.runtime, session=session)
+ row = _wire(defn_syn, session.tenant, rt=session.runtime)
row["system"] = SYSTEM_FIELD_AGENT
out.append(row)
return out
@@ -912,7 +860,7 @@ def _odoo_sync_row(session, detail=False):
"config": {"connector": "odoo", "every": every,
"frozen": frozen}}]},
}
- row = _wire(defn, session.tenant, rt=session.runtime, session=session)
+ row = _wire(defn, session.tenant, rt=session.runtime)
row["system"] = SYSTEM_ODOO_SYNC
# ⛔ THE SENTENCE IS OVERRIDDEN, AND IT IS A FIX RATHER THAN A PREFERENCE. `compose_sentence`
# speaks the automation vocabulary — it builds "When , run N actions" out of
@@ -1371,7 +1319,7 @@ def list_automations(session: Session = Depends(_GATE)):
pass
_STATEMENTS_SEEDED.add(session.tenant)
defs = engine.all_definitions(session.runtime)
- items = [_wire(d, session.tenant, rt=session.runtime, session=session) for _, d in
+ items = [_wire(d, session.tenant, rt=session.runtime) for _, d in
sorted(defs.items(), key=lambda kv: (kv[1].get("name") or "").lower())]
# ⭐⭐ WAVE 34 · CONTRACT C3 (W34-T48) — field agents join the list as SYNTHETIC rows.
# ⚠ MERGED AND RE-SORTED, not appended in a block at the end. R13 asks for a field agent to be
@@ -2169,7 +2117,7 @@ def agent_author_action(auto_id: str, body: dict = Body(default=None),
session.runtime.update(AGENT_ACTIONS_KEY, _set, flush="sync")
_prune_marks(session, auto_id)
- return {"automation": _wire(updated, session.tenant, rt=session.runtime, session=session),
+ return {"automation": _wire(updated, session.tenant, rt=session.runtime),
"actionId": action_id, "agent": agent_id, "notes": notes}
@@ -2240,7 +2188,7 @@ def get_automation(auto_id: str, session: Session = Depends(_GATE)):
defn = engine.all_definitions(session.runtime).get(str(auto_id))
if defn is None:
raise err(404, "unknown_automation", "no automation with that id")
- return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session)}
+ return {"automation": _wire(defn, session.tenant, rt=session.runtime)}
@router.post("/automations")
@@ -2265,7 +2213,7 @@ def create_automation(body: dict = Body(default=None), session: Session = Depend
engine.ensure_agent_contract(session.runtime, defn.get("id"), session.uname,
defn.get("name") or "")
_sync_schedule_or_503(session.tenant, defn)
- return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session), "notes": _notes}
+ return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
@router.patch("/automations/{auto_id}")
@@ -2296,10 +2244,7 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
# now but still the guard for any other caller of that function.
if not _odoo_connected(session):
raise err(404, "unknown_automation", "no automation with that id")
- if not session.admin:
- raise err(403, "automation_read_only", "Only an Administrator can change the connector schedule.")
return _patch_odoo_sync(session, body or {})
- _require_item_edit(session, engine.all_definitions(session.runtime).get(str(auto_id)))
# D-75, same channel as `create` above — an EDIT is where this matters most, because the
# person has just typed the thing that gets dropped.
# ⛔⛔ W36-T38 / R9 — THE AGENT-OWNED WALL, AT THE DOOR, BEFORE ANY WRITE. A `disabled`
@@ -2320,7 +2265,7 @@ def patch_automation(auto_id: str, body: dict = Body(default=None),
# and refuses an id nobody can see.
_prune_marks(session, auto_id)
_sync_schedule_or_503(session.tenant, defn)
- return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session), "notes": _notes}
+ return {"automation": _wire(defn, session.tenant, rt=session.runtime), "notes": _notes}
def _stored_agent_or_404(session, agent_id):
@@ -2502,7 +2447,6 @@ def delete_automation(auto_id: str, session: Session = Depends(_GATE)):
_sys = str(_defn.get("system") or "").strip()
if _sys:
raise err(409, "system_agent", engine.system_agent_refusal(_sys))
- _require_item_edit(session, _defn)
engine.remove(session.runtime, auto_id)
# R9's other half: the user MAY delete an agent-authored step, and deleting the whole
# automation takes its annotations with it rather than stranding them in the document.
@@ -2574,7 +2518,7 @@ def toggle_automation_node(auto_id: str, node_id: str, session: Session = Depend
"unknown_automation" if error == "no such automation" else "node_not_toggleable",
error)
_sync_schedule_or_503(session.tenant, defn)
- return {"automation": _wire(defn, session.tenant, rt=session.runtime, session=session)}
+ return {"automation": _wire(defn, session.tenant, rt=session.runtime)}
@router.post("/automations/{auto_id}/hook/{token}")
diff --git a/api/routes_external.py b/api/routes_external.py
index 083e281501ef0aa3331c4dae77e5443346516b14..c31671a60c75fb2ad0309e784be8af11c5f3b37e 100644
--- a/api/routes_external.py
+++ b/api/routes_external.py
@@ -156,8 +156,10 @@ class _PreviewRuntime:
def _load(self, name):
key = str(name)
if key not in self._docs:
- import application_registry
- value = application_registry._read_strict(self._real, key)
+ try:
+ value = self._real.get(key, fresh=True)
+ except TypeError:
+ value = self._real.get(key)
value = copy.deepcopy(value)
self._initial[key] = copy.deepcopy(value)
self._docs[key] = value
@@ -172,9 +174,6 @@ class _PreviewRuntime:
def get(self, name, *args, **kwargs):
return copy.deepcopy(self._load(name))
- def _read_strict(self, name):
- return self.get(name)
-
def get_projection(self, name, drop=()):
value = self.get(name)
if isinstance(value, dict):
@@ -3121,12 +3120,12 @@ def _bucket_revision(st, key, fallback):
return {"rev": None, "token": _json_digest(fallback)}
-def _database_value_plan(session, database, record_id, values, fields, *, apply_defaults=False):
+def _database_value_plan(session, database, record_id, values, fields):
"""Apply the grid's field/value vocabulary without calling its event side effects."""
from core import grid_events, user_tables
import aios_grid
- if not isinstance(values, dict) or (not values and not apply_defaults):
+ if not isinstance(values, dict) or not values:
raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
field_by_key = {str(field.get("key")): field for field in fields if isinstance(field, dict)}
unknown = sorted(str(key) for key in values if str(key) not in field_by_key)
@@ -3134,7 +3133,8 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
raise err(403, "field_unavailable",
"Every changed field must be readable and editable in this database.")
ctx = _view_context(session, database, {"pid": record_id})
- for key in values:
+ planned = {}
+ for key, raw in values.items():
key = str(key)
definition = field_by_key[key]
if key in (ctx.hidden_keys or frozenset()) or not grid_events._may_edit_field_value(
@@ -3143,26 +3143,6 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
"Every changed field must be readable and editable in this database.")
if user_tables.is_computed_cell(definition) or definition.get("type") == "automation":
raise err(403, "computed_field", "A computed or automation field is read only.")
- if apply_defaults:
- editable = [definition for key, definition in field_by_key.items()
- if key not in (ctx.hidden_keys or frozenset())
- and grid_events._may_edit_field_value(ctx, key, definition)
- and not user_tables.is_computed_cell(definition)
- and definition.get("type") != "automation"]
- try:
- expanded = user_tables._new_row_values(editable, values)
- except ValueError as exc:
- raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300]) from exc
- if expanded is None:
- raise err(400, "bad_value", "A field default is not valid for its field.")
- # Supplied arrays and typed cells must reach their normalizers unchanged.
- values = {**expanded, **values}
- if not values:
- raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
- planned = {}
- for key, raw in values.items():
- key = str(key)
- definition = field_by_key[key]
why = user_tables.cell_type_refusal(definition, raw)
if why:
raise err(400, "bad_value", why)
@@ -3170,15 +3150,8 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
bag = definition.get("link") if isinstance(definition.get("link"), dict) else {}
if bag.get("on") or bag.get("inverse"):
raise err(403, "computed_field", "A derived link field is read only.")
- target_database = str(bag.get("table") or "")
- _assert_database_scope(session, target_database)
- target = _external_read_scope(session, target_database)
- target_fields = target["fields"]
- available = {str(row["pid"]): row for row in target["records"]}
- if ("selectionFilter" in bag and user_tables.clean_link_selection_filter(
- bag["selectionFilter"], target_fields) is None):
- raise err(400, "link_selection_refused",
- "The link selection condition is invalid or names an unavailable field.")
+ target = user_tables.get(str(bag.get("table") or ""), st=session.runtime) or {}
+ available = set((target.get("rows") or {}).keys())
raw_ids = raw if isinstance(raw, (list, tuple, set)) else str(raw or "").split(",")
selected = []
for item in raw_ids:
@@ -3187,9 +3160,6 @@ def _database_value_plan(session, database, record_id, values, fields, *, apply_
continue
if candidate not in available or len(selected) >= user_tables.LINK_MAX_IDS:
raise err(400, "bad_value", "A linked record is unavailable.")
- if not user_tables.link_selection_permits(definition, available[candidate], target_fields):
- raise err(400, "link_selection_refused",
- "That record does not match the link selection condition. Choose an available record.")
selected.append(candidate)
if bag.get("single"):
break
@@ -3262,8 +3232,9 @@ def _plan_database_write(session, args):
rows = table.get("rows") or {}
if action == "record_create":
raw_values = args.get("values")
- values = _database_value_plan(
- session, database, None, raw_values, g["fields"], apply_defaults=True)
+ # An empty object is a valid create when field defaults fill it (checked below).
+ values = ({} if isinstance(raw_values, dict) and not raw_values else
+ _database_value_plan(session, database, None, raw_values, g["fields"]))
record_id = str(max((int(key) for key in rows if str(key).isdigit()), default=0) + 1)
before, after = None, values
else:
@@ -3292,8 +3263,16 @@ def _plan_database_write(session, args):
else:
try:
if action == "record_create":
+ # The grid's core insert rules: defaults, server-owned numbers, creation order.
+ after = user_tables._new_row_values(target.get("fields") or [], after)
+ if after is None:
+ raise err(400, "bad_value", "A field default is not valid for its field.")
+ if not after:
+ raise err(400, "tool_arguments_invalid", "Record values must be a non-empty object.")
user_tables.allocate_autonumbers(target, after)
user_tables._stamp_row_creation(target, record_id)
+ user_tables._validate_link_selection_values(
+ target.get("fields") or [], values, bucket_after)
except ValueError as exc:
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300])
target.setdefault("rows", {})[record_id] = copy.deepcopy(after)
@@ -4045,8 +4024,6 @@ def _preview_external_write(session, name, arguments, *, issue_token=True, execu
response["purpose"] = purpose
if name == "views" and normalised.get("action") == "share":
response.update({key: copy.deepcopy(result[key]) for key in ("view", "audience")})
- if name == "apps" and normalised.get("action") == "catalog_build":
- response.update({key: copy.deepcopy(result[key]) for key in _CATALOG_BUILD_RESULT_FIELDS})
if payload["strong"]:
response["confirmation_phrase"] = _CONFIRMATION_PHRASE
if issue_token:
@@ -4288,7 +4265,6 @@ def _confirmation_status(session, operation_id, status, result=None):
def _committed_build_evidence(session, writer, arguments, *, build_kind=None):
"""Resolve identities from committed documents and this writer's native inserts."""
import application_registry
- import catalog_store
import automation_engine
import intelligence_store as files
import wiki_log
@@ -4327,11 +4303,6 @@ def _committed_build_evidence(session, writer, arguments, *, build_kind=None):
for identity in before.keys() | after.keys():
if before.get(identity) != after.get(identity):
add("schedule", identity)
- elif key == catalog_store.STORE_KEY:
- before, after = before.get("catalogs") or {}, after.get("catalogs") or {}
- for identity in before.keys() | after.keys():
- if before.get(identity) != after.get(identity):
- add("app", (after.get(identity) or before.get(identity) or {}).get("appId"))
elif key in (application_registry._KEY, automation_engine.STORE_KEY):
kind = "app" if key == application_registry._KEY else "automation"
if kind == "app":
@@ -4553,7 +4524,6 @@ MCP_RESULT_CODES = {
code: reason for reason, codes in _MCP_CODE_GROUPS for code in codes.split()
}
MCP_RESULT_CODES.update({
- "link_selection_refused": "Choose a readable linked record that matches the field's selection condition.",
"app_rule": "Correct the App rule named in the refusal before saving it.",
"audience_not_allowed": "A person must choose sharing with everyone on screen.",
"not_owner": "You cannot administer this item's audience.",
@@ -4685,7 +4655,7 @@ _MCP_RESULT_IDENTIFIERS = frozenset({
"resourceUri", "deepLink", "pdfLink", "src", "websiteUrl", "fileId", "link", "href",
"id", "ids", "operation_id", "key", "keys", "pid", "pids", "database", "databases", "sourceDatabase",
"compatibleDatabases", "field", "fields", "field_key", "colId", "metric_key", "groupBy",
- "workbook_id", "worksheet", "tab", "view_id", "app_id", "catalog_id", "chart_id", "record_id", "contextId",
+ "workbook_id", "worksheet", "tab", "view_id", "app_id", "chart_id", "record_id", "contextId",
"path", "paths", "address", "addresses", "range", "cursor", "next_cursor", "token",
"source_version", "code", "tool", "action", "person", "agent", "owner", "author", "from", "to",
"username", "tenant", "createdBy", "updatedBy", "by", "byName", "reads", "approvers", "tags", "updated",
@@ -5196,7 +5166,9 @@ def _mcp_guide(session: Session, group=None) -> str:
"Call a group with action and arguments. Each action keeps its own read or write rules.",
"Every tool accepts optional intent beside action and arguments. Every write requires it, including "
"previews, confirm_change, requests.send and intelligence.create_wiki. Use 1 to 500 characters. "
- 'Example: {"intent":"Prepare the weekly sales review"}. Intent is stripped before dispatch.',
+ 'Example: {"intent":"Prepare the weekly sales review"}. Intent is stripped before dispatch. '
+ "A client that cannot send keys beside action and arguments may put intent, about and purpose "
+ "inside arguments. The value beside action and arguments wins.",
"Each tool call records one external.query event with tool, action, outcome and argument keys and types. "
"Large shapes continue in argument_shape_1 and later numbered fields. Unknown keys are redacted. "
"Argument values are never recorded. Intent is retained only when sent, with credential patterns redacted. "
@@ -5208,7 +5180,7 @@ def _mcp_guide(session: Session, group=None) -> str:
"characters, and one or more distinct tags below. intelligence.create_wiki needs the same about "
"and still publishes directly. The tool supplies the build kind. Confirmation uses the saved about.",
"Build tags: " + ", ".join(external_tools.BUILD_TAGS) + ".",
- "For a previewed build, put optional purpose beside action and arguments, not inside arguments. "
+ "For a previewed build, put optional purpose beside action and arguments. "
"Use one line of 1 to 240 characters without control characters or long dashes. "
"Confirmation uses that saved purpose; do not send a new purpose to confirm_change.",
"Previous tool names remain callable for one release, but are absent from tools/list.", ""]
@@ -5223,6 +5195,7 @@ def _mcp_guide(session: Session, group=None) -> str:
from tool_groups.data import query_guide
lines += [query_guide(rows), ""]
states = {row["action"]: row for row in capabilities if row["group"] == group}
+ uses_filter_node = False
for action, entry in selected["actions"].items():
lines += ["### " + action,
"State: " + states[action]["state"] + "."
@@ -5234,7 +5207,11 @@ def _mcp_guide(session: Session, group=None) -> str:
lines.append("Previous name: `" + entry["legacy_name"] + "`.")
schema = copy.deepcopy(entry["schema"])
schema.get("properties", {}).pop("about", None)
+ schema, collapsed = external_tools.guide_schema(schema)
+ uses_filter_node = uses_filter_node or collapsed
lines += ["```json", json.dumps(_mcp_schema_copy(schema), ensure_ascii=True, indent=2), "```", ""]
+ if uses_filter_node:
+ lines += [external_tools.filter_node_guide(), ""]
return _MCPGuideText("\n".join(lines) + "\n")
lines += ["## Connected AI clients", "",
"Client names and who connected them in this workspace. No entries means none are connected.",
@@ -5365,13 +5342,14 @@ def _handle_mcp(req, session: Session, base_url: str = ""):
return reply
params = req.get("params")
params = params if isinstance(params, dict) else {}
- tool, schema = _mcp_audit_schema(params.get("name"), params.get("arguments"))
- limitation_tool, limitation_action = _mcp_limitation_address(tool, params.get("arguments"))
+ arguments = _mcp_hoist_call_metadata(params.get("name"), params.get("arguments", {}))
+ tool, schema = _mcp_audit_schema(params.get("name"), arguments)
+ limitation_tool, limitation_action = _mcp_limitation_address(tool, arguments)
try:
with external_activity.capture_call(session, tool) as call:
if tool == limitation_tool:
external_activity.note_action(limitation_action)
- external_activity.note_arguments(params.get("arguments", {}), schema)
+ external_activity.note_arguments(arguments, schema)
metadata = params.get("_meta")
call["question"] = metadata.get("loopable/question") if isinstance(metadata, dict) else None
reply = _dispatch_mcp(req, session, base_url)
@@ -5451,6 +5429,23 @@ def _mcp_call_intent(arguments):
return value
+def _mcp_hoist_call_metadata(name, arguments):
+ """Return group call arguments with intent, about and purpose lifted out of the inner arguments."""
+ import tool_groups
+ keys = ("intent", "about", "purpose")
+ if (not isinstance(name, str) or name not in tool_groups.groups() or not isinstance(arguments, dict)
+ or not isinstance(arguments.get("arguments"), dict)
+ or not any(key in arguments["arguments"] for key in keys)):
+ return arguments
+ inner = arguments["arguments"]
+ hoisted = {**arguments, "arguments": {key: value for key, value in inner.items() if key not in keys}}
+ # The value beside action and arguments wins over the nested copy.
+ for key in keys:
+ if key in inner and key not in arguments:
+ hoisted[key] = inner[key]
+ return hoisted
+
+
def _mcp_requires_intent(name, arguments):
"""Classify declared writes before argument validation can mask the intent requirement."""
if name == "confirm_change":
@@ -5525,7 +5520,7 @@ def _dispatch_mcp(req, session: Session, base_url: str = ""):
return {"jsonrpc": "2.0", "id": rid, "result": {"contents": [resource]}}
if method != "tools/call":
return protocol_error(rid, -32601, "The requested MCP method was not found.")
- arguments = params.get("arguments", {})
+ arguments = _mcp_hoist_call_metadata(name, params.get("arguments", {}))
intent = _mcp_call_intent(arguments)
if intent is None and _mcp_requires_intent(name, arguments):
raise err(400, "call_intent_required", "Send intent explaining why you are making this write.",
@@ -5548,10 +5543,6 @@ def _dispatch_mcp(req, session: Session, base_url: str = ""):
purpose = _build_purpose(arguments.pop("purpose"))
if "about" in metadata_keys:
about = arguments.pop("about")
- if (name in tool_groups.groups() and isinstance(arguments, dict)
- and isinstance(arguments.get("arguments"), dict)
- and {"about", "purpose", "intent"} & arguments["arguments"].keys()):
- raise err(400, "tool_arguments_invalid", "Send intent and build metadata beside action and arguments.")
_assert_tool_query_filter_bounds(name, arguments)
resolved = tool_groups.resolve(name, arguments)
confirm = True
diff --git a/api/routes_geo.py b/api/routes_geo.py
index c43bf9441efa92d5c66f52b35ea5b528391d396c..a0f00c7ac995e12dce4209931f72e8db0317a38b 100644
--- a/api/routes_geo.py
+++ b/api/routes_geo.py
@@ -327,40 +327,10 @@ def _zone_context(session, raw_table_key):
return table_key, fields, set(grid.get("pids") or ()), list(grid.get("rows_src") or ())
-def _zone_application(session, table_key, application, *, write=False):
- """Authorize an explicit App and its bound database before reading its Zones."""
- if application is None:
- return None
- if not isinstance(application, str) or not application.strip() or len(application) > 120:
- raise err(400, "invalid_route_application", "choose a Routing App id")
- application = application.strip()
- table_key = str(table_key or "").strip()
- import application_registry as registry
- from core import route_system
- try:
- doc = registry._read_strict(session.runtime, registry._KEY) or {}
- if not isinstance(doc, dict) or not isinstance(doc.get("applications", {}), dict):
- raise ValueError("invalid Application registry")
- except Exception:
- raise err(503, "application_store_unavailable", "the Application registry is unavailable")
- app = doc.get("applications", {}).get(application)
- if app is None and session.admin and not write and route_system.list_zones(
- session.runtime, table_key=table_key, application=application):
- return application
- if not isinstance(app, dict) or app.get("tenant") != session.tenant:
- raise err(404, "route_application_not_found", "that Routing App does not exist")
- if not registry.may_read(app, session.uname, is_admin=session.admin):
- raise err(403, "route_application_forbidden", "your account cannot open this Routing App")
- source = app.get("sourceDatabase")
- if (source != table_key if source else table_key not in (app.get("compatibleDatabases") or ())):
- raise err(409, "route_application_source", "this App does not use the selected database")
- return application
-
-
-def _zone_subject(session, table_key, zone_id, application=None):
+def _zone_subject(session, table_key, zone_id):
from core import route_system
zone = next((item for item in route_system.list_zones(
- session.runtime, table_key=table_key, application=application)
+ session.runtime, table_key=table_key)
if str(item.get("id") or "") == str(zone_id)), None)
if not isinstance(zone, dict):
raise err(404, "unknown_zone", "no Zone with that id")
@@ -603,13 +573,11 @@ def geo_providers(session: Session = Depends(require_session)):
@router.get("/geo/zones")
-def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session),
- application: str = None):
+def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(require_session)):
"""The canonical table-scoped Zone DTOs a Map may draw or filter by."""
from core import route_system
- application = _zone_application(session, tableKey, application)
table_key, _fields, pids, rows = _zone_context(session, tableKey)
- zones = route_system.list_zones(session.runtime, rows, table_key=table_key, application=application)
+ zones = route_system.list_zones(session.runtime, rows, table_key=table_key)
# A hidden Zone remains recoverable to its creator/admin, but cannot become visible through a
# second table simply because row ids happen to collide there.
visible = [zone for zone in zones if zone.get("visible", True)
@@ -620,14 +588,10 @@ def geo_zones(tableKey: str = Query(default=""), session: Session = Depends(requ
@router.post("/geo/zones")
-def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session),
- application: str = None):
+def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(require_session)):
"""Persist one Zone in the existing table-scoped Zone store and field/filter contract."""
from core import route_system
body = body if isinstance(body, dict) else {}
- from routes_customers import _route_application_body
- _route_application_body(body, application)
- application = _zone_application(session, body.get("tableKey"), application, write=True)
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
try:
if any(key in body for key in ("memberships", "memberPids", "member_pids")):
@@ -637,7 +601,7 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(
"geometryGeoJson": body.get("geometryGeoJson"), "zipCodes": body.get("zipCodes"),
"visible": body.get("visible"), "geographicField": body.get("geographicField")
}, rows=rows, tenant_id=session.tenant, created_by=session.uname,
- table_key=table_key, application=application)
+ table_key=table_key)
if zone is None:
raise ValueError("the Zone does not match this database's fields and records")
except ValueError as exc:
@@ -649,15 +613,12 @@ def geo_zone_create(body: dict = Body(default=None), session: Session = Depends(
@router.patch("/geo/zones/{zone_id}")
def geo_zone_update(zone_id: str, body: dict = Body(default=None),
- session: Session = Depends(require_session), application: str = None):
+ session: Session = Depends(require_session)):
"""Edit a table-scoped Zone while retaining creator, geometry and membership invariants."""
from core import route_system
body = body if isinstance(body, dict) else {}
- from routes_customers import _route_application_body
- _route_application_body(body, application)
- application = _zone_application(session, body.get("tableKey"), application, write=True)
table_key, field_keys, pids, rows = _zone_context(session, body.get("tableKey"))
- previous = _zone_subject(session, table_key, zone_id, application)
+ previous = _zone_subject(session, table_key, zone_id)
try:
if any(key in body for key in ("memberships", "memberPids", "member_pids")):
raise ValueError("Zone membership is derived from current permitted rows")
@@ -669,7 +630,7 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
"visible": body.get("visible", previous.get("visible")),
"geographicField": body.get("geographicField", previous.get("geographicField"))
}, rows=rows, tenant_id=session.tenant, created_by=session.uname,
- table_key=table_key, application=application)
+ table_key=table_key)
if zone is None:
raise ValueError("the Zone does not match this database's fields and records")
except ValueError as exc:
@@ -679,16 +640,13 @@ def geo_zone_update(zone_id: str, body: dict = Body(default=None),
@router.delete("/geo/zones/{zone_id}")
def geo_zone_delete(zone_id: str, body: dict = Body(default=None),
- session: Session = Depends(require_session), application: str = None):
+ session: Session = Depends(require_session)):
"""Delete exactly one table-scoped Zone; record values are never mutated here."""
body = body if isinstance(body, dict) else {}
- from routes_customers import _route_application_body
- _route_application_body(body, application)
- application = _zone_application(session, body.get("tableKey"), application, write=True)
table_key, _fields, _pids, _rows = _zone_context(session, body.get("tableKey"))
- _zone_subject(session, table_key, zone_id, application)
+ _zone_subject(session, table_key, zone_id)
from core import route_system
- if not route_system.delete_zone(session.runtime, zone_id, table_key=table_key, application=application):
+ if not route_system.delete_zone(session.runtime, zone_id, table_key=table_key):
raise err(404, "unknown_zone", "no Zone with that id")
return {"deleted": str(zone_id)}
diff --git a/api/routes_grid.py b/api/routes_grid.py
index 5918779d115f9517a2fd8466628849bed1855c29..c2566480e528e58372c37091ee8f911ec7d71c9b 100644
--- a/api/routes_grid.py
+++ b/api/routes_grid.py
@@ -1816,7 +1816,7 @@ def _materialise_recurrence_cells(session, scope, events, results, fields):
# admin route over the CALLING TENANT, and a scheduler must call it once per tenant.
-def refresh_recurrence_columns(st, scope, today=None, defn=None, by=None):
+def refresh_recurrence_columns(st, scope, today=None, defn=None):
"""R2's roll-forward for ONE database: `{field_key: rows_written}`; `{}` when nothing moved.
Callable WITHOUT an HTTP request — `st` is a store handle (`session.runtime`) and `scope` a
@@ -1880,8 +1880,7 @@ def refresh_recurrence_columns(st, scope, today=None, defn=None, by=None):
counts[key] = counts.get(key, 0) + 1
if not updates:
return {}
- # S76-T32: `by` is the signed-in admin who asked; a scheduler passes None and stamps no person.
- written = user_tables.patch_many_cells(scope, updates, st=st, by=by)
+ written = user_tables.patch_many_cells(scope, updates, st=st)
if not written:
return {}
if written != len(updates):
@@ -1892,7 +1891,7 @@ def refresh_recurrence_columns(st, scope, today=None, defn=None, by=None):
return counts
-def refresh_recurrence_tenant(st, today=None, by=None):
+def refresh_recurrence_tenant(st, today=None):
"""Every user database in ONE tenant: `{table_key: {field_key: rows_written}}`.
ONE `all_tables` read for the whole walk, with each definition LENT onward — see
@@ -1904,7 +1903,7 @@ def refresh_recurrence_tenant(st, today=None, by=None):
today = str(today or time.strftime("%Y-%m-%d"))
out = {}
for scope, defn in (user_tables.all_tables(st=st) or {}).items():
- counts = refresh_recurrence_columns(st, scope, today=today, defn=defn, by=by)
+ counts = refresh_recurrence_columns(st, scope, today=today, defn=defn)
if counts:
out[str(scope)] = counts
return out
@@ -1930,7 +1929,7 @@ def recurrence_refresh(session: Session = Depends(require_session)):
raise err(503, "store_unavailable",
"the tenant store is unavailable. Nothing was refreshed")
today = time.strftime("%Y-%m-%d")
- tables = refresh_recurrence_tenant(session.runtime, today=today, by=getattr(session, "uname", None))
+ tables = refresh_recurrence_tenant(session.runtime, today=today)
return {"today": today, "tables": tables,
"cells": sum(sum(counts.values()) for counts in tables.values()),
"columns": sum(len(counts) for counts in tables.values())}
diff --git a/api/routes_nav.py b/api/routes_nav.py
index 1e44da884199676c99a5836a4fc5d878b8822878..b95d8dc1e3d425b0fc6037501e295799c23c4b23 100644
--- a/api/routes_nav.py
+++ b/api/routes_nav.py
@@ -28,7 +28,6 @@ router = APIRouter(prefix="/api/v1")
_NAV_PREFS_KEY = "nav_prefs"
_MAX_NAV_FOLDERS = 16
-
#: WAVE 19 (R8 / contract C1): the database's NAME and ICON overrides.
#:
#: ⚠ TENANT-WIDE, which is the whole difference from `nav_prefs` above and the reason it is a
diff --git a/api/routes_odoo_tables.py b/api/routes_odoo_tables.py
index d897219cae2cc8f52a9f0e473ff99f51af01557a..ca19e58647fb0e9023ddd830979742dc5779b189 100644
--- a/api/routes_odoo_tables.py
+++ b/api/routes_odoo_tables.py
@@ -4532,12 +4532,6 @@ def mirror_stamp(spec, cur=None, table_key="", rt=None, defn=None):
return ""
except Exception: # noqa: BLE001
return ""
- if str(table_key).startswith("ut_amzn_"):
- try:
- from external_freshness import amazon_sync_stamp
- return str(amazon_sync_stamp(cur, table_key) or "")[:10]
- except Exception:
- return ""
ident = str(spec.get("id") or "")
alias = ident.split(".", 1)[0] if "." in ident else ""
table = str((spec.get("tables") or {}).get(alias) or spec.get("table")
diff --git a/api/routes_query.py b/api/routes_query.py
index b9583d27e59612196fbff5ea32e34a7115e6b1db..32192f903147e57a0057f30668efd0e07fd27238 100644
--- a/api/routes_query.py
+++ b/api/routes_query.py
@@ -124,6 +124,18 @@ QUERY_NO_SOURCE_MATCHED = (
"None of the databases you can read cover that question. Pick one from the list, "
"or ask about a database you can open."
)
+# A fresh turn made only of these words names no data subject, so it is conversation (D-2673).
+_CHAT_WORDS = (
+ "hello hi hey hiya good morning afternoon evening thanks thank please ok okay yes no yeah yep sure "
+ "cool great nice sorry bye goodbye cheers welcome i me you your yours we it its they them can could "
+ "would will should might have has had be am been being does doing done get got there here then "
+ "just also too so really still now hear see know help think say ask mean understand need want like "
+ "try talk chat explain database table field data workspace loopable assistant loopy app question answer"
+)
+CONVERSATION_PROMPT = (
+ "\nNo database is chosen for this turn and no tool is available. Reply in plain sentences with no "
+ "markdown, and never state a figure from data. If the user asks about their data, ask which database to use."
+)
QUERY_DRAFT_ADMIN = "This database has no approved fields yet. Pick the ones this answer should use and they will be approved for everyone."
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."
@@ -1023,6 +1035,8 @@ 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("conversation"):
+ tools = []
if turn.get("admittedTools"):
tools = [tool for tool in tools if tool["function"]["name"] in set(turn["admittedTools"])]
if turn.get("memoryOnly"):
@@ -1033,6 +1047,11 @@ def _call_model(question, snapshot, model=MODEL_AUTO, chat=None, history=None, s
"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("conversation"):
+ names = turn.get("conversationSources")
+ prompt += CONVERSATION_PROMPT + ("" if names is None else
+ " The databases this user can open: " + "; ".join(names) + "."
+ if names else " This user can open no database yet.")
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. "
@@ -2013,8 +2032,13 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
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 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": []}
+ # D-2673: an app turn with no data subject reaches the model with no tools, never the no-source refusal.
+ conversation = (door == "app" and dock is None and replay is None and not also_as
+ and _conversation(question, routed))
+ if conversation:
+ routed = {"database": "", "label": "", "reason": "", "auto": True, "alternatives": []}
target = routed["database"]
- 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
+ route_refusal = (None if conversation or 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 plan mirrors from schema. Dock turns read through permissioned tools.
@@ -2064,6 +2088,9 @@ def _submit_active(body, session, question, selected_model, context_hint, dock,
turn["admittedTools"] = sorted(admitted)
if memory_only:
turn["memoryOnly"] = True
+ if conversation:
+ turn["conversation"] = True
+ turn["conversationSources"] = _readable_labels(session)
turn["memoryCompanyRequested"] = assistant_memory.company_requested(question)
if snapshot is not None:
turn["memorySources"] = [{"database": snapshot["database"],
@@ -2382,48 +2409,7 @@ def _recorded_artifacts(session):
yield from assistant_artifacts._rows(session.runtime, h, index)
-def _artifact_can_edit(session, item, *, query_views=None):
- """Resolve current item authority before offering or executing an Artifact mutation."""
- try:
- session.require("analyst")
- if not session.uname or item.get("status") == "deleted":
- return False
- kind, ref = item["kind"], item.get("ref")
- owner = assistant_log._hash(session.runtime, session.uname)
- legacy_query = kind == "query" and item["id"] == "query:" + str(ref)
- # Every caller already resolved the row through this principal's catalog or Query namespace.
- if not legacy_query and assistant_artifacts._seq(owner, item["id"]) is None:
- return False
- if kind == "query":
- if query_views is not None:
- # The list already admitted these sources in its current permission batch.
- return ref in query_views
- _artifact_or_404(session, ref)
- return True
- if kind == "view":
- from routes_starred import _find_view
- from routes_starred import _home_view_row
- found = _find_view(session, ref, item["toolCall"]["args"].get("database") or "")
- return bool(found and _home_view_row(session, found)["capabilities"]["edit"])
- if kind == "sheet":
- from core import sheets
- import routes_sheet
- book = sheets.get_workbook(session.runtime, ref)
- routes_sheet._require_reader(session, book)
- return routes_sheet._role_on_workbook(session, book) in ("owner", "edit")
- if kind == "schedule":
- import schedules
- schedule = schedules.get(session.runtime, ref)
- return bool(schedule and schedule.get("owner") == session.uname and not schedule.get("system"))
- if kind == "snapshot":
- _snapshot_content(session, item)
- return True
- return kind in ("report", "run", "pdf", "xlsx", "image")
- except Exception:
- return False
-
-
-def _artifact_actions(item, session=None, *, query_views=None):
+def _artifact_actions(item):
actions = ["run"]
if item["kind"] in ("sheet", "view", "query") and item.get("ref"):
actions.insert(0, "open")
@@ -2431,15 +2417,6 @@ def _artifact_actions(item, session=None, *, query_views=None):
actions.extend(["resume" if item.get("status") == "paused" else "pause", "delete"])
elif item["kind"] in ("view", "query") and item.get("ref"):
actions.append("delete")
- if session is not None:
- # Extracted projections without an item authority resolver keep mutation actions closed.
- can_edit = globals().get("_artifact_can_edit")
- if callable(can_edit) and can_edit(session, item, query_views=query_views):
- actions.append("rename")
- if "delete" not in actions:
- actions.append("delete")
- else:
- actions = [action for action in actions if action not in ("delete", "pause", "resume")]
return actions
@@ -2481,7 +2458,7 @@ def _artifact_rows(session, views_only=False):
"database": view["source"]["database"], "question": view["question"]}}})
for row in rows:
row["title"] = _no_dashes(row["title"])[:200]
- row["actions"] = _artifact_actions(row, session, query_views=by_ref)
+ row["actions"] = _artifact_actions(row)
return sorted(rows, key=lambda row: (row["createdAt"], row["id"]), reverse=True)
@@ -2519,7 +2496,7 @@ def _artifact_item(session, item_id):
if stored and stored["status"] != "deleted":
if stored["kind"] == "query":
_artifact_or_404(session, stored["ref"])
- stored["actions"] = _artifact_actions(stored, session)
+ stored["actions"] = _artifact_actions(stored)
return stored
item = next((row for row in _artifact_rows(session) if row["id"] == item_id), None)
if item is None:
@@ -2637,23 +2614,18 @@ def resume_artifact(id: str, session: Session = Depends(require_session)):
def delete_artifact(id: str, session: Session = Depends(require_session)):
import agent_runtime
item = _artifact_item(session, id)
- if not _artifact_can_edit(session, item):
- raise err(403, "artifact_read_only", "Your current rights do not allow deleting this artifact.")
if item["kind"] == "schedule":
name, args = "schedule_delete", {"id": item["ref"]}
elif item["kind"] == "view":
- name, args = "artifact_entry_delete", {"id": item["id"]}
+ name, args = "view_delete", {"database": item["toolCall"]["args"].get("database"), "view_id": item["ref"]}
elif item["kind"] == "query":
name, args = "query_view_delete", {"qid": item["ref"]}
- elif item["kind"] in ("sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"):
- name, args = "artifact_entry_delete", {"id": item["id"]}
else:
raise err(400, "not_deletable", "This artifact cannot be deleted here.")
pending = agent_runtime._pending(session, "app", name, args)
- if item["kind"] in ("query", "schedule", "view", "sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"):
+ if item["kind"] in ("query", "schedule"):
# The artifact carries the name the reader knows; a schedule id or a Query id is not one.
- noun = ("Query answer" if item["kind"] == "query" else item["kind"]
- if item["kind"] in ("schedule", "view") else "artifact")
+ noun = "Query answer" if item["kind"] == "query" else "schedule"
pending["summary"] = f"Remove {noun} {_no_dashes(item['title']).rstrip('. ')}."
def name_request(raw):
current = copy.deepcopy(raw)
@@ -2667,79 +2639,6 @@ def delete_artifact(id: str, session: Session = Depends(require_session)):
return {"pendingDelete": pending}
-def _update_artifact_entry(session, item_id, patch):
- """Update only this principal's catalog entry while preserving its backing object."""
- owner = assistant_log._hash(session.runtime, session.uname)
- seq = assistant_artifacts._seq(owner, item_id)
- if seq is None:
- raise err(404, "unknown_artifact", "That artifact does not exist.")
- saved = {}
-
- def update(raw):
- saved.clear()
- doc = copy.deepcopy(raw or {})
- row = next((row for row in doc.get("items", []) if row.get("id") == item_id), None)
- if row is None or row.get("status") == "deleted":
- raise err(404, "unknown_artifact", "That artifact does not exist.")
- if not _artifact_can_edit(session, row):
- raise err(403, "artifact_read_only", "Your current rights do not allow changing this artifact.")
- row.update(patch)
- saved.update(row)
- return doc
-
- session.runtime.update(assistant_artifacts._chunk_key(owner, seq // assistant_artifacts.CHUNK_ITEMS),
- update, flush="sync")
- if not saved:
- raise err(503, "store_unavailable", "The artifact change could not be confirmed. Reload and try again.")
- saved["actions"] = _artifact_actions(saved, session)
- return saved
-
-
-@router.patch("/artifacts/{id}")
-def rename_artifact(id: str, body: dict = Body(default=None), session: Session = Depends(require_session)):
- """Rename an authorized Artifact's label without changing its generated content."""
- title = (body or {}).get("title")
- if not isinstance(title, str) or not title.strip() or len(title.strip()) > 200:
- raise err(400, "bad_title", "Use a title of 1 to 200 characters.")
- item = _artifact_item(session, id)
- if not _artifact_can_edit(session, item):
- raise err(403, "artifact_read_only", "Your current rights do not allow renaming this artifact.")
- title = title.strip()
- if item["kind"] == "query":
- if len(title) > 60 or title != " ".join(title.split()):
- raise err(400, "bad_title", "Use a title of at most 60 characters with single spaces.")
- title = rename_query(item["ref"], {"name": title}, session)["name"]
- if id.startswith("query:"):
- return {"artifact": _artifact_item(session, id)}
- return {"artifact": _update_artifact_entry(session, id, {"title": title})}
-
-
-def _delete_artifact_entry(session, args):
- item = _artifact_item(session, args["id"])
- if item["kind"] == "view":
- if not _artifact_can_edit(session, item):
- raise err(403, "artifact_read_only", "Your current rights do not allow deleting this artifact.")
- from routes_starred import delete_home_view
- delete_home_view(item["toolCall"]["args"]["database"], item["ref"], None, session)
- assistant_artifacts.set_status(session.runtime, session.uname, item["id"], "deleted")
- return {"deleted": item["id"]}
- if item["kind"] not in ("sheet", "report", "run", "pdf", "xlsx", "image", "snapshot"):
- raise err(400, "not_deletable", "This artifact cannot be deleted through this action.")
- _update_artifact_entry(session, item["id"], {"status": "deleted"})
- return {"deleted": item["id"]}
-
-
-def _register_artifact_entry_delete():
- import agent_tools
- agent_tools.register("artifact_entry_delete", {
- "type": "object", "description": "Remove your Artifact entry after confirmation while retaining its backing data.",
- "properties": {"id": {"type": "string"}}, "required": ["id"], "additionalProperties": False,
- }, _delete_artifact_entry, effect="delete")
-
-
-_register_artifact_entry_delete()
-
-
def _settle_artifact_delete(session, call):
kind = {"schedule_delete": "schedule", "view_delete": "view", "query_view_delete": "query"}.get(call["name"])
if kind is None:
@@ -2872,6 +2771,32 @@ def _route_candidates(session):
return candidates
+def _readable_labels(session):
+ """The names of the databases this session may open: the picker's set, no record read.
+
+ None when the status wall cannot be read, so a greeting still gets its reply."""
+ from harness import semantic as sem
+ try:
+ projection = getattr(session.runtime, "get_projection", None)
+ definitions = (projection("user_tables", drop=("rows",)) or {}) if projection else {}
+ topics = {row.get("grid"): row.get("label") for row in sem.topics().values()}
+ statuses = assistant_source_status(session, None)
+ except Exception: # noqa: BLE001
+ return None
+ return sorted({_said(status.get("label") or (definitions.get(database) or {}).get("label")
+ or topics.get(database) or database.removeprefix("ut_").replace("_", " ")) or database
+ for database, status in statuses.items()
+ if status.get("permitted")})
+
+
+def _conversation(question, routed):
+ """True when an auto route found no database or the question holds no data word."""
+ from harness import semantic as sem
+ return bool(routed.get("auto")) and (
+ not routed.get("database")
+ or not set(sem._route_tokens(question)) - set(sem._route_tokens(_CHAT_WORDS)))
+
+
def _route(session, question):
from harness import semantic as sem
candidates = _route_candidates(session)
@@ -3438,6 +3363,10 @@ def governed_query(body: dict = Body(default=None),
"database": "", "label": "", "reason": "", "auto": False, "alternatives": []}}
routed = _route(session, question) if not database else {
"database": database, "label": "", "reason": "", "auto": False, "alternatives": []}
+ if _conversation(question, routed):
+ # D-2673: a greeting or a question no database covers continues to chat, never a Clarify card.
+ return {"status": "continue_chat", "routedTo": {
+ "database": "", "label": "", "reason": "", "auto": False, "alternatives": []}}
database = routed["database"]
if database:
_semantic_authorize(session, database, require_answerable=not routed["auto"])
diff --git a/api/routes_sheet.py b/api/routes_sheet.py
index 2482f7f75aa270e379d644e7c9b077afcec33462..f5bdff298aad4a3c062d4c34c6e5000bdd68a6d1 100644
--- a/api/routes_sheet.py
+++ b/api/routes_sheet.py
@@ -1412,7 +1412,7 @@ _MISSING_CODES = ("workbook_missing", "folder_missing", "tab_missing", "unknown_
#: it, which is what 403 means and is the only status a client can act on.
#:
#: `workbook_read_only` is a VIEWER at a write door; `workbook_owner_only` is a non-owner at a
-#: door C5 reserves for the owner (the two share doors). Two codes rather than one
+#: door C5 reserves for the owner (the two share doors, and DELETE). Two codes rather than one
#: because they send the reader to two different places: one asks for edit access, the other
#: cannot be granted at all.
_FORBIDDEN_CODES = ("workbook_read_only", "workbook_owner_only", "tenant_mismatch", "sheet_actor_required")
@@ -3443,10 +3443,18 @@ def duplicate_sheet_tab(workbook_id: str, tab: str, body: dict = Body(default=No
@router.delete("/sheets/{workbook_id}")
def drop_sheet(workbook_id: str, session: Session = Depends(require_session)):
- """Delete a workbook through its current edit right under R26."""
+ """Delete a workbook. THE OWNER's door, and an editor is refused by name (C5).
+
+ ⛔ AN `edit` GRANT IS PERMISSION TO CHANGE THE CONTENT, NOT TO DESTROY THE OBJECT, and the
+ fail-closed reading is the one that ships: an editor who deletes the owner's workbook has
+ taken it from everybody it was shared with, and nothing in this system can put it back. The
+ refusal is `workbook_owner_only` rather than `workbook_read_only` because the sentences send
+ the reader to two different places, and telling an editor their workbook is read only would be
+ flatly false.
+ """
from core import sheets
try:
- _require_editor(session, sheets.get_workbook(_store(session), workbook_id))
+ _require_owner(session, sheets.get_workbook(_store(session), workbook_id))
removed = sheets.delete_workbook(_store(session), workbook_id)
except sheets.SheetRefusal as exc:
raise _refuse(exc)
diff --git a/api/routes_starred.py b/api/routes_starred.py
index 790c9a30c5cf267ca2e9b54f0fb85062e5119ae4..e023040953e08b22064f590570434a8c4e0a4f97 100644
--- a/api/routes_starred.py
+++ b/api/routes_starred.py
@@ -34,7 +34,7 @@ import json
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
-from fastapi import APIRouter, Body, Depends, Request
+from fastapi import APIRouter, Body, Depends
import routes_nav
from deps import Session, err, require_session
@@ -304,7 +304,7 @@ def _refresh_one(session, cache, key):
return (order, docs, unread)
-def _scan_starred_views(session, keys=None, cache=None, include=None, with_rights=False):
+def _scan_starred_views(session, keys=None, cache=None, include=None):
"""`(rows, unread)` — every view this caller has starred, newest-worked database first.
A row is `{"id", "database", "name", "config"}`. ⚠ `config` is carried so the COUNTS route does
@@ -367,12 +367,11 @@ def _scan_starred_views(session, keys=None, cache=None, include=None, with_right
doc = session.runtime.get_projection(ws_key, drop=("overlays", "fields")) or {}
docs[key] = doc
- found, owners = {}, {}
+ found = {}
own = doc.get(session.uname)
for vid, view in ((own.get("views") or {}) if isinstance(own, dict) else {}).items():
if isinstance(view, dict):
found[str(vid)] = view
- owners[str(vid)] = session.uname
for vid in pending:
owner = granted.get(vid)
@@ -392,17 +391,12 @@ def _scan_starred_views(session, keys=None, cache=None, include=None, with_right
break
if isinstance(view, dict):
found.setdefault(vid, view)
- owners.setdefault(vid, owner if owner else candidate_owner)
resolved.add(vid)
for vid, view in found.items():
cfg = view.get("config") or {}
if (include(view) if include else cfg.get("important") is True):
- row = {"id": vid, "database": key,
- "name": str(view.get("name") or vid)[:120], "config": cfg}
- if with_rights:
- row.update(routes_nav._home_view_row(
- session, (key, ws_key, owners[vid], {**view, "id": vid}, None)))
- out.append(row)
+ out.append({"id": vid, "database": key,
+ "name": str(view.get("name") or vid)[:120], "config": cfg})
return out, unread
@@ -522,82 +516,15 @@ def _payload(session, keys=None, cache=None):
@router.get("/nav/views")
def nav_views(session: Session = Depends(require_session)):
- """Project readable saved View names and their current item rights."""
- rows, unread = _scan_starred_views(session, include=lambda view: True, with_rights=True)
- return {"views": [{key: row[key] for key in ("database", "id", "name", "capabilities")}
- for row in rows], "unread": unread}
-
-
-# S76-T17: the Home Views section's rename and delete live beside its GET, never in routes_nav (R7).
-
-def _home_view_row(session, found):
- """Project only a saved View's identity, name and current edit right."""
- database, _, owner, view, _ = found
- editable = (view.get("id") != SYSTEM_VIEW_ID and view.get("kind") != "system"
- and _may_star_view(session, owner, view))
- return {"database": database, "id": view["id"], "name": str(view.get("name") or view["id"])[:120],
- "capabilities": {"edit": bool(editable), "delete": bool(editable)}}
-
-
-def _editable_home_view(session, database, view_id):
- found = _find_view(session, view_id, database)
- if found is None:
- raise err(404, "view_not_found", "That saved View is no longer available.")
- if not _home_view_row(session, found)["capabilities"]["edit"]:
- raise err(403, "view_read_only", "Your current rights do not allow changes to this View.")
- return found
-
-
-@router.patch("/nav/views/{database}/{view_id}")
-def rename_home_view(database: str, view_id: str, request: Request, body: dict = Body(default=None),
- session: Session = Depends(require_session)):
- """Rename the canonical saved View without reading or returning database records."""
- from core import table_store, view_audit, write_execution
- from routes_tables import _audit_origin
-
- name = (body or {}).get("name")
- if not isinstance(name, str) or not name.strip() or len(name.strip()) > 120:
- raise err(400, "bad_name", "Use a View name of 1 to 120 characters.")
- found = _editable_home_view(session, database, view_id)
- key, workspace, owner, _, cache = found
- views = table_store.make(workspace, st=session.runtime)
- saved, changes = {}, {}
-
- def rename(data, audit):
- saved.clear()
- current = ((data.get(owner) or {}).get("views") or {}).get(view_id)
- if not isinstance(current, dict):
- raise err(404, "view_not_found", "That saved View is no longer available.")
- if not _may_star_view(session, owner, current):
- raise err(403, "view_read_only", "Your current rights do not allow changes to this View.")
- names = [candidate.get("name") for who, personal in data.items()
- if who not in table_store.RESERVED_MEMBERS and isinstance(personal, dict)
- for candidate_id, candidate in (personal.get("views") or {}).items()
- if candidate_id != view_id and isinstance(candidate, dict)]
- updated = {**current, "name": table_store._unique_name(name.strip(), names),
- "updatedAt": write_execution.utcnow().isoformat()} # S76-T37
- changes.update(before=view_audit.summary(current), after=view_audit.summary(updated))
- data[owner]["views"][view_id] = updated
- audit(action=view_audit.derive_action(current, updated), owner=owner, view_id=view_id,
- actor=session.uname, origin=_audit_origin(request), **changes)
- saved.update(updated)
- return data
-
- views._audited_update(rename)
- views.log_view_activity(view_id, "saved", by=session.uname, via=_audit_origin(request), **changes)
- return {"view": _home_view_row(session, (key, workspace, owner, saved, cache))}
-
+ """S76-T17: every saved View this caller may open, as names only, for the module home.
-@router.delete("/nav/views/{database}/{view_id}")
-def delete_home_view(database: str, view_id: str, request: Request, session: Session = Depends(require_session)):
- """Move the canonical saved View to trash through its own edit right."""
- from core import table_store
- from routes_tables import _audit_origin
-
- _, workspace, owner, _, _ = _editable_home_view(session, database, view_id)
- table_store.make(workspace, st=session.runtime).delete_view(
- owner, view_id, actor=session.uname, origin=_audit_origin(request))
- return {"deleted": view_id}
+ Read-only: rename and delete stay closed (capabilities false) until their governed doors exist
+ (D-9736). The config never goes on the wire, for `_starred_views`' reason.
+ """
+ rows, unread = _scan_starred_views(session, include=lambda view: True)
+ return {"views": [{"database": r["database"], "id": r["id"], "name": r["name"],
+ "capabilities": {"edit": False, "delete": False}} for r in rows],
+ "unread": unread}
@router.get("/starred")
diff --git a/api/routes_tables.py b/api/routes_tables.py
index 74248dfc69f2adb4489306911f44ae60088f3951..47bb44268f63dbf628fd9dec2b16f42bce484fe5 100644
--- a/api/routes_tables.py
+++ b/api/routes_tables.py
@@ -2957,13 +2957,9 @@ def add_row(table_key: str, body: dict = Body(default=None),
if ut.ZONE_FIELD_KEY in values or "zone" in values:
raise err(400, "zone_membership_read_only",
"Zone membership is worked out from the record's current location")
- # S76-T32: an undo restores a deleted record's retained server facts only when it says so.
- restore = (body or {}).get("restore", False)
- if not isinstance(restore, bool):
- raise err(400, "bad_restore", "restore must be true or false")
try:
rid = ut.add_row(table_key, values, session.uname, st=session.runtime,
- rid=(body or {}).get("rid"), restore=restore, via=via)
+ rid=(body or {}).get("rid"), via=via)
except ValueError as exc:
# A core value rule (negative policy, link condition, server-owned cell) names its reason.
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the row was refused")
@@ -2986,23 +2982,7 @@ def add_row(table_key: str, body: dict = Body(default=None),
_refresh_relations(session)
from routes_alerts import after_write
after_write(session, table_key)
- return {"rid": rid, "pid": int(rid), "values": _added_row_values(session, table_key, rid)}
-
-
-def _added_row_values(session, table_key, rid):
- """The stored row as this session may read it: generated cells included, hidden fields and
- server-only keys (`_rowAudit`, `_created`) never."""
- import core.perm_scope as perm_scope
- try:
- entry = _table_entry(session.runtime, table_key) or {}
- except Exception:
- return {} # the row is saved; a failed read-back must not report a failed write
- row = (entry.get("rows") or {}).get(str(rid))
- if not isinstance(row, dict):
- return {}
- hidden = _ut_hidden(session, table_key, entry.get("fields") or [], st=session.runtime)
- return perm_scope.strip_row({key: value for key, value in row.items()
- if not str(key).startswith("_")}, hidden)
+ return {"rid": rid, "pid": int(rid)}
@router.post("/tables/{table_key}/rows/import", status_code=201)
@@ -3061,10 +3041,6 @@ def import_rows(table_key: str, body: dict = Body(default=None),
raise err(400, "bad_value", f"row {index + 1}: {why}. Nothing was imported")
try:
made = ut.add_rows(table_key, rows_in, session.uname, st=session.runtime)
- except ValueError as exc:
- # S76-T33: a Link condition or value rule refuses the batch with its own code and reason.
- raise err(400, getattr(exc, "code", "bad_value"),
- (str(exc)[:280].rstrip(". ") or "a value was refused") + ". Nothing was imported")
except Exception:
raise err(503, "store_unavailable", "nothing was imported. The store refused")
if made is None:
@@ -3151,33 +3127,6 @@ def _admit_if_sources(session, table_key, body, definition, fkey=''):
raise err(403 if exc.code == 'if_source_forbidden' else 400, exc.code, str(exc))
-def _admit_link_selection(session, body):
- """S76-T33: a Link condition may name only target fields this session can read."""
- raw = body if isinstance(body, dict) else {}
- bag = raw.get("link")
- if not isinstance(bag, dict) or not isinstance(bag.get("selectionFilter"), dict):
- return
- target = str(bag.get("table") or "")
- if not target.startswith(_ut().KEY_PREFIX):
- return # a registry target is checked in core, which fails closed
- import core.perm_scope as perm_scope
- if not perm_scope.may_read(session.user, target, st=session.runtime):
- raise err(403, "link_selection_forbidden",
- "You cannot read the linked database, so its records cannot set a condition.")
- named, stack = set(), list(bag["selectionFilter"].get("nodes") or [])
- while stack:
- node = stack.pop()
- if not isinstance(node, dict):
- continue
- stack.extend(node.get("children") or [])
- rhs = node.get("rhs") if isinstance(node.get("rhs"), dict) else {}
- named.update(ref for ref in (node.get("colId"), rhs.get("colId")) if isinstance(ref, str) and ref)
- fields = (_table_entry(session.runtime, target) or {}).get("fields") or []
- if named & set(_ut_hidden(session, target, fields, st=session.runtime) or ()):
- raise err(403, "link_selection_forbidden",
- "The link condition names a field you cannot read in the linked database.")
-
-
@router.post("/tables/{table_key}/fields", status_code=201)
@_c8_write
def add_field(table_key: str, body: dict = Body(default=None),
@@ -3185,7 +3134,6 @@ def add_field(table_key: str, body: dict = Body(default=None),
_managed_or_refuse(session, table_key, mutation=True)
definition = _field_or_refuse(session, table_key)
_admit_if_sources(session, table_key, body, definition)
- _admit_link_selection(session, body)
ut = _ut()
from routes_grid import govern_date_recurrence
# Only recurrence admission needs the merged workspace. Plain creates need no row audience.
@@ -3321,7 +3269,6 @@ def patch_field(table_key: str, fkey: str, body: dict = Body(default=None),
_managed_or_refuse(session, table_key, mutation=True)
definition = _field_or_refuse(session, table_key, fkey)
_admit_if_sources(session, table_key, body, definition, fkey)
- _admit_link_selection(session, body)
ut = _ut()
body = body or {}
from routes_grid import govern_date_recurrence
@@ -3655,12 +3602,6 @@ def patch_row(table_key: str, pid: int, body: dict = Body(default=None),
except ValueError as exc:
# A core value rule refused the cell before anything was stored. Name its reason (C4).
raise err(400, getattr(exc, "code", "bad_value"), str(exc)[:300] or "the edit was refused")
- # S76-T29: `overlay_patch` records a value rule's refusal instead of raising; answer it the same way.
- for _refusal in getattr(ctx.out, "refusals", None) or ():
- if _refusal.get("event") == "overlay_patch" and _refusal.get("code") not in (
- "cell_write_refused", "row_outside_audience", "bad_row_id"):
- raise err(400, _refusal.get("code") or "bad_value",
- _refusal.get("message") or "the edit was refused")
# ⚠ THE READ-BACK IS THE DEFINITION ROW, AND ON A `ut_` SCOPE THAT IS THE WHOLE OF IT.
#
# ⛔ CORRECTED, wave-29 T22 (owner item 2a): this note used to say "THE READ-BACK SPANS BOTH
diff --git a/api/schedules.py b/api/schedules.py
index 831ef11de93a1a388279471b6aff2e57f0c3cf03..a0ddfe8bd32e796358c97346e21679d257e145d2 100644
--- a/api/schedules.py
+++ b/api/schedules.py
@@ -224,7 +224,7 @@ def create(rt, owner, *, cron=None, tz, action, label, system=False, once_at=Non
item = {"id": schedule_id, "owner": owner, "label": label,
"cron": None if once or trigger else " ".join(cron.split()),
"tz": tz, "action": action, "paused": False, "nextRunAt": next_stamp,
- "createdAt": _iso(now), "updatedAt": _iso(now), "lastFiredMinute": None, "lastFiredAt": None,
+ "createdAt": _iso(now), "lastFiredMinute": None, "lastFiredAt": None,
"lastOutcome": None, "runs": [], "system": bool(system)}
if once:
item.update(once=True, onceAt=next_stamp)
@@ -261,7 +261,6 @@ def _set_paused(rt, schedule_id, paused):
or _utc(instant) <= now):
raise ValueError("That reminder already ran.")
item["paused"] = paused
- item["updatedAt"] = _iso(now) # S76-T37: pausing or resuming is an update
if not paused and item.get("trigger") == "sync" and item.get("syncFallback"):
item["nextRunAt"] = _iso(now + dt.timedelta(hours=1))
if not paused and not item.get("once") and item.get("trigger") != "sync":
diff --git a/api/tool_groups/sheet.py b/api/tool_groups/sheet.py
index e7bca114ab9292bc3176c49eef3db87e9a7debec..a498c0a6b9aa40741cc8d7596f0c692a2c8a3327 100644
--- a/api/tool_groups/sheet.py
+++ b/api/tool_groups/sheet.py
@@ -49,13 +49,6 @@ def _workbook_view(ctx, args):
"editable": not bool(reason), "reason": reason, "sheets": tabs}}
-def _object_available(operation):
- """Promise only object actions implemented by the compatibility dispatcher."""
- from core import sheet_compat
- return (callable(getattr(sheet_compat, "dispatch_object_operation", None))
- and operation in sheet_compat.OBJECT_OPERATIONS)
-
-
GROUP = {
"name": "sheet", "title": "Sheets",
"guide": ("Read and change workbooks, tabs, cells, styles and charts. "
@@ -71,8 +64,6 @@ for name, actions in external_tools._SHEET_OBJECT_ACTIONS.items():
GROUP["actions"][name.removesuffix("_object") + "." + action] = legacy_action(
name, action=action, read=action in external_tools._OBJECT_READ_ACTIONS[name],
destructive=action in {"delete", "clear"})
- operation = name.removesuffix("_object") + "." + action
- GROUP["actions"][operation]["available"] = lambda operation=operation: _object_available(operation)
GROUP["actions"]["read_batch"] = legacy_action("validated_batch", read=True)
GROUP["actions"]["write_batch"] = legacy_action("validated_batch", read=False, destructive=True)
GROUP["actions"]["workbook.view"] = {
@@ -83,22 +74,6 @@ GROUP["actions"]["workbook.view"] = {
"required": ["workbook_id"], "additionalProperties": False},
}
GROUP["guide"] += " Use workbook.view with workbook_id to open the workbook view."
-GROUP["guide"] += (
- " Use workbook.list to find readable workbook ids, names and revisions. "
- "Send action='list' in the action arguments, with page_size and cursor inside its arguments object. "
- "Follow next_cursor until it is null to read every workbook. "
- "Use workbook.get with action='get' and workbook_id, or put an exact case-insensitive name in arguments.name. "
- "A near name refuses with readable close names."
-)
-GROUP["actions"]["workbook.list"]["schema"]["properties"]["arguments"] = {
- "type": "object", "properties": {"cursor": {"type": "string"},
- "page_size": {"type": "integer", "minimum": 1}}, "additionalProperties": False,
-}
-GROUP["actions"]["workbook.get"]["schema"]["properties"]["arguments"] = {
- "type": "object", "properties": {"name": {"type": "string", "minLength": 1},
- "workbook_id": {"type": "string", "minLength": 1}, "id_or_name": {"type": "string", "minLength": 1}},
- "additionalProperties": False,
-}
GROUP["guide"] += ' Under MCP rule 9, ask "Do you want me to build a Sheet workbook in Loopable?".'
_BATCH_GUIDE = (
" A batch has 1 to 50 operations for one workbook. Use name and arguments for each operation. "
diff --git a/platform/core/external_tools.py b/platform/core/external_tools.py
index 530cde20712472b8a2fff0fae00d7fbde81df00e..5fffd1244b7b94613937d6a291bb8c8014bcc300 100644
--- a/platform/core/external_tools.py
+++ b/platform/core/external_tools.py
@@ -140,6 +140,46 @@ _QUERY_FILTER = {"oneOf": [
_object({"link": _STRING, "where": _query_filter_node(allow_link=False)},
("link", "where"), additionalProperties=False),
]}
+FILTER_NODE_REF = "#/$defs/filter_node"
+FILTER_NODE_EXAMPLE = {"conj": "and", "nodes": [
+ {"colId": "status", "op": "eq", "value": "open"},
+ {"conj": "or", "children": [{"colId": "amount", "op": "gt", "value": 100},
+ {"colId": "region", "op": "eq", "value": "West"}]},
+]}
+
+
+def _is_filter_node(value):
+ """Tell a published query filter node from any other schema."""
+ branches = value.get("oneOf") if isinstance(value, dict) and set(value) == {"oneOf"} else None
+ first = branches[0] if isinstance(branches, list) and branches and isinstance(branches[0], dict) else {}
+ properties = first.get("properties")
+ return isinstance(properties, dict) and "colId" in properties and "op" in properties
+
+
+def guide_schema(schema):
+ """Return a guide copy with each query filter node replaced by one reference, and whether any was."""
+ if _is_filter_node(schema):
+ return {"$ref": FILTER_NODE_REF}, True
+ if isinstance(schema, list):
+ pairs = [guide_schema(item) for item in schema]
+ return [item for item, _ in pairs], any(used for _, used in pairs)
+ if not isinstance(schema, dict):
+ return copy.deepcopy(schema), False
+ pairs = {key: guide_schema(child) for key, child in schema.items()}
+ return {key: item for key, (item, _) in pairs.items()}, any(used for _, used in pairs.values())
+
+
+def filter_node_guide():
+ """Return the one markdown section that defines the filter_node reference in a guide."""
+ node = {"oneOf": [guide_schema(branch)[0] for branch in _QUERY_FILTER_NODE["oneOf"]]}
+ return ("## filter_node\n\n"
+ "A filter_node is a condition {colId, op, ...}, a group {conj, children: 1 to 50 filter_node}, "
+ "or a link {link, where}.\n"
+ "Groups nest at most two deep inside one node. A link's where holds no link.\n"
+ "Example filter: `" + json.dumps(FILTER_NODE_EXAMPLE, ensure_ascii=True) + "`\n"
+ "```json\n" + json.dumps({"$defs": {"filter_node": node}}, ensure_ascii=True, indent=2) + "\n```")
+
+
_BINDING = _object({
"database": _STRING,
"aggregate": _object({"fn": _STRING, "field": _STRING, "metric_key": _STRING}),
diff --git a/platform/core/grid_events.py b/platform/core/grid_events.py
index 808023949f5f84d1080a3c5686b1cc5937de4138..ef535dd6a8e87b7171ae640aac966b290fd15bba 100644
--- a/platform/core/grid_events.py
+++ b/platform/core/grid_events.py
@@ -78,9 +78,7 @@ _FIELD_ECHO_PROPS = ('label', 'type', 'note', 'options', 'colorCodeOptions',
# echo while the route still answers 200 - so the reader sees the change
# land and then lose it. `showAs` is a DISPLAY mode, never an aggregate.
'showAs',
- 'recurrence', 'if',
- # S76-T28: '' , 0 and false are real defaults, so this key compares by type.
- 'defaultValue')
+ 'recurrence', 'if')
class StoreUnavailable(RuntimeError):
@@ -1103,13 +1101,6 @@ def _field_echo_equal(accepted, raw):
empty = ('', [], {})
for k in _FIELD_ECHO_PROPS:
a, b = accepted.get(k), raw.get(k) if isinstance(raw, dict) else None
- if k == 'defaultValue':
- # Absence, '', False and 0 render differently, so no empty-collapse and no 0 == False.
- have = (a is not None, type(a), a) # an explicit null is a clear, stored as absent
- sent = (b is not None, type(b), b)
- if have != sent:
- return False
- continue
if k == 'scope':
# 'global' and absent are the SAME rendering (an unscoped field) — the event may
# say 'global' explicitly while the stored def says it by omission.
@@ -2279,19 +2270,6 @@ def handle_one(event, ctx):
fmt = _ag2._clean_format(raw.get('format'), ftype)
if fmt:
field['format'] = fmt
- # S76-T28: explicit null clears a default; omission keeps it only from a same-type definition.
- if 'defaultValue' in raw:
- _default = raw.get('defaultValue')
- else:
- _prior_def = shared_prior if shared_field else (ws.get('fields') or {}).get(key)
- _default = (_prior_def.get('defaultValue') if isinstance(_prior_def, dict)
- and _prior_def.get('type') == ftype else None)
- if _default is not None:
- from core import user_tables as _ut_default
- if readonly or not _ut_default._default_value_valid(field, _default):
- return _refuse(ctx, 'bad_default_value',
- 'The default value does not fit this field type.', key)
- field['defaultValue'] = _default
else:
# ⛔ THE FALL-THROUGH, AND IT IS THE WIDEST OF THE EIGHT: the key is neither a base
# contract field (a note/format override) nor a `custom_`/`measure_` key, so there is
@@ -3684,31 +3662,20 @@ def handle_one(event, ctx):
if updates:
if _connector_cells:
# Source refreshes own source rows. Authored cells use the same overlay as REST.
- try:
- if choice_additions:
- updates = _connector_overlay.put_cells_and_choice_options(
- _history_table, pid, updates, choice_additions, st=ctx.table.st)
- else:
- updates = _connector_overlay.put_cells(
- _history_table, pid, updates, st=ctx.table.st)
- except ValueError as exc:
- # S76-T33: a registry Link condition refusal keeps its code and reason.
- return _folder_refuse(ctx, kind, getattr(exc, 'code', None) or 'bad_value',
- str(exc) or 'The edit was refused.', key=','.join(updates))
+ if choice_additions:
+ updates = _connector_overlay.put_cells_and_choice_options(
+ _history_table, pid, updates, choice_additions, st=ctx.table.st)
+ else:
+ updates = _connector_overlay.put_cells(
+ _history_table, pid, updates, st=ctx.table.st)
elif str(ctx.scope_key or '').startswith('ut_') and ctx.table is not None:
# User-table cells are collaborative record data. Views/layout remain personal,
# but record values live in the definition rows so Links, Rollups, automations,
# and every viewer observe one truth.
import core.user_tables as _ut_values
- try:
- _cells_taken = _ut_values.patch_cells(
+ if not _ut_values.patch_cells(
ctx.scope_key, pid, updates, st=ctx.table.st,
- by=ctx.by if ctx.by is not None else uname, via=ctx.via)
- except ValueError as exc:
- # S76-T29/T33: a core value rule (number policy, Link condition) names its reason.
- return _folder_refuse(ctx, kind, getattr(exc, 'code', None) or 'number_value_refused',
- str(exc) or 'The edit was refused.', key=','.join(updates))
- if not _cells_taken:
+ by=ctx.by if ctx.by is not None else uname, via=ctx.via):
updates = {}
refused = True
elif _store_of(ctx).available():
diff --git a/platform/core/sheet_compat.py b/platform/core/sheet_compat.py
index 3d4f1c792b1b9be9433bdeaf500fdff21a43701a..a30d704797250bf889ca03beac3d55195037a265 100644
--- a/platform/core/sheet_compat.py
+++ b/platform/core/sheet_compat.py
@@ -48,12 +48,6 @@ _FPA = ".agents/skills/refresh-fpa/SKILL.md"
# The evidence references are intentionally literal and machine-readable. Section 26 of the
# Sheet gate re-censuses the source operations and requires every token to land on one row here.
_OPERATIONS = (
- _cap("workbook.list", True, "List(cursor=None, page_size=100)",
- "Pages every readable workbook's id, name and revision through the existing workbook permission resolver.",
- ["aios-web/api/verify_sheet.py:section_s76_t47_workbook_discovery"]),
- _cap("workbook.get", True, "Get(workbook_id | name)",
- "Resolves a readable workbook by stable id or exact case-insensitive name, with readable close-name suggestions.",
- ["aios-web/api/verify_api.py:section_s76_t47_workbook_discovery"]),
_cap("workbooks.open", True, "Open(id_or_name, UpdateLinks=0, ReadOnly=False)",
"Looks up one existing workbook by stable id, then exact case-insensitive name.",
[f"{_SALES}:421", f"{_FPA}:153"]),
@@ -892,76 +886,6 @@ def execute(st, workbook_id, operation, arguments=None, *, actor="", actor_name=
return out
-OBJECT_OPERATIONS = frozenset({"workbook.list", "workbook.get"})
-
-
-def dispatch_object_operation(*, session, object_name, action, arguments):
- """Discover workbook identities through the same role resolver as the Sheet index."""
- import difflib
-
- operation = str(object_name) + "." + str(action)
- if operation not in OBJECT_OPERATIONS:
- raise CompatibilityRefusal("tool_capability_unsupported", "This Sheet action is not available yet.")
- require_supported(operation)
- session.require("sheets")
- options = arguments.get("arguments") or {}
- if not isinstance(options, dict):
- raise CompatibilityRefusal("tool_arguments_invalid", "Workbook lookup arguments must be an object.")
- st = session.runtime
- visible = sheets.project_shares(st, sheets.list_workbooks(st), session.uname, is_admin=session.admin)
- visible.sort(key=lambda row: str(row["id"]))
-
- def identity(row):
- return {"id": row["id"], "name": row["name"], "rev": row["rev"]}
-
- if action == "list":
- size = options.get("page_size", 100)
- if type(size) is not int or size < 1:
- raise CompatibilityRefusal("tool_arguments_invalid", "Workbook page_size must be a positive integer.")
- cursor = options.get("cursor")
- principal = [str(session.tenant), str(session.uname).casefold()]
- after = ""
- if cursor is not None:
- try:
- if not isinstance(cursor, str) or not cursor:
- raise ValueError("empty cursor")
- position = json.loads(base64.b64decode(cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True))
- if (not isinstance(position, dict) or position.get("principal") != principal
- or not isinstance(position.get("after"), str) or not position["after"]):
- raise ValueError("invalid cursor")
- after = position["after"]
- except (ValueError, TypeError, UnicodeError) as exc:
- raise CompatibilityRefusal("tool_arguments_invalid", "That workbook cursor is invalid. Start a new list.") from exc
- remaining = [row for row in visible if str(row["id"]) > after]
- page = remaining[:size]
- next_cursor = None
- if len(remaining) > len(page):
- next_cursor = base64.urlsafe_b64encode(json.dumps({
- "principal": principal, "after": str(page[-1]["id"])
- }, separators=(",", ":")).encode()).decode().rstrip("=")
- return {"workbooks": [identity(row) for row in page], "next_cursor": next_cursor, "total": len(visible)}
-
- target = arguments.get("workbook_id") or options.get("workbook_id") or options.get("name") or options.get("id_or_name")
- if not isinstance(target, str) or not target.strip():
- raise CompatibilityRefusal("tool_arguments_invalid", "Choose a workbook_id or an exact workbook name.")
- target = target.strip()
- matches = [row for row in visible if row["id"] == target]
- if not matches:
- matches = [row for row in visible if str(row["name"]).casefold() == target.casefold()]
- if len(matches) > 1:
- raise CompatibilityRefusal("workbook_unavailable", "More than one readable workbook has that exact name. Choose its workbook_id.")
- if matches:
- book = sheets.get_workbook(st, matches[0]["id"])
- if sheets.may_read_workbook(book, sheets.workbook_role(st, book, session.uname, is_admin=session.admin)):
- return {"workbook": identity(book)}
- names = {str(row["name"]).casefold(): str(row["name"]) for row in visible}
- close = difflib.get_close_matches(target.casefold(), list(names), n=5, cutoff=0.5)
- reason = "That workbook is not available to this account."
- if close:
- reason += " Close names: " + ", ".join(names[name] for name in close) + ". Use an exact name."
- raise CompatibilityRefusal("workbook_missing", reason)
-
-
def dispatch_validated_batch(*, runtime, operations, staging, dispatch, actor="", actor_name=""):
"""Stage native Sheet operations, then publish one workbook revision through its guarded writer."""
if not isinstance(operations, list) or not 1 <= len(operations) <= 50:
diff --git a/platform/core/table_store.py b/platform/core/table_store.py
index 8c2679a046ce3b6a223a0373f9ebf2bd0e1f584b..07838471e9568fa9f7072cb873aa59ced90e6bc0 100644
--- a/platform/core/table_store.py
+++ b/platform/core/table_store.py
@@ -1528,7 +1528,6 @@ class TableStore:
if k not in ('filters', 'filterConj', 'memberPids')},
}
def _up(data, audit):
- record['updatedAt'] = write_execution.utcnow().isoformat()
bucket = data.setdefault(ASSIGNED_KEY, {}).setdefault('views', {})
bucket.setdefault(who, {})[assignment_id] = record
# ⭐ W50-T25 — C3's `share` action. The audit `owner` is the SOURCE VIEW's owner,
@@ -1667,8 +1666,6 @@ class TableStore:
)
payload = dict(requested)
payload['name'] = _unique_name(payload.get('name'), names)
- # S76-T37: the server stamps every View update; a client-sent updatedAt is never kept.
- payload['updatedAt'] = write_execution.utcnow().isoformat()
accepted.clear()
accepted.update(payload)
ws = data.setdefault(username, {})
@@ -2011,7 +2008,6 @@ class TableStore:
payload = dict(entry.get('view') or {})
payload['id'] = vid
payload['name'] = _unique_name(payload.get('name'), names)
- payload['updatedAt'] = write_execution.utcnow().isoformat()
data.setdefault(owner, {}).setdefault('views', {})[vid] = payload
carried = entry.get('assignments')
if isinstance(carried, dict) and carried:
diff --git a/web/public/AIOS_DEPLOY_RECEIPT b/web/public/AIOS_DEPLOY_RECEIPT
index 19cbdd1460ed5cf554c87b5675830e1a72167c7f..84bb9578baf0618966cabb52696cb51904ac764e 100644
--- a/web/public/AIOS_DEPLOY_RECEIPT
+++ b/web/public/AIOS_DEPLOY_RECEIPT
@@ -1 +1 @@
-4e2ae47d2bd75a80fc43d8dbb57bf56676f6199ef1ceb9ad4cc0db78bd011355
+3860b2103007bea62cccf6249230c80ce9f6f5b35c01af56ed6ea30aa116dcee
diff --git a/web/s71_frontend_contracts.py b/web/s71_frontend_contracts.py
index 5116acd9a7c5303d96e39f87c1bfbb5b4d5650ef..f178f5fc2a58dbc2ddf84c30be70ac189efdc27a 100644
--- a/web/s71_frontend_contracts.py
+++ b/web/s71_frontend_contracts.py
@@ -64,53 +64,6 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
import json
from playwright.sync_api import sync_playwright
from verify_w45_data_applications import AppRoutingFixture
- from verify_catalog import s76_t09_fixture_record, s76_t09_template_registry
-
- class CatalogHostFixture(AppRoutingFixture):
- def __init__(self):
- super().__init__()
- self.catalog = s76_t09_fixture_record()
- self.catalog["pages"][3]["bindings"]["products"] = ["WF-1", "CS-2"]
- self.typed_cursors = []
- self.fields.extend([{"key": key, "label": key, "type": kind, "source": "odoo"}
- for key, kind in (("stock", "text"), ("list_price", "int"),
- ("category", "text"), ("description", "text"))])
- self.applications[0]["fieldMap"].update(sku="stock", price="list_price",
- category="category", description="description")
- for row in self.rows:
- row.update(stock="Mapped sku", list_price=19.975,
- category="Mapped category", description="Mapped description")
- self.original_workspace = __import__("copy").deepcopy(self.workspace)
-
- def route(self, route):
- from urllib.parse import urlsplit
- request = route.request
- path = urlsplit(request.url).path.removeprefix("/api/v1/")
- result = None
- if path == "typed/openapi.json":
- properties = {field["key"]: {"type": "number" if field["type"] == "int" else "string"}
- for field in self.fields}
- properties["pid"] = {"type": "integer"}
- result = {"components": {"schemas": {"Record_customer_data": {"properties": properties}}}}
- elif path == "typed/databases/customer_data/query":
- body = request.post_data_json
- self.typed_cursors.append(body.get("cursor"))
- if not self.rows:
- result = {"database": self.database, "fields": self.fields, "records": [],
- "page": {"returned": 0, "has_more": False, "next_cursor": None}}
- elif request.method == "GET" and path == "apps/app-fixture/catalogs":
- result = {"catalogs": [self.catalog] if self.catalog else [], "nextCursor": None}
- elif request.method == "GET" and path == "catalogs/catalog-six":
- result = {"catalog": self.catalog}
- elif request.method == "GET" and path == "catalogs/templates":
- result = s76_t09_template_registry()
- result["kinds"][3]["templates"][0]["slots"] = [
- "title", "body", "products", "price", "sku", "category", "description"]
- if result is None:
- return super().route(route)
- self.requests.append({"path": path, "method": request.method})
- route.fulfill(status=200, content_type="application/json", body=json.dumps(result))
-
out_dir.mkdir(parents=True, exist_ok=True)
evidence = {"checks": [], "controls": [], "errors": []}
def check(name, value):
@@ -123,16 +76,12 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=True)
try:
- cases = ['catalog', 'empty-source', 'mobile'] + (['settings-discriminator', 'route-listener', 'legacy-loader'] if negative_controls else [])
+ cases = ['catalog'] + (['settings-discriminator', 'route-listener', 'legacy-loader'] if negative_controls else [])
for case in cases:
- fixture = CatalogHostFixture()
- if case == 'empty-source':
- fixture.rows = []
- fixture.catalog = None
- fixture.applications[0]['capabilities']['edit'] = True
+ fixture = AppRoutingFixture()
fixture.legacy_unavailable = True
fixture.hold_registry = True
- context = browser.new_context(viewport={"width": 390 if case == 'mobile' else 1440, "height": 1000})
+ context = browser.new_context(viewport={"width": 1440, "height": 1000})
context.add_init_script("""window.catalogRouteListeners = [];
const ordinaryAdd = window.addEventListener;
window.addEventListener = function(type, ...args) {
@@ -141,7 +90,7 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
};""")
context.route('**/api/**', fixture.route)
applied = []
- if case in ('settings-discriminator', 'route-listener', 'legacy-loader'):
+ if case != 'catalog':
old, new = ('applicationTemplateSurface(resolvedApplication) !== "catalog"', 'true') if case == 'settings-discriminator' \
else ('rowsEnabled: legacyRowsEnabled', 'rowsEnabled: true') if case == 'legacy-loader' \
else (r'if \(!routeApplicationSurface\) return;\s*const openRoute', 'const openRoute')
@@ -186,19 +135,7 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
continue
check('held registry has no legacy rows', not early_legacy)
fixture.release_registry()
- page.locator('.cg-catalog-library').wait_for(timeout=30000)
- check('Catalog library withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0)
- if case == 'empty-source':
- check('empty source opens the empty library', page.get_by_text('No catalogs yet', exact=True).count() == 1
- and page.get_by_role('button', name='New catalog', exact=True).count() == 1
- and page.locator('.cg-catalog-library-card').count() == 0)
- check('empty source preserves the saved View', not fixture.view_events
- and fixture.workspace == fixture.original_workspace)
- page.screenshot(path=str(out_dir / 'catalog-empty-source.png'), full_page=True)
- continue
- page.get_by_role('button', name='Open Seasonal collection', exact=True).click()
- page.locator('.cg-catalog-page-thumb[data-page-kind="grid"]').click()
- page.locator('.cg-catalog-canvas .cg-catalog-product-open').first.wait_for(timeout=30000)
+ page.locator('.cg-cat-stage .cg-cat-card').first.wait_for(timeout=30000)
page.wait_for_timeout(600)
if case == 'settings-discriminator':
check('Catalog discriminator removal fails controls absence', bool(applied) and not no_controls(page))
@@ -206,40 +143,13 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
continue
check('resolved Catalog has no Map/Bubble size/Routes', no_controls(page))
check('resolved Catalog registers no route-open handler', page.evaluate('window.catalogRouteListeners.length') == 0)
- check('six editor page kinds remain available',
- page.locator('.cg-catalog-page-thumb').evaluate_all("nodes => nodes.map(node => node.dataset.pageKind)")
- == ['cover', 'toc', 'product', 'grid', 'section', 'closing'])
- check('typed pool walks both cursor pages', None in fixture.typed_cursors
- and 'fixture-next' in fixture.typed_cursors)
- check('all cursor pages painted', sorted(page.locator('.cg-catalog-canvas .cg-catalog-product-open').evaluate_all(
- "nodes => nodes.map(node => node.getAttribute('aria-label').slice(5))"))
+ check('all cursor pages painted', sorted(page.locator('.cg-cat-stage .cg-cat-desc').all_text_contents())
== ['Cedar Supply', 'Willow Floral'])
- before = page.locator('.cg-catalog-canvas').inner_text()
- evidence['mapped_products'] = before
- check('Catalog registry keeps every optional product role',
- all(value in before for value in
- ('19.975', 'Mapped sku', 'Mapped category', 'Mapped description')))
+ before = page.locator('.cg-cat-stage').inner_text()
page.evaluate("window.dispatchEvent(new CustomEvent('aios:route-open', {detail:{routeId:'refused-route'}}))")
page.wait_for_timeout(200)
- check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-catalog-canvas').inner_text() == before)
- check('Catalog editor withholds source footer', page.locator('.cg-grid-footer, .cg-sum-bar').count() == 0)
- if case == 'mobile':
- geometry = page.locator('.cg-catalog-canvas').bounding_box()
- check('390px editor keeps a usable full-width canvas', geometry is not None
- and geometry['width'] >= 250 and geometry['x'] + geometry['width'] <= 391)
- check('390px editor preserves the shared App frame',
- page.locator('.cg-app-frame-header').count() == 1
- and page.get_by_role('link', name='Back to Apps', exact=True).count() == 1)
- heading = page.locator('.cg-catalog-record-head h2').evaluate(
- 'node => {const range=document.createRange(); range.selectNodeContents(node); const r=range.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};}')
- actions = page.locator('.cg-catalog-record-head button').evaluate_all(
- 'nodes => nodes.map(node => {const r=node.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height};})')
- check('390px catalog title does not overlap its actions', len(actions) >= 3 and all(
- heading['x'] + heading['width'] <= action['x'] or action['x'] + action['width'] <= heading['x']
- or heading['y'] + heading['height'] <= action['y'] or action['y'] + action['height'] <= heading['y']
- for action in actions))
- page.screenshot(path=str(out_dir / 'catalog-editor-390.png'), full_page=True)
- page.locator('.cg-catalog-canvas').get_by_role('button', name='Open Cedar Supply', exact=True).click()
+ check('Catalog ignores route-open', no_controls(page) and page.locator('.cg-cat-stage').inner_text() == before)
+ page.get_by_role('button', name='Open Cedar Supply', exact=True).click()
page.locator('.cg-record-modal').wait_for(timeout=10000)
check('real typed tail card drawer', 'Cedar Supply' in page.locator('.cg-record-modal').inner_text())
check('unavailable legacy endpoint never requested', not any(request['path'] == 'customers' for request in fixture.requests))
@@ -248,15 +158,10 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
page.screenshot(path=str(out_dir / 'catalog-cold-drawer.png'), full_page=True)
finally:
context.close()
- for surface in ('data-map', 'route', 'legacy-catalog'):
+ for surface in ('data-map', 'route'):
fixture = AppRoutingFixture()
fixture.config['display'] = {'mode': 'map'}
fixture.workspace['views'][0]['config']['display'] = {'mode': 'map'}
- if surface == 'legacy-catalog':
- display = {'mode': 'catalog',
- 'catalogs': fixture.applications[0]['config']['display']['catalogs']}
- fixture.config['display'] = display
- fixture.workspace['views'][0]['config']['display'] = display
fixture.original_workspace = __import__('copy').deepcopy(fixture.workspace)
if surface == 'route':
fixture.fields.extend([{'key': 'lat', 'label': 'Latitude', 'type': 'number', 'source': 'odoo'},
@@ -266,24 +171,14 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
fixture.applications[0]['templateKind'] = 'route'
fixture.applications[0]['fieldMap'] = {'title': 'name', 'latitude': 'lat', 'longitude': 'lon'}
fixture.applications[0]['config'] = {'display': {'mode': 'map'}}
- context = browser.new_context(viewport={"width": 390 if surface == 'legacy-catalog' else 1440, "height": 1000})
+ context = browser.new_context(viewport={"width": 1440, "height": 1000})
context.route('**/api/**', fixture.route)
# Keep the product's offline map; a synthetic transport cannot make an outward tile read.
context.route('https://tile.openstreetmap.org/**', lambda route: route.abort())
page = context.new_page()
try:
- page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface != 'route'
+ page.goto(base_url + ('/#/data?database=customer_data&view=saved-check' if surface == 'data-map'
else '/#/app?database=customer_data&application=app-fixture'))
- if surface == 'legacy-catalog':
- page.locator('.cg-cat-stage').wait_for(timeout=30000)
- stage = page.locator('.cg-cat-stage').bounding_box()
- rail = page.locator('.cg-cat-rail').bounding_box()
- check('390px legacy rail collapses above a usable page', stage is not None and rail is not None
- and stage['width'] >= 200 and stage['x'] + stage['width'] <= 391
- and rail['height'] <= 129 and stage['y'] >= rail['y'] + rail['height'])
- check('Data Catalog keeps its own footer', page.locator('.cg-grid-footer').count() == 1)
- page.screenshot(path=str(out_dir / 'catalog-legacy-390.png'), full_page=True)
- continue
page.locator('.cg-map-settings').wait_for(timeout=30000)
check(surface + ' keeps Map settings', page.get_by_text('Bubble size', exact=True).count() > 0)
if surface == 'route':
@@ -302,213 +197,3 @@ def mounted_catalog_host(base_url: str, out_dir: Path, negative_controls: bool =
(out_dir / 'catalog-host.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8')
print(f"PASS S71 Catalog host mounted: {len(evidence['checks'])} checks, {len(evidence['controls'])} controls")
return evidence
-
-def client_amend_contracts() -> int:
- """Execute the edited callbacks with held acknowledgements and whole-batch refusals."""
- import subprocess
- script = r'''
-const fs = require("fs"), vm = require("vm"), ts = require("typescript"), assert = require("node:assert/strict");
-const grid = ts.createSourceFile("grid.tsx", fs.readFileSync("src/customer-grid/CustomerGrid.tsx", "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-const bridge = ts.createSourceFile("bridge.ts", fs.readFileSync("src/customer-grid/apiBridge.ts", "utf8"), ts.ScriptTarget.Latest, true);
-const display = ts.createSourceFile("display.ts", fs.readFileSync("src/customer-grid/display.ts", "utf8"), ts.ScriptTarget.Latest, true);
-let checks = 0;
-function check(value, why) { assert.ok(value, why); checks++; }
-function declaration(file, name) {
- let found;
- function visit(node) {
- if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node)) && node.name?.getText(file) === name) found = node;
- ts.forEachChild(node, visit);
- }
- visit(file); assert.ok(found, "missing executable " + name);
- return ts.isVariableDeclaration(found) ? "const " + found.getText(file) + ";" : found.getText(file).replace(/^export\s+/, "");
-}
-function bind(name, context, file = grid) {
- const source = declaration(file, name) + "\nglobalThis.subject = " + name + ";";
- const js = ts.transpileModule(source, {compilerOptions:{target:ts.ScriptTarget.ES2022, module:ts.ModuleKind.CommonJS}}).outputText;
- const box = {useCallback: fn => fn, ...context};
- vm.runInNewContext(js, box); return box.subject;
-}
-function pure(name, context = {}, file = grid) { return bind(name, context, file); }
-async function run() {
- const numericOrUndefined = pure("numericOrUndefined", {}, display);
- const numberWriteRefusal = pure("numberWriteRefusal", {numericOrUndefined}, display);
- const numberBatchRefusal = pure("numberBatchRefusal", {numberWriteRefusal});
- const number = {key:"amount", label:"Amount", type:"currency", format:{currencySymbol:"EUR", allowNegative:false}};
- const fields = [number, {key:"note",label:"Note",type:"text"}];
- const writes = [], entries = [], toasts = [];
- const ctx = {fields, numberBatchRefusal, currentValue:()=> "before",
- patchOverlay:(...args)=>writes.push(args), recordCells:(...args)=>entries.push(args),
- TOAST_EVENT:"toast", CustomEvent: class {constructor(type, init) {this.type=type;this.detail=init.detail;}},
- window:{dispatchEvent:event=>toasts.push(event)}};
- const single = bind("patchAndRecord", ctx), batch = bind("patchManyAndRecord", ctx);
- single(1, {amount:"-1",note:"must stay unchanged"});
- check(writes.length === 0 && entries.length === 0 && toasts.at(-1).detail.tone === "error", "single negative is a C4 refusal before writes or undo");
- batch([{pid:1,updates:{amount:"5"}},{pid:2,updates:{amount:"Infinity"}}], "paste");
- check(writes.length === 0 && entries.length === 0, "mixed valid and invalid paste is atomic");
- for (const value of ["", "0", "125.6789"]) single(1, {amount:value});
- check(writes.length === 3 && entries.length === 3, "blank, zero and unrounded valid writes retain undo");
- const changedFields = [{...number, format:{...number.format, allowNegative:true}}];
- bind("patchAndRecord", {...ctx,fields:changedFields})(1,{amount:"-5"});
- check(writes.length === 4, "current field policy admits a valid negative");
- let fetched = 0, closed = 0, busy = 0;
- const noop = () => {};
- await bind("applyBulkUpdate", {...ctx, bulkField:number,bulkSelectedCount:20,bulkValue:"-2",
- clearSelection:noop,dropTableRowsCache:noop,patchManyAndRecord:batch,requestWindow:noop,scope:"ut_fixture",
- selectedPids:new Set([1]),serverBulkPending:false,serverFilteredSelection:{token:"selection"},
- windowRequest:noop,setServerBulkPending:()=>busy++,setBulkUpdateOpen:()=>closed++,fetch:()=>fetched++})();
- check(fetched === 0 && closed === 0 && busy === 0, "server filtered bulk refuses before request, busy state or dialog dismissal");
- const buildOverlayField = pure("buildOverlayField", {DEFAULT_SUMMED_TYPES:[],slugify:pure("slugify")});
- for (const value of [0,false,""]) check(buildOverlayField("Default","text",[],{defaultValue:value}).defaultValue === value, "falsy default survives constructor");
- check(Object.hasOwn(buildOverlayField("Clear","text",[],{defaultValue:null}),"defaultValue"), "explicit default clear retains property presence");
- const createdDefinitions = [];
- let createdFields = [];
- const create = bind("createField",{canAddField:true,scopeChoice:false,isUserTable:true,scope:"ut_fixture",
- buildOverlayField,insertColumn:noop,saveField:()=>{throw Error("wrong definition door");},stampFieldEdit:noop,stampFieldDelete:noop,
- setFields:update=>{createdFields=update(createdFields);},
- addTableField:(_scope,definition)=>{createdDefinitions.push(definition);return new Promise(()=>{});}});
- for (const [kind,value] of [["text",""],["int",0],["checkbox",false],["text",null]])
- create("Default",kind,null,"end",undefined,undefined,{defaultValue:value});
- check(createdDefinitions.slice(0,4).map(field=>JSON.stringify(field.defaultValue)).join() === '"",0,false,null',
- "field creation forwards blank, zero, false and explicit clear through the definition body");
- create("Choice","select",null,"end",["Active"],undefined,{defaultValue:"Active"});
- create("Date","date",null,"end",undefined,undefined,{defaultValue:"2026-10-19"});
- check(createdDefinitions[4].defaultValue === "Active" && createdDefinitions[5].defaultValue === "2026-10-19",
- "select and date defaults use the same field creation body");
- const patches = [];
- const old = {key:"amount",label:"Amount",type:"int",source:"overlay",custom:true,defaultValue:0};
- const retype = bind("retypeField", {fieldByKey:new Map([["amount",old]]),saveField:()=>{throw Error("wrong definition door");},
- scope:"ut_fixture",isUserTable:true,emitHostEvent:noop,isUserSchemaField:()=>true,
- patchTableField:async(_scope,_key,patch)=>{patches.push(patch);return null;},setFields:noop,signal:noop});
- retype("amount","int"); retype("amount","int",[],{defaultValue:null});
- check(patches[0].defaultValue === 0 && patches[1].defaultValue === null, "retype preserves zero or sends explicit clear on the schema PATCH");
- let pending = [], overlays = {}, undo = {past:[],future:[]}, resolveAdd, request;
- const scope = "ut_fixture", workspaceScopeRef = {current:scope};
- const setPendingRows = update => {pending = update(pending);};
- const setOverlayEdits = update => {overlays = update(overlays);};
- const acceptPendingRow = bind("acceptPendingRow",{scope,workspaceScopeRef,setPendingRows,setOverlayEdits});
- const undoBook = {current:{}}, stackFor=()=>undo, pushUndo=(_state,entry)=>{undo={...undo,past:[...undo.past,entry]};return undo;};
- const defaults = [{key:"name",type:"text",defaultValue:"base"},{key:"zero",type:"int",defaultValue:0},
- {key:"tick",type:"checkbox",defaultValue:false},{key:"choice",type:"select",defaultValue:"Active"},
- {key:"starts",type:"date",defaultValue:"2026-11-01"},{key:"date",type:"date",defaultValue:"2026-10-19"},{key:"denied",type:"text",defaultValue:"hidden",denied:true}];
- const append = bind("appendRow", {canMutateRecords:true,scope,seedValues:()=>({name:"seed",date:""}),mintRid:()=>7,
- fields:defaults,payload:{viewer:{username:"qa"}},mayEditField:field=>!field.denied,
- setPendingRows,setNewRowPid:noop,addTableRow:(...args)=>{request=args;return new Promise(resolve=>{resolveAdd=resolve;});},
- acceptPendingRow,workspaceScopeRef,undoBook,stackFor,pushUndo});
- const adding = append();
- check(pending[0].zero === "0" && pending[0].tick === "False" && pending[0].name === "seed" && pending[0].date === "" && pending[0].choice === "Active" && pending[0].starts === "2026-11-01"
- && !Object.hasOwn(pending[0],"denied"), "authorized defaults paint immediately below explicit seeds");
- check(request[1].zero === "0" && request[1].tick === "False" && request.length === 3, "append sends painted defaults with ordinary restore=false call");
- overlays[7]={name:"typed while pending"};
- resolveAdd({rid:"8",pid:8,values:{name:"server",sequence:"51",creator:"qa"}});
- await adding;
- check(pending[0].pid === 8 && pending[0].sequence === "51" && overlays[8].name === "typed while pending" && !overlays[7],
- "acknowledgement supplies generated cells and moves later local overlay to returned identity");
- check(undo.past[0].rows[0].values.zero === "0" && undo.past[0].rows[0].rid === "8", "append undo captures defaults and accepted identity");
- const stale = [], restores = [], deleted = [];
- const restoreEntry = {kind:"rowAdd",table:scope,rows:[{rid:"9",values:{name:"restored",sequence:"old",creator:"forged",modified:"old",modifier:"forged"}}]};
- let resolveRestore;
- const restoreRowsRef = {current:[]};
- const applyEntry = bind("applyEntry", {fields:[{key:"sequence",type:"autonumber"},{key:"creator",type:"created_by"},
- {key:"modified",type:"last_modified_time"},{key:"modifier",type:"last_modified_by"}],
- AUDIT_FIELD_TYPES:["created_by","last_modified_time","last_modified_by"],directed:entry=>entry,patchOverlay:noop,
- withdrawPending:ids=>{pending=pending.filter(row=>!ids.map(Number).includes(row.pid));},emitHostEvent:noop,
- acceptPendingRow,workspaceScopeRef,setPendingRows,setOverlayEdits,rowsRef:restoreRowsRef,mintRid:()=>11,addTableRow:(...args)=>{restores.push(args);return new Promise(resolve=>{resolveRestore=resolve;});},
- deleteTableRow:async(_table,rid)=>{deleted.push(rid);return true;},signal:(...args)=>stale.push(args),
- ROWS_STALE_EVENT:"stale",TOAST_EVENT:"toast",describe:()=>"undo",applyingUndo:{current:false}});
- const restoring = applyEntry(restoreEntry,"forward");
- const optimistic = pending.find(row=>row.pid === 9);
- check(optimistic && Object.keys(optimistic).sort().join() === "name,pid"
- && Object.keys(restores[0][1]).join() === "name" && restores[0][3] === true, "all four generated kinds stay out of restore request and optimistic cells");
- resolveRestore({rid:"10",pid:10,values:{sequence:"52",creator:"original",modified:"fresh",modifier:"qa"}});
- await restoring;
- check(pending.find(row=>row.pid === 10)?.creator === "original" && !stale.some(event=>event[0] === "stale"),
- "restored creator, counter and modifier paint from ack without a full refresh");
- await applyEntry({...restoreEntry,kind:"rowDelete"},"forward");
- check(deleted[0] === "10" && !pending.some(row=>row.pid === 10), "redo deletes the accepted restored identity without a ghost");
- restoreRowsRef.current = pending;
- const occupied = {kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"other restored row"}}]};
- const colliding = applyEntry(occupied,"forward");
- check(pending.find(row=>row.pid === 8)?.name === "server" && pending.find(row=>row.pid === 11)?.name === "other restored row",
- "occupied restore keeps the existing pending row and paints a separate temporary identity");
- resolveRestore({rid:"12",pid:12,values:{sequence:"53",creator:"original"}});
- await colliding;
- check(pending.some(row=>row.pid === 8) && pending.some(row=>row.pid === 12) && occupied.rows[0].rid === "12",
- "collision acknowledgement and next undo retain both real identities");
- restoreRowsRef.current = pending;
- const refusedRestore=applyEntry({kind:"rowAdd",table:scope,rows:[{rid:"8",values:{name:"refused"}}]},"forward");
- resolveRestore(null); await refusedRestore;
- check(pending.some(row=>row.pid === 8) && !pending.some(row=>row.pid === 11),
- "a refused collision withdraws only its temporary row and preserves the occupied record");
- const linkSelectionPredicate = pure("linkSelectionPredicate");
- const restriction = {conj:"and",nodes:[{colId:"status",op:"eq",value:"Active"}]};
- const candidate = {filterConj:"or",filters:[{colId:"name",op:"contains",value:"Cedar"},{colId:"name",op:"contains",value:"Willow"}]};
- const narrowed = linkSelectionPredicate(candidate,restriction);
- check(narrowed.filterConj === "and" && narrowed.filters[0].children === restriction.nodes
- && narrowed.filters[1].conj === "or" && narrowed.filters[1].children === candidate.filters, "candidate OR search remains inside the immutable AND restriction");
- check(linkSelectionPredicate({filters:[]},restriction).filters[0].children === restriction.nodes, "clearing search cannot relax link restriction");
- const hookSlots = [], windowCalls = [], completions = [];
- let cursor = 0, unavailableCondition = false;
- const hookContext = {
- useRef:initial=>{const i=cursor++;return hookSlots[i]??=( {current:initial} );},
- useState:initial=>{const i=cursor++;if (!(i in hookSlots)) hookSlots[i]=initial;
- return [hookSlots[i],value=>{hookSlots[i]=typeof value === "function" ? value(hookSlots[i]) : value;}];},
- useCallback:fn=>fn,useEffect:()=>{},linkSelectionPredicate,ROWS_STALE_EVENT:"stale",
- unresolvedConditions:()=>unavailableCondition ? 1 : 0,window:ctx.window,CustomEvent:ctx.CustomEvent,TOAST_EVENT:"toast",
- fetchTableWindow:(table,request)=>{windowCalls.push({table,request});return new Promise(resolve=>completions.push(resolve));}};
- const windowHook = pure("useRecordIdWindow",hookContext);
- const renderWindow = filter=>{cursor=0;return windowHook("ut_target",undefined,null,undefined,false,false,filter);};
- const firstWindow = renderWindow(restriction);
- check(firstWindow.payload === null && firstWindow.pending, "restricted picker withholds an unfiltered initial payload");
- firstWindow.requestWindow({...candidate,offset:50,limit:50,search:"Cedar"});
- check(windowCalls[0].request.filterConj === "and" && windowCalls[0].request.filters[0].children === restriction.nodes
- && windowCalls[0].request.offset === 50 && windowCalls[0].request.search === "Cedar",
- "real window callback sends immutable restriction with search and page before server counts");
- const changedRestriction={conj:"and",nodes:[{colId:"status",op:"eq",value:"Ready"}]};
- const secondWindow=renderWindow(changedRestriction);
- completions[0]({rows:[{pid:1}],counts:{matched:99}}); await Promise.resolve();
- check(renderWindow(changedRestriction).payload === null, "stale response from an older link condition cannot populate the picker");
- secondWindow.requestWindow({offset:0,limit:50,filters:[],search:""});
- completions[1]({fields:[{key:"status",type:"text"}],rows:[{pid:2}],counts:{matched:1}}); await Promise.resolve();
- check(renderWindow(changedRestriction).payload?.counts.matched === 1, "fresh restricted response owns rows and count");
- unavailableCondition = true;
- const toastCount = toasts.length;
- renderWindow(changedRestriction).requestWindow({offset:0,limit:50,filters:[]});
- completions[2]({fields:[],rows:[{pid:3}],counts:{matched:99}}); await Promise.resolve();
- check(renderWindow(changedRestriction).payload === null && toasts.length === toastCount + 1 && toasts.at(-1).detail.tone === "error",
- "an unavailable restriction withholds broader rows and counts with a C4 refusal");
- const posts = [];
- let reply = {rid:"12",pid:12,values:{pid:999,zero:0,blank:null,tick:false,private:{secret:"no"}}};
- const add = bind("addTableRow", {API_V1:"/api/v1",CREDENTIALS:"include",JSON_HEADERS:{"Content-Type":"application/json"},
- fetch:async(_url,init)=>{posts.push(JSON.parse(init.body));return {ok:true};},handledSession:()=>false,
- readJson:async()=>reply,dropTableRowsCache:noop,signal:noop,TOAST_EVENT:"toast",DATA_ERROR_EVENT:"error"}, bridge);
- const ack = await add(scope,{name:"new"},12);
- check(posts[0].restore === false && ack.pid === 12 && ack.values.zero === 0 && ack.values.blank === null && ack.values.tick === "False"
- && !Object.hasOwn(ack.values,"pid") && !Object.hasOwn(ack.values,"private"), "ordinary create sends false and normalizes authorized scalar acknowledgement cells");
- reply={rid:"12",pid:12}; const legacy=await add(scope,{},12,true);
- check(posts[1].restore === true && !Object.hasOwn(legacy,"values"), "restore transport tolerates an older identity-only acknowledgement");
- console.log("PASS W3 client amendments: " + checks + "/" + checks + " checks");
-}
-run().catch(error=>{console.error(error.stack);process.exitCode=1;});
-'''
- result = subprocess.run(["node", "-"], input=script, text=True, cwd=WEB, timeout=45)
- return result.returncode
-
-
-if __name__ == "__main__":
- import argparse
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--client", action="store_true")
- parser.add_argument("--base-url")
- parser.add_argument("--out-dir", type=Path, default=Path("/tmp/aios-w3-host"))
- args = parser.parse_args()
- if args.client:
- result = client_amend_contracts()
- if result or not args.base_url:
- raise SystemExit(result)
- if args.base_url:
- from urllib.parse import urlsplit
- if urlsplit(args.base_url).hostname not in ("127.0.0.1", "localhost", "::1"):
- parser.error("The synthetic fixture requires a local Vite origin")
- mounted_catalog_host(args.base_url, args.out_dir)
- else:
- raise SystemExit(catalog_host_scan())
diff --git a/web/src/apps/catalog/CatalogApp.tsx b/web/src/apps/catalog/CatalogApp.tsx
index dd6d3b694b7d78fda40c05594045b578bd74768f..3ec161b28d6bb2f6e08033a420def9fe37588055 100644
--- a/web/src/apps/catalog/CatalogApp.tsx
+++ b/web/src/apps/catalog/CatalogApp.tsx
@@ -45,6 +45,9 @@ export function CatalogApp({ definition, database, scope, onOpen, onData, editor
;
}
const filteredCodes = data.rows.map((row) => String(row[definition.fieldMap.key] ?? "").trim()).filter(Boolean);
+ if (!filteredCodes.length) {
+ return
` whose summary is a real disclosure control, and wrapping every one of
them in its own live region would announce the same strip N times. */}
{groupedRefusals.length > 0 && (
- <>
+
{groupedRefusals.map((refusal) => (
))}
- >
+
)}
) : (
diff --git a/web/src/customer-grid/apiBridge.ts b/web/src/customer-grid/apiBridge.ts
index 361ee1e595bb8c06654c07bb5ee8720d22dc335e..e2859cd8fdc384837f800360bf04a1d83e116593 100644
--- a/web/src/customer-grid/apiBridge.ts
+++ b/web/src/customer-grid/apiBridge.ts
@@ -1825,27 +1825,20 @@ export function patchCustomer(pid: number, updates: Partial): Promise;
-}
-
export async function addTableRow(
tableKey: string,
values: Record = {},
- rid?: string | number,
- restore = false
-): Promise {
+ rid?: string | number
+): Promise<{ rid: string | number; pid: number } | null> {
try {
const res = await fetch(`${API_V1}/tables/${encodeURIComponent(tableKey)}/rows`, {
method: "POST",
credentials: CREDENTIALS,
headers: JSON_HEADERS,
- body: JSON.stringify(rid === undefined ? { values, restore } : { rid, values, restore }),
+ body: JSON.stringify(rid === undefined ? { values } : { rid, values }),
});
if (handledSession(res)) return null;
- const body = (await readJson(res)) as { rid?: string | number; pid?: number; values?: unknown;
+ const body = (await readJson(res)) as { rid?: string | number; pid?: number;
error?: { message?: string } } | null;
if (!res.ok) {
// The server states WHY (a row cap, a store refusal). Surfacing its sentence beats a
@@ -1859,15 +1852,7 @@ export async function addTableRow(
return null;
}
dropTableRowsCache(tableKey);
- const accepted: TableRowAcknowledgement["values"] = body.values &&
- typeof body.values === "object" && !Array.isArray(body.values) ? {} : undefined;
- if (accepted) for (const [key, value] of Object.entries(body.values as Record)) {
- if (key === "pid") continue;
- if (value === null || typeof value === "string" ||
- (typeof value === "number" && Number.isFinite(value))) accepted[key] = value;
- else if (typeof value === "boolean") accepted[key] = value ? "True" : "False";
- }
- return { rid: body.rid, pid: body.pid, ...(accepted ? { values: accepted } : {}) };
+ return { rid: body.rid, pid: body.pid };
} catch {
signal(DATA_ERROR_EVENT, "Cannot reach the server.");
return null;
diff --git a/web/src/filter-kit/FieldsHidePanel.tsx b/web/src/filter-kit/FieldsHidePanel.tsx
index fb4bbd0bf7d2db4aacfbefe4ea6dea02749729c5..db8215e9334dc0a7d8d3c9f04aab988632bf577b 100644
--- a/web/src/filter-kit/FieldsHidePanel.tsx
+++ b/web/src/filter-kit/FieldsHidePanel.tsx
@@ -15,7 +15,6 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useEscapeClose } from "../ui/useEscapeClose";
-import { TOAST_EVENT } from "../apiContract";
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
// ⭐⭐ W46-T31 (contract C6) — the lane's own sheet, imported from the COMPONENT and never from
// `index.css`. An @imported sheet is inlined at the TOP of the bundle's cascade and loses every
@@ -788,12 +787,7 @@ export function FieldsHidePanel({
if (action === "reassign" && onReassignFields && passed.length > 0) onReassignFields(passed);
if (action === "share" || action === "reassign") done += passed.length;
const text = bulkOutcomeLine(action, done, refused);
- if (text && refused.length > 0) {
- window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
- setBulkNote(null);
- } else {
- setBulkNote(text ? { text, refused: false } : null);
- }
+ setBulkNote(text ? { text, refused: refused.length > 0 } : null);
/**
* ⭐ AFTER A DELETE THE SELECTION BECOMES EXACTLY WHAT SURVIVED IT, and that is one
* decision doing two jobs: the deleted keys are gone from `fields` and must not linger in a
@@ -1625,7 +1619,7 @@ export function FieldsHidePanel({
`bulkOutcomeLine` and never here, so R6(a)'s refusal has exactly one producer. */}
{bulkNote && (
{bulkNote.text}
diff --git a/web/src/index.css b/web/src/index.css
index 5393074d53c6dd7d34e5e5764f1c144639be3b12..dd8a9292864b6d49402c283cef5e4f30928ce99c 100644
--- a/web/src/index.css
+++ b/web/src/index.css
@@ -30,7 +30,6 @@
@import "./styles/wave51/sheet-chrome.css";
@import "./styles/wave51/sheet-engine.css";
@import "./styles/sdlc74/settings.css";
-@import "./styles/sdlc76/overlays.css";
@font-face {
font-family: "Inter";
diff --git a/web/src/intelligence/intelligenceApi.ts b/web/src/intelligence/intelligenceApi.ts
index acce23cd11f1c2a10273f2e04baa8d984282f2a4..f7ce85725a159e758f3c3db46d6952c0cfc3fd97 100644
--- a/web/src/intelligence/intelligenceApi.ts
+++ b/web/src/intelligence/intelligenceApi.ts
@@ -104,8 +104,6 @@ export interface IntelligenceList {
offset: number;
limit: number;
folders: string[];
- canManageFolders?: boolean;
- folderRevision?: number;
}
export interface IntelligenceQuery {
q: string;
@@ -134,10 +132,6 @@ export interface IntelligenceApi {
history(path: string, version: number, signal?: AbortSignal): Promise;
restore(path: string, version: number, expectedVersion: number): Promise;
insights(signal?: AbortSignal): Promise;
- renameFile?: (path: string, title: string, expectedVersion: number) => Promise;
- deleteFile?: (path: string, expectedVersion: number) => Promise<{ deleted: string }>;
- renameFolder?: (path: string, name: string, expectedRevision: number) => Promise<{ path: string }>;
- deleteFolder?: (path: string, expectedRevision: number) => Promise<{ deleted: string }>;
}
export class IntelligenceApiError extends Error {
@@ -163,7 +157,6 @@ function readRow(value: unknown): IntelligenceFileRow {
if (value.section === "database-notes" && (typeof value.databaseKey !== "string" || !value.databaseKey
|| value.databaseKey.includes("/") || value.path !== `database-notes/${value.databaseKey}.md`
|| typeof value.canEdit !== "boolean" || value.revisionHistory !== "database-note")) throw new Error("Invalid note.");
- if (value.canEdit != null && typeof value.canEdit !== "boolean") throw new Error("Invalid permission.");
return value as unknown as IntelligenceFileRow;
}
function readFile(value: unknown): IntelligenceFile {
@@ -196,16 +189,7 @@ function readList(value: unknown): IntelligenceList {
|| (value.files.length > 0 && value.offset + value.files.length > value.total)) throw new Error("Invalid list.");
const files = value.files.map(readRow);
if (new Set(files.map((file) => file.path)).size !== files.length) throw new Error("Invalid list.");
- if ((value.canManageFolders != null && typeof value.canManageFolders !== "boolean")
- || (value.folderRevision != null && !count(value.folderRevision))) throw new Error("Invalid folder permission.");
- return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[],
- ...(typeof value.canManageFolders === "boolean" ? { canManageFolders: value.canManageFolders } : {}),
- ...(count(value.folderRevision) ? { folderRevision: value.folderRevision } : {}) };
-}
-
-function readDeleted(value: unknown, path: string): { deleted: string } {
- if (!object(value) || value.deleted !== path) throw new Error("Invalid deletion.");
- return { deleted: path };
+ return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[] };
}
function readHistory(value: unknown): IntelligenceHistory {
@@ -258,8 +242,7 @@ async function request(query: string, init: RequestInit, parse: (value: unkno
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
const refusal = refusalPair(body);
- const message = response.status >= 500 ? (init.method === "PATCH" || init.method === "DELETE"
- ? "The change could not be confirmed. Reload and try again." : init.method === "PUT"
+ const message = response.status >= 500 ? (init.method === "PUT"
? "The file save could not be confirmed. Reload and try again." : init.method === "POST"
? resource === "restore" ? "The restore could not be confirmed. Reload and try again."
: "The decision could not be confirmed. Reload and try again." : "Brain files could not be read. Try again.") : refusal.message;
@@ -288,29 +271,6 @@ export function newFilePayload(input: NewIntelligenceFile): { path: string; body
}
export const intelligenceApi: IntelligenceApi = {
- renameFile(path, title, expectedVersion) {
- return request("", { method: "PATCH", headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ path, title, expectedVersion }) }, (value) => {
- const file = readFile(value);
- if (file.path !== path || file.version <= expectedVersion) throw new Error("Invalid rename.");
- return file;
- });
- },
- deleteFile(path, expectedVersion) {
- return request(`?${new URLSearchParams({ path, expectedVersion: String(expectedVersion) })}`,
- { method: "DELETE" }, (value) => readDeleted(value, path));
- },
- renameFolder(path, name, expectedRevision) {
- return request("", { method: "PATCH", headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ path, name, expectedRevision }) }, (value) => {
- if (!object(value) || typeof value.path !== "string" || !value.path) throw new Error("Invalid folder rename.");
- return { path: value.path };
- }, "folders");
- },
- deleteFolder(path, expectedRevision) {
- return request(`?${new URLSearchParams({ path, expectedRevision: String(expectedRevision) })}`,
- { method: "DELETE" }, (value) => readDeleted(value, path), "folders");
- },
history(path, version, signal) {
return request(`?${new URLSearchParams({ path, version: String(version) })}`, { method: "GET", signal }, readHistory, "history");
},
diff --git a/web/src/operator/OperatorPage.tsx b/web/src/operator/OperatorPage.tsx
index e0280ffbd316192fbb3e5294b106b294fa91d916..7d49f910e370db172c3bdd51cdc01d5c2d5b5fa3 100644
--- a/web/src/operator/OperatorPage.tsx
+++ b/web/src/operator/OperatorPage.tsx
@@ -1,10 +1,10 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import {
AutomationError, createOperatorGrant, getOperatorAudit, getOperatorSetup,
getOperatorVoiceSetup, getSystemData, type OperatorAudit, type OperatorGrant,
type OperatorSetup, type OperatorSetupField, type OperatorVoiceSetup, type SystemData,
} from "../automation/automationApi";
-import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
+import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
import "./operator.css";
export interface OperatorPageProps { platformAdmin: boolean }
@@ -13,30 +13,7 @@ const SAFE_SETUP_FIELDS: OperatorSetupField[] = [
"displayName", "timezone", "voicePurpose", "consentPolicy", "queryEnabled", "providerLabel",
];
-function useRefusalToast() {
- const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
- const sequence = useRef(0);
- const delivered = useRef(0);
- useEffect(() => {
- if (!messages.length) return;
- const through = messages[messages.length - 1].id;
- for (const message of messages) {
- if (message.id <= delivered.current) continue;
- delivered.current = message.id;
- const text = message.text;
- window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
- }
- setMessages((current) => current.filter((message) => message.id > through));
- }, [messages]);
- return (text: string) => {
- if (!text) return;
- const message = { id: ++sequence.current, text };
- setMessages((current) => [...current, message]);
- };
-}
-
export default function OperatorPage({ platformAdmin }: OperatorPageProps) {
- const refuse = useRefusalToast();
const [audit, setAudit] = useState(null);
const [system, setSystem] = useState(null);
const [tenant, setTenant] = useState("");
@@ -80,20 +57,13 @@ export default function OperatorPage({ platformAdmin }: OperatorPageProps) {
const voiceSetup = await getOperatorVoiceSetup(target, granted.token);
setSetup(tenantSetup); setVoice(voiceSetup);
} catch (error) {
- const refused = error instanceof AutomationError && [401, 403, 404].includes(error.status);
- const text = (refused ? "That tenant or capability is unavailable. " : "")
- + (error instanceof Error ? error.message : "Tenant setup unavailable.");
- if (refused) refuse(text);
- else setProblem(text);
+ const refused = error instanceof AutomationError && (error.status === 403 || error.status === 404);
+ setProblem((refused ? "That tenant or capability is unavailable. " : "") + (error instanceof Error ? error.message : "Tenant setup unavailable."));
} finally {
// Both allowed and refused inspections append an audit result. Refresh after either path so
// the visible receipt is the final server outcome, not the preflight list.
try { setAudit((await getOperatorAudit()).audit); }
- catch (error) {
- const text = error instanceof Error ? error.message : "Audit refresh unavailable.";
- if (error instanceof AutomationError && [401, 403, 404].includes(error.status)) refuse(text);
- else setLoadError({ sentence: "Could not refresh the audit history.", detail: text });
- }
+ catch (error) { setProblem((current) => current || (error instanceof Error ? error.message : "Audit refresh unavailable.")); }
setBusy(false);
}
}
diff --git a/web/src/query/queryApi.ts b/web/src/query/queryApi.ts
index 5271b3b7efd1f013bb2c55620a62499ffd496e21..c084fbf8b359d3e8a7a5c95cf011fd0c648b5134 100644
--- a/web/src/query/queryApi.ts
+++ b/web/src/query/queryApi.ts
@@ -254,7 +254,7 @@ export interface AssistantArtifact {
createdAt: string; status: "active" | "paused" | "deleted";
toolCall: ArtifactToolCall;
file_id?: string; mime?: string; link?: string; frozen_at?: string;
- actions: Array<"open" | "run" | "pause" | "resume" | "rename" | "delete">;
+ actions: Array<"open" | "run" | "pause" | "resume" | "delete">;
}
export interface ArtifactIndex { items: AssistantArtifact[]; nextCursor: string | null; }
diff --git a/web/src/query/queryParts.tsx b/web/src/query/queryParts.tsx
index cccf6cbc446924f13e0a1f0770bd94a2183fd293..fd7c4e1dce84ea1a7d37420f1493ced5df0de68c 100644
--- a/web/src/query/queryParts.tsx
+++ b/web/src/query/queryParts.tsx
@@ -1,7 +1,6 @@
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import type { ReactNode } from "react";
import { useEscapeClose } from "../ui/useEscapeClose";
-import { TOAST_EVENT } from "../apiContract";
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
import { FolderMark } from "../customer-grid/icons";
@@ -52,28 +51,6 @@ import type { SavedQuery } from "./queryApi";
import "./query.css";
/** Which label of which row is being typed into. One at a time, by construction. */
-function useRefusalToast() {
- const [messages, setMessages] = useState<{ id: number; text: string }[]>([]);
- const sequence = useRef(0);
- const delivered = useRef(0);
- useEffect(() => {
- if (!messages.length) return;
- const through = messages[messages.length - 1].id;
- for (const message of messages) {
- if (message.id <= delivered.current) continue;
- delivered.current = message.id;
- const text = message.text;
- window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
- }
- setMessages((current) => current.filter((message) => message.id > through));
- }, [messages]);
- return (text: string) => {
- if (!text) return;
- const message = { id: ++sequence.current, text };
- setMessages((current) => [...current, message]);
- };
-}
-
interface Editing { id: string; field: "name" | "description"; value: string; }
function QueryActionMenu({ anchor, onClose, children }: {
@@ -219,23 +196,20 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {
const [editing, setEditing] = useState(null);
const menuOpenerRef = useRef(null);
const editingFinishedRef = useRef(false);
- const editingSequence = useRef(0);
useEscapeClose(editing !== null, () => {
- editingSequence.current += 1;
editingFinishedRef.current = true;
setEditing(null);
menuOpenerRef.current?.focus();
});
const beginEditing = (next: Editing) => {
- editingSequence.current += 1;
editingFinishedRef.current = false;
setMenuFor("");
setEditing(next);
};
// âš TWO STATES, NOT ONE. A refusal and a confirmation read differently and are coloured
// differently; sharing one slot painted "Saved as ..." in the refusal red.
+ const [problem, setProblem] = useState("");
const [notice, setNotice] = useState("");
- const refuse = useRefusalToast();
/**
* ⭐ C2's star list, read AFTER PAINT and never blocking the rail (E-2: `GET /starred` scans
* every visible database's view bucket and was MEASURED at 7,331 ms on a cold container). The
@@ -245,28 +219,17 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {
*/
const stars = useStarred();
const starred = new Set(stars.starred.queries);
- const said = (message: string) => setNotice(message);
- const failed = (text: string) => {
- setNotice("");
- refuse(text);
- };
+ const said = (message: string) => { setNotice(message); setProblem(""); };
+ const failed = (message: string) => { setProblem(message); setNotice(""); };
const commit = async () => {
if (!editing || editingFinishedRef.current) return;
editingFinishedRef.current = true;
const current = editing;
- const sequence = editingSequence.current;
setEditing(null);
const result = await renameQuery(current.id, current.field === "name"
? { name: current.value } : { description: current.value });
- if (!result.ok) {
- if (sequence === editingSequence.current) {
- editingFinishedRef.current = false;
- setEditing((next) => next ?? current);
- }
- failed(result.message);
- return;
- }
+ if (!result.ok) { failed(result.message); return; }
said("");
onChanged?.(result.value);
};
@@ -328,6 +291,7 @@ export function QueryRail({ groups, activeId, onSelect, onDelete, onChanged }: {