Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(show-page-acl): retire show_page resource ACL (#1605)
Max36dabbee3c28
diff --git a/core/show_pages.py b/core/show_pages.pyindex 7557d0c9a..28674946c 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -303,34 +303,6 @@ class ShowAccessApplyResult:show_access: ShowAccess-def get_show_page_resource_metadata(connection: Connection, session_id: str) -> dict[str, str] | None:- """Return the Show Page title metadata allowed in the hosted index."""-- row = connection.execute(- select(- show_pages.c.session_id,- show_pages.c.updated_at.label("page_updated_at"),- agent_sessions.c.title,- agent_sessions.c.updated_at.label("session_updated_at"),- )- .select_from(- show_pages.outerjoin(- agent_sessions,- agent_sessions.c.id == show_pages.c.session_id,- )- )- .where(show_pages.c.session_id == session_id)- .limit(1)- ).mappings().first()- if row is None:- return None- title = str(row["title"] or "").strip()- return {- "display_name": title or str(row["session_id"]),- "updated_at": str(row["session_updated_at"] or row["page_updated_at"]),- }--def validate_session_id(session_id: str) -> str:value = (session_id or "").strip()if not value:@@ -683,18 +655,11 @@ def require_show_page_management(*,user_context: Any = None,) -> None:- """Require management access using the caller's active transaction."""-- from storage import resource_access_service+ """Require Instance Editor authority to change the page."""session_id = validate_session_id(session_id)context = _resolve_resource_access_context(user_context)- if not resource_access_service.can_manage_resource_acl(- context,- "show_page",- session_id,- connection=connection,- ):+ if not _instance_editor_or_owner(context):raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")@@ -704,18 +669,11 @@ def require_show_page_sharing_control(*,user_context: Any = None,) -> None:- """Require resource-owner authority for shared-audience changes."""-- from storage import resource_access_service+ """Require Instance Editor authority to widen anonymous sharing."""session_id = validate_session_id(session_id)context = _resolve_resource_access_context(user_context)- if not resource_access_service.can_control_resource_sharing(- context,- "show_page",- session_id,- connection=connection,- ):+ if not _instance_editor_or_owner(context):raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")@@ -725,20 +683,24 @@ def require_show_page_access_management(*,user_context: Any = None,) -> None:- """Require authority to manage the audience or make sharing more restrictive."""-- from storage import resource_access_service+ """Require Instance Editor authority to manage the audience or narrow sharing."""session_id = validate_session_id(session_id)context = _resolve_resource_access_context(user_context)- if not resource_access_service.can_manage_show_page_access(- context,- session_id,- connection=connection,- ):+ if not _instance_editor_or_owner(context):raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")+def _instance_editor_or_owner(context: Any) -> bool:+ """The /show Workbench management capability is the Instance Editor role.++ ``show_page_email`` sessions are Viewer-only, so they can never satisfy an+ Editor check. Instance Owner passes as the top of the role ladder.+ """++ return bool(context is not None and context.has_role("editor"))++def private_url(session_id: str, *, config: V2Config | None = None) -> str | None:base = base_public_url(config)if not base:@@ -1049,7 +1011,12 @@ class ShowPageStore:return _page_from_row(row) if row else Nonedef require_access(self, session_id: str, *, user_context: Any = None) -> ShowPage:- """Return a Show Page only when the caller may use its ACL resource."""+ """Return a Show Page only to an Instance Viewer (owner/editor/viewer).++ ``/show`` admission is the Instance role alone, independent of the+ sharing list and of Resource ACL (§3.2): any Viewer enters the Workbench,+ while a signed ``show_page_email`` session never does.+ """session_id = validate_session_id(session_id)context = _resolve_resource_access_context(user_context)@@ -1061,7 +1028,7 @@ class ShowPageStore:)if row is None:raise ShowPageError("This session has no Show Page.", code="show_page_not_found")- self._require_resource_access(conn, session_id, context)+ self._require_resource_access(context)return _page_from_row(row)def require_management(self, session_id: str, *, user_context: Any = None) -> ShowPage:@@ -1095,9 +1062,6 @@ class ShowPageStore:page_request: PageRequest | None,user_context: Any = None,) -> PageResult[ShowPage]:- from storage import resource_access_service-- context = _resolve_resource_access_context(user_context)if visibility is not None and visibility not in VISIBILITIES:raise ShowPageError(f"Unsupported visibility: {visibility}", code="invalid_visibility")statement = select(show_pages)@@ -1128,23 +1092,14 @@ class ShowPageStore:statement = statement.order_by(show_pages.c.updated_at.desc(), show_pages.c.session_id.asc())with self.engine.begin() as conn:rows = conn.execute(statement).mappings().all()- rows = resource_access_service.filter_accessible_resources(- context,- "show_page",- rows,- connection=conn,- )return page_sequence([_page_from_row(row) for row in rows], page_request)@staticmethod- def _require_resource_access(connection, session_id: str, user_context: Any) -> None:- from storage import resource_access_service-- if not resource_access_service.can_use_resource(- user_context,- "show_page",- session_id,- connection=connection,+ def _require_resource_access(user_context: Any) -> None:+ if not (+ user_context is not None+ and user_context.has_role("viewer")+ and user_context.instance_access_source != "show_page_email"):raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")@@ -1208,44 +1163,25 @@ class ShowPageStore:return permissions.resolve_current_instance_ownership()- @classmethod- def _reconcile_resource_policy(- cls,- connection,- session_id: str,- user_context: Any,- ownership: dict[str, Any],- ) -> dict[str, Any]:- from storage import resource_access_service+ @staticmethod+ def _reconcile_resource_policy(ownership: dict[str, Any]) -> dict[str, Any]:+ """Map the instance-ownership fence to a frontend ``ownership_status``.++ §3.2 removed show_page from the Resource ACL, so there is no policy row+ to reconcile: the status is derived from the ownership fence alone and+ ``policy`` is always ``None``. The ``conflict`` status is obsolete with+ the Resource ACL gone — there is no ``policy_organization_id`` to diverge+ from the instance organization.+ """- current_policy = resource_access_service.get_resource_policy(- "show_page",- session_id,- connection=connection,- )- if current_policy is None:- try:- cls._require_project_edit_access(connection, session_id, user_context)- except ShowPageError:- if not user_context.can_use_show_page(session_id):- raise- return {- "status": "unchanged",- "ownership": ownership,- "policy": None,- }- owner_user_id = (- user_context.subject- if user_context.subject and user_context.has_role("editor")- else None- )- return resource_access_service.reconcile_show_page_resource_policy(- connection,- resource_id=session_id,- ownership=ownership,- owner_user_id=owner_user_id,- owner_email=user_context.email,- )+ status = {+ "unmanaged": "unmanaged",+ "personal": "unchanged",+ "organization": "unchanged",+ "organization_pending": "pending",+ "configuration_unavailable": "configuration_unavailable",+ }.get(ownership.get("mode"), "unmanaged")+ return {"status": status, "ownership": ownership, "policy": None}@classmethoddef _existing_page_for_use(@@ -1269,9 +1205,8 @@ class ShowPageStore:)if existing is None:return None- cls._reconcile_resource_policy(connection, session_id, user_context, ownership)cls._require_project_edit_access(connection, session_id, user_context)- cls._require_resource_access(connection, session_id, user_context)+ cls._require_resource_access(user_context)return _page_from_row(existing)def get_for_use(self, session_id: str, *, user_context: Any = None) -> ShowPage:@@ -1314,7 +1249,6 @@ class ShowPageStore:"""Resolve ownership outside SQLite, then reconcile one existing page."""session_id = validate_session_id(session_id)- context = _resolve_resource_access_context(user_context)ownership = self._resolve_instance_ownership()with config_file_lock():with self.engine.begin() as connection:@@ -1328,12 +1262,7 @@ class ShowPageStore:"This session has no Show Page.",code="show_page_not_found",)- return self._reconcile_resource_policy(- connection,- session_id,- context,- ownership,- )+ return self._reconcile_resource_policy(ownership)def ensure(self, session_id: str, *, user_context: Any = None) -> ShowPage:session_id = validate_session_id(session_id)@@ -1367,7 +1296,6 @@ class ShowPageStore:updated_at=page.updated_at,))- self._reconcile_resource_policy(conn, session_id, context, ownership)return pagedef ensure_active(self, session_id: str, *, user_context: Any = None) -> tuple[ShowPage, bool]:@@ -1440,14 +1368,6 @@ class ShowPageStore:"Could not allocate a unique share ID.",code="share_id_allocation_failed",)- reconciliation = self._reconcile_resource_policy(- conn,- session_id,- context,- ownership,- )- if not (created and reconciliation["status"] == "pending"):- self._require_resource_access(conn, session_id, context)return _page_from_row(row), createddef is_archived(self, session_id: str) -> bool:diff --git a/storage/resource_access_service.py b/storage/resource_access_service.pyindex 76c926a11..7ec54763a 100644--- a/storage/resource_access_service.py+++ b/storage/resource_access_service.py@@ -17,7 +17,6 @@ from typing import Any, Iteratorfrom sqlalchemy import selectfrom sqlalchemy.engine import Connection-from config.v2_config import config_file_lockfrom storage.db import get_cached_sqlite_enginefrom storage.models import resource_access_groups, resource_access_policies, state_metafrom vibe.authorization import (@@ -27,25 +26,12 @@ from vibe.authorization import ()-RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})+RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill"})ACCESS_LEVELS = frozenset({"public", "scope", "private"})ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})RESOURCE_USER_CONTEXT_METADATA_KEY = "resource_user_context"RESOURCE_ORGANIZATIONS_META_KEY = "resource_access_organizations"-SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY = "show_page_instance_ownership"HARNESS_ACCESS_FORBIDDEN_CODE = "harness_access_forbidden"-SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE = "configuration_unavailable"--_SHOW_PAGE_OWNERSHIP_MODES = frozenset(- {- "unmanaged",- "personal",- "organization",- "organization_pending",- SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,- }-)-_CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE = object()class ResourceAccessError(ValueError):@@ -91,22 +77,6 @@ def _required_identifier(value: Any, *, code: str) -> str:return cleaned-def _assert_show_page_pairing_current(ownership: Mapping[str, Any]) -> None:- """Reject a reconciliation snapshot that no longer names the current pairing."""-- configured = _configured_show_page_instance()- instance_id = _clean_optional_string(ownership.get("instance_id"))- if (- configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE- or configured is None- or instance_id is None- or configured[0] != instance_id- or ownership.get("mode") not in {"personal", "organization"}- or configured[1] != ownership.get("mode")- ):- raise ResourceAccessError("show_page_pairing_changed")--def _validate_resource_kind(resource_kind: Any) -> str:if resource_kind not in RESOURCE_KINDS:raise ResourceAccessError("invalid_resource_kind")@@ -341,412 +311,6 @@ def _connection(connection: Connection | None) -> Iterator[Connection]:yield active_connection-def _configured_show_page_instance() -> tuple[str, str] | None | object:- try:- from config.v2_config import V2Config-- cloud = V2Config.load().remote_access.vibe_cloud- credentials = cloud.runtime_credentials()- if credentials is None:- return None- if not isinstance(credentials, (tuple, list)) or len(credentials) != 3:- return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE- instance_id = _clean_optional_string(credentials[1])- if instance_id is None or cloud.instance_kind not in {"personal", "organization"}:- return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE- except (- AttributeError,- FileNotFoundError,- IndexError,- KeyError,- OSError,- TypeError,- ValueError,- ):- return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE- return instance_id, cloud.instance_kind---def _configuration_unavailable_ownership() -> dict[str, Any]:- return {- "mode": SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,- "instance_id": None,- "organization_id": None,- "source": "config",- }---def _stored_show_page_instance_ownership(connection: Connection) -> dict[str, Any] | None:- raw_value = connection.execute(- select(state_meta.c.value_json).where(- state_meta.c.key == SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY- )- ).scalar_one_or_none()- try:- payload = json.loads(raw_value) if raw_value else None- except (TypeError, ValueError):- return None- if not isinstance(payload, dict) or payload.get("schema_version") != 1:- return None- instance_id = _clean_optional_string(payload.get("instance_id"))- mode = payload.get("mode")- organization_id = _clean_optional_string(payload.get("organization_id"))- if instance_id is None or mode not in {"personal", "organization"}:- return None- if mode == "organization" and organization_id is None:- return None- if mode == "personal" and organization_id is not None:- return None- return {- "mode": mode,- "instance_id": instance_id,- "organization_id": organization_id,- "source": "stored",- }---def current_show_page_instance_ownership(- *,- connection: Connection | None = None,-) -> dict[str, Any]:- """Return the persisted ownership fence for the exact current pairing."""-- configured = _configured_show_page_instance()- if configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE:- return _configuration_unavailable_ownership()- if configured is None:- return {- "mode": "unmanaged",- "instance_id": None,- "organization_id": None,- "source": "config",- }- instance_id, instance_kind = configured- with _connection(connection) as conn:- stored = _stored_show_page_instance_ownership(conn)- exact_stored = stored if stored and stored["instance_id"] == instance_id else None- if instance_kind == "personal":- return {- "mode": "personal",- "instance_id": instance_id,- "organization_id": None,- "source": "config",- }- if instance_kind == "organization":- if exact_stored and exact_stored["mode"] == "organization":- return exact_stored- return {- "mode": "organization_pending",- "instance_id": instance_id,- "organization_id": None,- "source": "config",- }- if exact_stored is not None:- return exact_stored- return {- "mode": "unmanaged",- "instance_id": instance_id,- "organization_id": None,- "source": "config",- }---def remember_show_page_instance_ownership(- connection: Connection,- ownership: Mapping[str, Any],-) -> dict[str, Any]:- """Persist an authoritative binding only while its exact pairing is current."""-- with config_file_lock():- return _remember_show_page_instance_ownership_locked(connection, ownership)---def _remember_show_page_instance_ownership_locked(- connection: Connection,- ownership: Mapping[str, Any],-) -> dict[str, Any]:- """Implement ownership persistence while the pairing lock is held."""-- configured = _configured_show_page_instance()- instance_id = _clean_optional_string(ownership.get("instance_id"))- mode = ownership.get("mode")- organization_id = _clean_optional_string(ownership.get("organization_id"))- if (- configured is None- or configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE- or instance_id != configured[0]- or mode not in {"personal", "organization"}- or configured[1] != mode- or (mode == "organization") != bool(organization_id)- ):- return current_show_page_instance_ownership(connection=connection)- payload = {- "schema_version": 1,- "instance_id": instance_id,- "mode": mode,- "organization_id": organization_id,- }- connection.execute(- state_meta.delete().where(state_meta.c.key == SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY)- )- connection.execute(- state_meta.insert().values(- key=SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY,- value_json=json.dumps(payload, separators=(",", ":")),- updated_at=_utc_now_iso(),- )- )- return {**payload, "source": str(ownership.get("source") or "live")}---def reconcile_show_page_resource_policy(- connection: Connection,- *,- resource_id: str,- ownership: Mapping[str, Any],- owner_user_id: str | None,- owner_email: str | None = None,-) -> dict[str, Any]:- """Reconcile one Show Page policy under the persisted pairing lock."""-- with config_file_lock():- return _reconcile_show_page_resource_policy_locked(- connection,- resource_id=resource_id,- ownership=ownership,- owner_user_id=owner_user_id,- owner_email=owner_email,- )---def _reconcile_show_page_resource_policy_locked(- connection: Connection,- *,- resource_id: str,- ownership: Mapping[str, Any],- owner_user_id: str | None,- owner_email: str | None = None,-) -> dict[str, Any]:- """Reconcile one Show Page policy without changing either access axis."""-- identifier = _required_identifier(resource_id, code="invalid_resource_id")- mode = ownership.get("mode")- if mode not in _SHOW_PAGE_OWNERSHIP_MODES:- raise ResourceAccessError("invalid_show_page_ownership")- if mode in {"personal", "organization"}:- _assert_show_page_pairing_current(ownership)- fence = _remember_show_page_instance_ownership_locked(connection, ownership)- else:- fence = current_show_page_instance_ownership(connection=connection)- mode = fence["mode"]- policy = _policy_row(connection, "show_page", identifier)- policy_organization = _clean_optional_string(- policy.get("organization_id") if policy else None- )-- if mode == "unmanaged":- status = "unmanaged"- elif mode == "organization_pending":- status = "pending"- elif mode == SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE:- status = SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE- elif mode == "personal":- if policy is None:- _assert_show_page_pairing_current(fence)- policy = ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=identifier,- organization_id=None,- owner_user_id=owner_user_id,- owner_email=owner_email,- access_level="private",- created_by_user_id=owner_user_id,- updated_by_user_id=owner_user_id,- )- status = "created"- else:- status = "unchanged" if policy_organization is None else "conflict"- else:- organization_id = _required_identifier(- fence.get("organization_id"), code="invalid_organization_id"- )- if policy is None:- _assert_show_page_pairing_current(fence)- policy = ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=identifier,- organization_id=organization_id,- owner_user_id=owner_user_id,- owner_email=owner_email,- access_level="private",- created_by_user_id=owner_user_id,- updated_by_user_id=owner_user_id,- )- status = "created"- elif policy_organization is None:- _assert_show_page_pairing_current(fence)- connection.execute(- resource_access_policies.update()- .where(resource_access_policies.c.resource_kind == "show_page")- .where(resource_access_policies.c.resource_id == identifier)- .values(organization_id=organization_id)- )- connection.execute(- resource_access_groups.update()- .where(resource_access_groups.c.resource_kind == "show_page")- .where(resource_access_groups.c.resource_id == identifier)- .values(organization_id=organization_id)- )- remember_resource_organization(connection, organization_id)- policy = _policy_row(connection, "show_page", identifier)- status = "adopted"- else:- status = (- "unchanged" if policy_organization == organization_id else "conflict"- )- serialized = _serialize_policy(connection, policy) if policy else None- return {"status": status, "ownership": fence, "policy": serialized}---def _show_page_policy_matches_instance_ownership(- ownership: Mapping[str, Any],- policy: Mapping[str, Any] | None,-) -> bool:- mode = ownership.get("mode")- if mode == "unmanaged":- return True- if mode in {- "organization_pending",- SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,- }:- return False- policy_organization = _clean_optional_string(- policy.get("organization_id") if policy else None- )- if mode == "personal":- return policy_organization is None- return bool(- mode == "organization"- and policy_organization- and policy_organization == _clean_optional_string(ownership.get("organization_id"))- )---def _resolve_authoritative_show_page_ownership(- ownership: Mapping[str, Any],-) -> dict[str, Any]:- """Resolve a pending organization fence using the paired Permissions projection."""-- if ownership.get("mode") != "organization_pending":- return dict(ownership)- try:- from vibe import permissions-- resolved = permissions.resolve_current_instance_ownership()- except (- AttributeError,- FileNotFoundError,- OSError,- TypeError,- ValueError,- ):- return dict(ownership)- if resolved.get("mode") == "organization":- return dict(resolved)- return dict(ownership)---def _show_page_authorization_ownership(- connection: Connection | None,- ownership: Mapping[str, Any] | None = None,-) -> dict[str, Any]:- """Resolve the pairing fence before the authorization transaction reads state."""-- if ownership is not None:- return _resolve_authoritative_show_page_ownership(dict(ownership))-- # With no caller-owned connection, finish the small persisted-fence read- # before resolving the potentially slow authoritative organization lookup.- if connection is None:- return _resolve_authoritative_show_page_ownership(- current_show_page_instance_ownership()- )-- configured = _configured_show_page_instance()- if configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE:- return _configuration_unavailable_ownership()- if configured is None:- return {- "mode": "unmanaged",- "instance_id": None,- "organization_id": None,- "source": "config",- }- instance_id, instance_kind = configured- if instance_kind == "personal":- return {- "mode": "personal",- "instance_id": instance_id,- "organization_id": None,- "source": "config",- }-- # A supplied Connection may contain an uncommitted legacy policy. Resolve- # the organization fence before its first SELECT so reconciliation can- # safely write through that same transaction.- provisional = {- "mode": "organization_pending",- "instance_id": instance_id,- "organization_id": None,- "source": "config",- }- resolved = _resolve_authoritative_show_page_ownership(provisional)- if resolved.get("mode") == "organization":- return resolved- return current_show_page_instance_ownership(connection=connection)---def _show_page_authorization_snapshot(- connection: Connection,- resource_id: str,- *,- ownership: Mapping[str, Any] | None = None,-) -> tuple[dict[str, Any], dict[str, Any] | None, list[str]]:- """Load one policy after adopting a legacy null-organization shape when safe."""-- identifier = _required_identifier(resource_id, code="invalid_resource_id")- current_ownership = dict(- ownership- if ownership is not None- else _show_page_authorization_ownership(connection)- )- policy = _policy_row(connection, "show_page", identifier)- policy_organization = _clean_optional_string(- policy.get("organization_id") if policy else None- )- if (- policy is not None- and policy_organization is None- and current_ownership.get("mode") in {"organization", "organization_pending"}- ):- try:- reconciliation = reconcile_show_page_resource_policy(- connection,- resource_id=identifier,- ownership=current_ownership,- owner_user_id=_clean_optional_string(policy.get("owner_user_id")),- owner_email=_clean_optional_string(policy.get("owner_email"), limit=320),- )- except ResourceAccessError:- return _configuration_unavailable_ownership(), policy, []- current_ownership = dict(reconciliation["ownership"])- policy = reconciliation["policy"]- groups = _policy_groups(connection, "show_page", identifier) if policy else []- return current_ownership, policy, groups--def _stored_resource_organizations(connection: Connection) -> set[str]:raw_value = connection.execute(select(state_meta.c.value_json).where(state_meta.c.key == RESOURCE_ORGANIZATIONS_META_KEY)@@ -806,6 +370,7 @@ def list_resource_organization_ids(*, connection: Connection | None = None) -> lstr(row.organization_id)for row in conn.execute(select(resource_access_policies.c.organization_id)+ .where(resource_access_policies.c.resource_kind.in_(RESOURCE_KINDS)).where(resource_access_policies.c.organization_id.is_not(None)).distinct())@@ -871,6 +436,11 @@ def list_resource_policies()if kind is not None:statement = statement.where(resource_access_policies.c.resource_kind == kind)+ else:+ # Unscoped listings exclude retired resource kinds so preserved legacy+ # rows (e.g. show_page policies written by older releases) degrade+ # silently instead of surfacing through sync or onboarding queries.+ statement = statement.where(resource_access_policies.c.resource_kind.in_(RESOURCE_KINDS))if organization is not None:statement = statement.where(resource_access_policies.c.organization_id == organization)if owner is not None:@@ -995,8 +565,6 @@ def _policy_allows(resource_id: str,policy: Mapping[str, Any] | None,group_ids: Sequence[str],- *,- show_page_ownership: Mapping[str, Any] | None = None,) -> bool:if context.is_instance_owner:return True@@ -1007,28 +575,6 @@ def _policy_allows(if resource_kind in {"skill", "vault_secret"}:if context.is_remote and context.is_active_organization_member and context.has_role("editor"):return True- # A signed Show Page email session carries an exact resource entitlement.- # It remains valid even when the local instance pairing cannot be reloaded;- # the broader instance/organization policy fence below must not revoke that- # independent Limited-link flow.- if resource_kind == "show_page" and context.can_use_show_page(resource_id):- return True- if (- resource_kind == "show_page"- and show_page_ownership is not None- and show_page_ownership.get("mode")- == SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE- ):- return False- if (- resource_kind == "show_page"- and show_page_ownership is not None- and not _show_page_policy_matches_instance_ownership(- show_page_ownership,- policy,- )- ):- return Falseif context.instance_access_source == "show_page_email":return Falseif not context.can_use_resource(resource_kind):@@ -1098,18 +644,6 @@ def _policy_allows_owner_control()-def _policy_allows_show_page_access_management(- context: ResourceUserContext,- policy: Mapping[str, Any] | None,-) -> bool:- """Allow the Instance Owner or page owner represented by the ACL."""- if _policy_allows_owner_control(context, policy):- return True- if policy is None or policy.get("resource_kind") != "show_page":- return False- return _policy_allows_management(context, policy)--def can_use_resource_policy_snapshot(user_context: ResourceUserContext | Mapping[str, Any] | None,policy: Mapping[str, Any] | None,@@ -1155,29 +689,15 @@ def can_use_resource(context = _as_context(user_context)kind = _validate_resource_kind(resource_kind)identifier = _required_identifier(resource_id, code="invalid_resource_id")- show_page_ownership = (- _show_page_authorization_ownership(connection)- if kind == "show_page"- else None- )with _connection(connection) as conn:- if kind == "show_page":- ownership, policy, groups = _show_page_authorization_snapshot(- conn,- identifier,- ownership=show_page_ownership,- )- else:- policy = _policy_row(conn, kind, identifier)- groups = _policy_groups(conn, kind, identifier) if policy else []- ownership = None+ policy = _policy_row(conn, kind, identifier)+ groups = _policy_groups(conn, kind, identifier) if policy else []return _policy_allows(context,kind,identifier,policy,groups,- show_page_ownership=ownership,)@@ -1191,61 +711,11 @@ def can_manage_resource_acl(context = _as_context(user_context)kind = _validate_resource_kind(resource_kind)identifier = _required_identifier(resource_id, code="invalid_resource_id")- show_page_ownership = (- _show_page_authorization_ownership(connection)- if kind == "show_page"- else None- )with _connection(connection) as conn:- if kind == "show_page":- ownership, policy, _groups = _show_page_authorization_snapshot(- conn,- identifier,- ownership=show_page_ownership,- )- else:- ownership = None- policy = _policy_row(conn, kind, identifier)- if (- kind == "show_page"- and not context.is_instance_owner- and not _show_page_policy_matches_instance_ownership(- ownership or {},- policy,- )- ):- return False+ policy = _policy_row(conn, kind, identifier)return _policy_allows_management(context, policy)-def can_manage_show_page_access(- user_context: ResourceUserContext | Mapping[str, Any] | None,- resource_id: str,- *,- connection: Connection | None = None,-) -> bool:- """Return whether the caller may manage a Show Page audience or narrow sharing."""-- context = _as_context(user_context)- identifier = _required_identifier(resource_id, code="invalid_resource_id")- show_page_ownership = _show_page_authorization_ownership(connection)- with _connection(connection) as conn:- ownership, policy, _groups = _show_page_authorization_snapshot(- conn,- identifier,- ownership=show_page_ownership,- )- if (- not context.is_instance_owner- and not _show_page_policy_matches_instance_ownership(- ownership,- policy,- )- ):- return False- return _policy_allows_show_page_access_management(context, policy)--def can_control_resource_sharing(user_context: ResourceUserContext | Mapping[str, Any] | None,resource_kind: str,@@ -1258,30 +728,8 @@ def can_control_resource_sharing(context = _as_context(user_context)kind = _validate_resource_kind(resource_kind)identifier = _required_identifier(resource_id, code="invalid_resource_id")- show_page_ownership = (- _show_page_authorization_ownership(connection)- if kind == "show_page"- else None- )with _connection(connection) as conn:- if kind == "show_page":- ownership, policy, _groups = _show_page_authorization_snapshot(- conn,- identifier,- ownership=show_page_ownership,- )- else:- ownership = None- policy = _policy_row(conn, kind, identifier)- if (- kind == "show_page"- and not context.is_instance_owner- and not _show_page_policy_matches_instance_ownership(- ownership or {},- policy,- )- ):- return False+ policy = _policy_row(conn, kind, identifier)return _policy_allows_owner_control(context, policy)@@ -1320,11 +768,6 @@ def filter_accessible_resources(identifiers = [identifier for _, identifier in candidates if identifier is not None]if not identifiers:return []- ownership = (- _show_page_authorization_ownership(connection)- if kind == "show_page"- else None- )with _connection(connection) as conn:policy_rows = conn.execute(select(resource_access_policies)@@ -1336,24 +779,6 @@ def filter_accessible_resources(identifier: _policy_groups(conn, kind, identifier)for identifier in policies}- if kind == "show_page":- if ownership and ownership.get("mode") == "organization":- for identifier, policy in list(policies.items()):- if _clean_optional_string(policy.get("organization_id")) is not None:- continue- try:- reconciliation = reconcile_show_page_resource_policy(- conn,- resource_id=identifier,- ownership=ownership,- owner_user_id=_clean_optional_string(policy.get("owner_user_id")),- owner_email=_clean_optional_string(policy.get("owner_email"), limit=320),- )- except ResourceAccessError:- ownership = _configuration_unavailable_ownership()- break- policies[identifier] = reconciliation["policy"] or policy- groups[identifier] = _policy_groups(conn, kind, identifier)return [rowfor row, identifier in candidates@@ -1364,7 +789,6 @@ def filter_accessible_resources(identifier,policies.get(identifier),groups.get(identifier, []),- show_page_ownership=ownership,)]diff --git a/tests/scenario_harness/permissions.py b/tests/scenario_harness/permissions.pyindex 88568a5d1..26cfcaeeb 100644--- a/tests/scenario_harness/permissions.py+++ b/tests/scenario_harness/permissions.py@@ -153,9 +153,9 @@ class PermissionsScenarioHarness:def _resource() -> dict:return {"instance_id": "inst-current",- "resource_kind": "show_page",+ "resource_kind": "agent","resource_id": "ses-resource",- "display_name": "Scenario Show Page",+ "display_name": "Scenario Agent","owner_user_id": "subject-owner","access": {"access_level": "private",@@ -189,7 +189,7 @@ class PermissionsScenarioHarness:if method == "GET" and path.endswith("/permissions"):return _BackendResponse(200, self.projection)if method == "GET" and path.endswith(- "/permissions/resources/show_page/ses-resource/access"+ "/permissions/resources/agent/ses-resource/access"):return _BackendResponse(200, {"resource": self.resource})if self.projection["instance"]["permission_authority"] == "cloud":@@ -243,7 +243,7 @@ class PermissionsScenarioHarness:},)if method == "PUT" and path.endswith(- "/permissions/resources/show_page/ses-resource/access"+ "/permissions/resources/agent/ses-resource/access"):current = self.resource["access"]["revision"]if payload.get("if_match_revision") != current:diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 9a4a4df06..bd88b67c9 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -170,7 +170,7 @@ scenarios:backend: webtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_remote_web_oauth_cold_launch_retry_is_single_owner- id: AUTH-SETUP-401- name: Exact-email Show Page login stays confined to its signed page+ name: Exact-email Show Page login stays a /p-only reader and never enters /showstatus: coveredkind: authorizationlayer: scenariodiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex aa1e8b703..cb113d2b3 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -85,28 +85,22 @@ class ShowPageEmailAccessScenarioTests(unittest.TestCase):exact = self.harness.get(handshake["next_path"])other = self.harness.get("/show/session-two/__show/me")api = self.harness.get("/api/show-pages")- self.assertEqual(exact.status_code, 200)- self.assertEqual(exact.get_json(), {"authenticated": False, "canAnnotate": False})+ # §3.2: a show_page_email grant is a /p-only read visitor — it never+ # enters the /show surface, even for its own signed page.+ self.assertEqual(exact.status_code, 403)self.assertEqual(other.status_code, 403)self.assertEqual(other.get_json()["error"], "show_page_access_forbidden")self.assertEqual(api.status_code, 403)self.harness.seed_broader_session()- existing_session_handshake = self.harness.begin_login("session-one")- existing_session_callback = self.harness.complete_login(- existing_session_handshake,- instance_role="editor",- access_source="email",- )- self.assertEqual(existing_session_callback.status_code, 302)- self.assertEqual(- existing_session_callback.headers["Location"],- existing_session_handshake["next_path"],- )+ # §3.2: a real Instance Editor session (email-sourced, not a show_page+ # grant) enters /show directly, with no login handshake and independent+ # of any show_page entitlement.self.assertEqual(- self.harness.get(existing_session_handshake["next_path"]).status_code,+ self.harness.get("/show/session-one/__show/me").status_code,200,)+ self.assertTrue(self.harness.get("/show/session-one/__show/me").get_json()["authenticated"])def test_limited_show_identity_closed_loop_installs_guest_lease(monkeypatch, tmp_path):diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yamlindex fa0df96ac..dab204469 100644--- a/tests/scenarios/permissions/catalog.yaml+++ b/tests/scenarios/permissions/catalog.yaml@@ -102,11 +102,20 @@ scenarios:when: Registered routes and frontend sources are inventoriedthen: No Management OAuth proxy or embedded Organization route remains- id: PERMISSIONS-011- name: Show Page Workspace access round-trips through exact-instance Resource ACL+ name: Resource ACL round-trips through exact-instance boundarystatus: coveredkind: mutationlayer: scenario- test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_011_show_page_resource_acl_round_trip_and_conflict- given: A paired Instance Owner has a canonical private Show Page Resource ACL+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_011_resource_acl_round_trip_and_conflict+ given: A paired Instance Owner has a canonical private agent Resource ACLwhen: The owner saves Selected groups and then submits a stale revisionthen: The canonical policy round-trips without a browser target field and the stale write changes nothing+ - id: PERMISSIONS-012+ name: Show Page Resource ACL kind is retired+ status: covered+ kind: retirement+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_012_show_page_resource_kind_is_retired+ given: A paired Instance Owner calls the retired show_page Resource ACL endpoint+ when: The local boundary validates the resource kind before any Backend contact+ then: Both read and write are rejected as invalid_resource_kind with no Backend requestdiff --git a/tests/scenarios/permissions/observations.yaml b/tests/scenarios/permissions/observations.yamlindex 0caae1fa4..3b050d37e 100644--- a/tests/scenarios/permissions/observations.yaml+++ b/tests/scenarios/permissions/observations.yaml@@ -33,10 +33,11 @@ observations:source: issue_contractrelated_scenarios:- PERMISSIONS-011- summary: Show Page Workspace access is the exact-current-instance Resource ACL while link and Limited-email access remain local and independent.- previous_assumption: The Show Page access panel could derive Organization ownership from a browser claim or a hidden Cloud-management session.- observed_behavior: The local service resolves pairing ownership, proxies canonical Resource ACL reads and writes, and preserves stale drafts on revision conflict.+ - PERMISSIONS-012+ summary: Resource ACL is bound to the exact-current-instance credential and covers agent / vault_secret / skill only; Show Page sharing is the local single-axis /p model with no Resource ACL row.+ previous_assumption: Show Page Workspace access was a show_page Resource ACL kind that the access panel could derive Organization ownership for from a browser claim.+ observed_behavior: The local service resolves pairing ownership, proxies canonical Resource ACL reads and writes for the remaining kinds, preserves stale drafts on revision conflict, and rejects the retired show_page kind before Backend contact.required_updates:- bind every Resource ACL request to the paired instance and strip the browser match field before Backend contact- - preserve local link visibility and Limited-email grants as separate policy dimensions- - treat ownership uncertainty or mismatch as fail-closed without overwriting an existing policy+ - keep Show Page link visibility and Limited-email grants as a separate local policy dimension with no show_page Resource ACL+ - reject the retired show_page resource kind as invalid_request without any Backend contactdiff --git a/tests/scenarios/permissions/test_permissions_scenarios.py b/tests/scenarios/permissions/test_permissions_scenarios.pyindex dea238d70..efaf1b5dd 100644--- a/tests/scenarios/permissions/test_permissions_scenarios.py+++ b/tests/scenarios/permissions/test_permissions_scenarios.py@@ -224,10 +224,10 @@ def test_permissions_010_legacy_management_surfaces_are_absent() -> None:assert "ShowPageSharingSettings" in source-def test_permissions_011_show_page_resource_acl_round_trip_and_conflict(harness) -> None:+def test_permissions_011_resource_acl_round_trip_and_conflict(harness) -> None:"""Scenario: PERMISSIONS-011."""client = harness.local_client()- resource_path = "/api/permissions/resources/show_page/ses-resource/access"+ resource_path = "/api/permissions/resources/agent/ses-resource/access"initial = client.get(resource_path)write = client.put(@@ -286,3 +286,30 @@ def test_permissions_011_show_page_resource_acl_round_trip_and_conflict(harness)"current_revision": 1,}assert harness.resource == before_conflict+++def test_permissions_012_show_page_resource_kind_is_retired(harness) -> None:+ """Scenario: PERMISSIONS-012."""+ client = harness.local_client()+ resource_path = "/api/permissions/resources/show_page/ses-resource/access"+ before = len(harness.backend_requests)++ read = client.get(resource_path)+ write = client.put(+ resource_path,+ json={+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 0,+ "if_match_instance_id": "inst-current",+ },+ headers=harness.csrf(client),+ )++ # §3.2 retired show_page from the Resource ACL: the local boundary rejects+ # the retired kind as an invalid resource before any Backend contact.+ assert read.status_code == 422+ assert read.get_json() == {"ok": False, "error": "invalid_resource_kind"}+ assert write.status_code == 422+ assert write.get_json() == {"ok": False, "error": "invalid_resource_kind"}+ assert len(harness.backend_requests) == beforediff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.pyindex 1c7d9dad3..6cf739a8f 100644--- a/tests/test_instance_authorization.py+++ b/tests/test_instance_authorization.py@@ -83,6 +83,7 @@ def test_show_page_email_context_is_exactly_page_scoped() -> None:)assert not context.can_read_instanceassert context.capability_projection()["can_read_instance"] is False+ assert context.capability_projection()["can_use_show_pages"] is Falseassert context.can_use_show_page("session-one")assert not context.can_use_show_page("session-two")assert not context.can_chatdiff --git a/tests/test_permissions.py b/tests/test_permissions.pyindex fe96ec863..3add1310c 100644--- a/tests/test_permissions.py+++ b/tests/test_permissions.py@@ -205,8 +205,8 @@ def _complete_projection(instance_id: str = "inst-123") -> dict:def _resource(instance_id: str = "inst-123",- resource_kind: str = "show_page",- resource_id: str = "page-1",+ resource_kind: str = "agent",+ resource_id: str = "agent-1",*,revision: int = 4,) -> dict:@@ -214,7 +214,7 @@ def _resource("instance_id": instance_id,"resource_kind": resource_kind,"resource_id": resource_id,- "display_name": "Page",+ "display_name": "Agent","owner_user_id": "owner-1","access": {"access_level": "scope",@@ -459,10 +459,10 @@ def test_resource_access_client_binds_identity_and_strips_local_pairing_precondimonkeypatch.setattr(permissions.requests, "request", request)- read = permissions.get_resource_access("show_page", "page-1", _config())+ read = permissions.get_resource_access("agent", "agent-1", _config())written = permissions.update_resource_access(- "show_page",- "page-1",+ "agent",+ "agent-1",{"access_level": "scope","group_ids": ["group-1"],@@ -474,7 +474,7 @@ def test_resource_access_client_binds_identity_and_strips_local_pairing_precondiexpected_url = ("https://backend.example/api/v1/instances/inst-123/permissions/"- "resources/show_page/page-1/access"+ "resources/agent/agent-1/access")assert read == {"resource": _resource(revision=4)}assert written == {"ok": True, "resource": _resource(revision=5)}@@ -492,12 +492,50 @@ def test_resource_access_client_binds_identity_and_strips_local_pairing_precondi][email protected]("operation", ["get", "put"])+def test_resource_access_client_rejects_retired_kind_before_backend(+ monkeypatch,+ operation,+) -> None:+ """§3.2 retired show_page from the Resource ACL: the retired kind fails+ client-side as an invalid resource before any Backend request is made."""+ called = False++ def request(*_args, **_kwargs):+ nonlocal called+ called = True+ return _Response(200, {"resource": _resource()})++ monkeypatch.setattr(permissions.requests, "request", request)++ with pytest.raises(+ permissions.PermissionsInvalidRequestError,+ match="invalid_resource_kind",+ ):+ if operation == "get":+ permissions.get_resource_access("show_page", "page-1", _config())+ else:+ permissions.update_resource_access(+ "show_page",+ "page-1",+ {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ _config(),+ )++ assert called is False++@pytest.mark.parametrize(("field", "value"),[("instance_id", "inst-other"),- ("resource_kind", "agent"),- ("resource_id", "page-other"),+ ("resource_kind", "vault_secret"),+ ("resource_id", "agent-other"),],)def test_resource_access_client_rejects_response_identity_mismatch(@@ -517,7 +555,7 @@ def test_resource_access_client_rejects_response_identity_mismatch(permissions.PermissionsInvalidResponseError,match="permissions_resource_mismatch",):- permissions.get_resource_access("show_page", "page-1", _config())+ permissions.get_resource_access("agent", "agent-1", _config())@pytest.mark.parametrize("operation", ["get", "put"])@@ -553,11 +591,11 @@ def test_resource_access_rechecks_pairing_after_response_validation(match="permissions_pairing_changed",):if operation == "get":- permissions.get_resource_access("show_page", "page-1", config)+ permissions.get_resource_access("agent", "agent-1", config)else:permissions.update_resource_access(- "show_page",- "page-1",+ "agent",+ "agent-1",{"access_level": "scope","group_ids": ["group-1"],@@ -2291,13 +2329,13 @@ def test_permissions_http_policy_allows_viewer_reads_but_owner_only_mutations())assert (http_authorization_policy(- "GET", "/api/permissions/resources/show_page/page-1/access"+ "GET", "/api/permissions/resources/agent/agent-1/access").minimum_role== "viewer")assert (http_authorization_policy(- "PUT", "/api/permissions/resources/show_page/page-1/access"+ "PUT", "/api/permissions/resources/agent/agent-1/access").minimum_role== "owner")@@ -2488,9 +2526,9 @@ def test_resource_access_same_origin_routes_forward_exact_identity_and_conflict(monkeypatch.setattr(permissions, "get_resource_access", get_resource)monkeypatch.setattr(permissions, "update_resource_access", update_resource)- read = client.get("/api/permissions/resources/show_page/page-1/access")+ read = client.get("/api/permissions/resources/agent/agent-1/access")write = client.put(- "/api/permissions/resources/show_page/page-1/access",+ "/api/permissions/resources/agent/agent-1/access",json={"access_level": "scope","group_ids": ["group-1"],@@ -2502,7 +2540,7 @@ def test_resource_access_same_origin_routes_forward_exact_identity_and_conflict(assert read.status_code == 200assert read.headers["Cache-Control"] == "private, no-store"- assert read.get_json()["resource"]["resource_id"] == "page-1"+ assert read.get_json()["resource"]["resource_id"] == "agent-1"assert write.status_code == 409assert write.get_json() == {"ok": False,@@ -2510,11 +2548,11 @@ def test_resource_access_same_origin_routes_forward_exact_identity_and_conflict("current_revision": 7,}assert captured == [- ("GET", "show_page", "page-1", None),+ ("GET", "agent", "agent-1", None),("PUT",- "show_page",- "page-1",+ "agent",+ "agent-1",{"access_level": "scope","group_ids": ["group-1"],@@ -2568,7 +2606,7 @@ def test_resource_access_same_origin_route_rejects_invalid_payload_before_backenmonkeypatch.setattr(permissions, "update_resource_access", update_resource)client = app.test_client()response = client.put(- "/api/permissions/resources/show_page/page-1/access",+ "/api/permissions/resources/agent/agent-1/access",json=payload,headers=csrf_headers(client),)@@ -2603,14 +2641,14 @@ def test_resource_access_route_rejects_page_scoped_guest_before_backend("vibe_instance_id": config.remote_access.vibe_cloud.instance_id,"vibe_instance_role": "viewer","vibe_instance_access_source": "show_page_email",- "vibe_show_page_id": "page-1",+ "vibe_show_page_id": "agent-1",},),domain="alex.avibe.bot",)response = client.get(- "/api/permissions/resources/show_page/page-1/access",+ "/api/permissions/resources/agent/agent-1/access",base_url="https://alex.avibe.bot",environ_base=remote_peer(),)@@ -2636,7 +2674,7 @@ def test_resource_access_route_surfaces_cloud_authority_failure(monkeypatch) ->)client = app.test_client()response = client.put(- "/api/permissions/resources/show_page/page-1/access",+ "/api/permissions/resources/agent/agent-1/access",json={"access_level": "private","group_ids": [],diff --git a/tests/test_remote_resource_acl_sync.py b/tests/test_remote_resource_acl_sync.pyindex e98747bbb..628edd64c 100644--- a/tests/test_remote_resource_acl_sync.py+++ b/tests/test_remote_resource_acl_sync.py@@ -3,15 +3,13 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any-from sqlalchemy import update-from config import pathsfrom config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Configfrom core.services.skills import skill_resource_idfrom storage import resource_access_servicefrom storage.db import get_cached_sqlite_enginefrom storage.migrations import run_migrations-from storage.models import agent_sessions, agents, show_pages, vault_secrets+from storage.models import agents, vault_secretsfrom vibe import remote_access@@ -88,7 +86,6 @@ def _seed_named_resources() -> dict[str, str]:project_dir=None,name="release-notes",),- "show_page": "ses-safe-name",}with engine.begin() as connection:connection.execute(@@ -127,34 +124,6 @@ def _seed_named_resources() -> dict[str, str]:updated_at=created_at,))- connection.execute(- agent_sessions.insert().values(- id=resource_ids["show_page"],- scope_id=None,- agent_backend="codex",- agent_variant="default",- session_anchor="private-show-anchor",- workdir="/private/show/workspace",- native_session_id="private-native-session",- title="Quarterly Results",- status="active",- metadata_json='{"execution_output":"private-show-output"}',- created_at=created_at,- updated_at=created_at,- last_active_at=created_at,- )- )- connection.execute(- show_pages.insert().values(- session_id=resource_ids["show_page"],- access_mode="private",- access_revision=0,- share_id=None,- offline_at=None,- created_at=created_at,- updated_at=created_at,- )- )for resource_kind, resource_id in resource_ids.items():resource_access_service.ensure_resource_policy(connection,@@ -175,11 +144,10 @@ def test_local_descriptors_resolve_all_resource_names_without_content() -> None:descriptors = remote_access._local_policy_resource_descriptors("org-1")by_kind = {descriptor["resource_kind"]: descriptor for descriptor in descriptors}- assert set(by_kind) == {"agent", "vault_secret", "skill", "show_page"}+ assert set(by_kind) == {"agent", "vault_secret", "skill"}assert by_kind["agent"]["display_name"] == "Research Agent"assert by_kind["vault_secret"]["display_name"] == "PRODUCTION_API_KEY"assert by_kind["skill"]["display_name"] == "release-notes"- assert by_kind["show_page"]["display_name"] == "Quarterly Results"allowed_descriptor_fields = {"resource_id","resource_kind",@@ -209,72 +177,10 @@ def test_local_descriptors_resolve_all_resource_names_without_content() -> None:"private-vault-wrap","private-vault-description","private.example",- "private-show-anchor",- "/private/show/workspace",- "private-native-session",- "private-show-output",):assert forbidden not in serialized-def test_local_descriptor_title_revision_and_safe_fallback() -> None:- resource_ids = _seed_named_resources()- first = {- item["resource_kind"]: item- for item in remote_access._local_policy_resource_descriptors("org-1")- }["show_page"]- engine = get_cached_sqlite_engine()- with engine.begin() as connection:- connection.execute(- update(agent_sessions)- .where(agent_sessions.c.id == resource_ids["show_page"])- .values(- title="Executive Overview",- updated_at="2026-07-27T20:00:00.000002+00:00",- )- )-- renamed = {- item["resource_kind"]: item- for item in remote_access._local_policy_resource_descriptors("org-1")- }["show_page"]- assert renamed["display_name"] == "Executive Overview"- assert renamed["metadata_revision"] > first["metadata_revision"]-- with engine.begin() as connection:- connection.execute(- update(agent_sessions)- .where(agent_sessions.c.id == resource_ids["show_page"])- .values(- title="Q3 / Launch: Ops",- updated_at="2026-07-27T20:00:00.000003+00:00",- )- )- separated = {- item["resource_kind"]: item- for item in remote_access._local_policy_resource_descriptors("org-1")- }["show_page"]- assert separated["display_name"] == "Q3 / Launch: Ops"- assert separated["metadata_revision"] > renamed["metadata_revision"]-- with engine.begin() as connection:- connection.execute(- update(agent_sessions)- .where(agent_sessions.c.id == resource_ids["show_page"])- .values(- title="Quarterly\nResults",- updated_at="2026-07-27T20:00:00.000004+00:00",- )- )- unsafe = {- item["resource_kind"]: item- for item in remote_access._local_policy_resource_descriptors("org-1")- }["show_page"]- assert unsafe["display_name"] == resource_ids["show_page"]- assert unsafe["metadata_revision"] > separated["metadata_revision"]- assert "Quarterly\nResults" not in repr(unsafe)--def test_local_descriptors_omit_missing_source_rows() -> None:paths.ensure_data_dirs()run_migrations()@@ -284,7 +190,6 @@ def test_local_descriptors_omit_missing_source_rows() -> None:("agent", "missing-agent"),("vault_secret", "missing-vault"),("skill", "missing-skill"),- ("show_page", "missing-show-page"),):resource_access_service.ensure_resource_policy(connection,@@ -501,7 +406,6 @@ def test_applied_acl_changes_publish_one_authorization_change_for_all_resource_c"agent": "agent-cache-revocation","skill": "skill-cache-revocation","vault_secret": "vault-cache-revocation",- "show_page": "show-cache-revocation",}with engine.begin() as connection:for resource_kind, resource_id in resource_ids.items():@@ -559,81 +463,18 @@ def test_applied_acl_changes_publish_one_authorization_change_for_all_resource_c)assert result["ok"] is True- assert result["applied"] == 4+ assert result["applied"] == 3assert events == [("authorization.changed",{"project_ids": [],- "resource_kinds": ["agent", "show_page", "skill", "vault_secret"],+ "resource_kinds": ["agent", "skill", "vault_secret"],},)]-def test_show_page_acl_widening_publishes_authorization_change(monkeypatch) -> None:- paths.ensure_data_dirs()- run_migrations()- engine = get_cached_sqlite_engine()- with engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="show-page-widening",- organization_id="org-1",- owner_user_id="owner-1",- access_level="private",- policy_revision=1,- last_applied_control_plane_revision=1,- )- monkeypatch.setattr(- remote_access,- "publish_resource_index",- lambda *_args, **_kwargs: {"organization_id": "org-1", "resources": []},- )- monkeypatch.setattr(- remote_access,- "pull_resource_acl_intents",- lambda *_args, **_kwargs: {- "organization_id": "org-1",- "intents": [- {- "resource_kind": "show_page",- "resource_id": "show-page-widening",- "revision": 2,- "access_level": "public",- "group_ids": [],- }- ],- },- )- monkeypatch.setattr(- remote_access,- "acknowledge_resource_acl_intent",- lambda *_args, **_kwargs: {},- )- events: list[tuple[str, dict[str, Any]]] = []- monkeypatch.setattr(- "vibe.sse_broker.broker.publish",- lambda event_type, data: events.append((event_type, data)),- )-- result = remote_access._sync_one_organization(- _config(),- organization_id="org-1",- resources=[],- )-- assert result["ok"] is True- assert result["applied"] == 1- assert events == [- (- "authorization.changed",- {"project_ids": [], "resource_kinds": ["show_page"]},- )- ]--def test_transient_apply_failure_leaves_intent_unacknowledged(monkeypatch) -> None:_seed_policy()config = _config()diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.pyindex 0ce5e932a..2c0b20f95 100644--- a/tests/test_resource_access_service.py+++ b/tests/test_resource_access_service.py@@ -6,7 +6,7 @@ from config.v2_config import V2Configfrom storage import resource_access_servicefrom storage.db import create_sqlite_enginefrom storage.migrations import run_migrations-from storage.models import state_meta+from storage.models import resource_access_policiesfrom vibe import permissions@@ -87,299 +87,148 @@ def test_resource_acl_is_enforced_for_editors_and_unknown_kinds_fail_closed(tmp_engine.dispose()- "load_error",- [- pytest.param(OSError("config unavailable"), id="io-error"),- pytest.param(AttributeError("config shape unavailable"), id="attribute-error"),- pytest.param(TypeError("config shape unavailable"), id="type-error"),- pytest.param(ValueError("config value unavailable"), id="value-error"),- ],-)-def test_show_page_config_reload_failure_preserves_exact_page_access_but_fails_closed_elsewhere(- monkeypatch,- tmp_path,- load_error: Exception,-) -> None:+def test_show_page_is_no_longer_a_resource_kind(monkeypatch, tmp_path) -> None:+ """§3.2 retired show_page from the Resource ACL: every entry point fails+ closed with ``invalid_resource_kind`` and nothing reads or writes a+ ``resource_access_policies`` row for it.+ """+monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))db = tmp_path / "vibe.sqlite"run_migrations(db)engine = create_sqlite_engine(db)- legacy_owner = _context(- "legacy-owner",- organization_id=None,- role=None,- instance_role="editor",- access_source="email_invitation",- )- link_guest = resource_access_service.ResourceUserContext(- subject="link-guest",- email="[email protected]",- instance_role="viewer",- instance_access_source="show_page_email",- show_page_id="legacy-page",- is_remote=True,- )- local_owner = resource_access_service.instance_owner_context()-- def fail_load(_cls, *_args, **_kwargs):- raise load_error-+ owner = _context("owner-1", instance_role="owner", access_source="owner")try:with engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="legacy-page",- organization_id=None,- owner_user_id="legacy-owner",- access_level="private",- )- monkeypatch.setattr(V2Config, "load", classmethod(fail_load))-- resolved = permissions.resolve_current_instance_ownership()- assert resolved["mode"] == (- resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE- )-- with engine.begin() as connection:- reconciliation = resource_access_service.reconcile_show_page_resource_policy(- connection,- resource_id="legacy-page",- ownership=resolved,- owner_user_id="legacy-owner",- )- assert reconciliation["status"] == (- resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE- )- assert reconciliation["policy"]["organization_id"] is None- assert reconciliation["policy"]["owner_user_id"] == "legacy-owner"-+ with pytest.raises(resource_access_service.ResourceAccessError, match="invalid_resource_kind"):+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="show_page",+ resource_id="legacy-page",+ organization_id=None,+ owner_user_id="owner-1",+ access_level="private",+ )with engine.connect() as connection:- ownership = resource_access_service.current_show_page_instance_ownership(- connection=connection- )- assert ownership["mode"] == (- resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE- )- assert not resource_access_service.can_use_resource(- legacy_owner,- "show_page",- "legacy-page",- connection=connection,- )- assert not resource_access_service.can_manage_resource_acl(- legacy_owner,- "show_page",- "legacy-page",- connection=connection,- )- assert not resource_access_service.can_manage_show_page_access(- legacy_owner,- "legacy-page",- connection=connection,- )- assert not resource_access_service.can_control_resource_sharing(- legacy_owner,- "show_page",- "legacy-page",- connection=connection,- )- assert resource_access_service.filter_accessible_resources(- legacy_owner,- "show_page",- [{"session_id": "legacy-page"}],- connection=connection,- ) == []- # The signed Limited-link session is scoped to this exact page and- # does not depend on the instance pairing/configuration reload.- assert resource_access_service.can_use_resource(- link_guest,- "show_page",- "legacy-page",- connection=connection,- )- wrong_page_guest = resource_access_service.ResourceUserContext(- subject="link-guest",- email="[email protected]",- instance_role="viewer",- instance_access_source="show_page_email",- show_page_id="another-page",- is_remote=True,- )- assert not resource_access_service.can_use_resource(- wrong_page_guest,- "show_page",- "legacy-page",- connection=connection,- )- assert resource_access_service.can_use_resource(- local_owner,- "show_page",- "legacy-page",- connection=connection,- )+ for call in (+ lambda: resource_access_service.can_use_resource(+ owner, "show_page", "legacy-page", connection=connection+ ),+ lambda: resource_access_service.can_manage_resource_acl(+ owner, "show_page", "legacy-page", connection=connection+ ),+ lambda: resource_access_service.can_control_resource_sharing(+ owner, "show_page", "legacy-page", connection=connection+ ),+ lambda: resource_access_service.filter_accessible_resources(+ owner,+ "show_page",+ [{"session_id": "legacy-page"}],+ connection=connection,+ ),+ lambda: resource_access_service.get_resource_policy(+ "show_page", "legacy-page", connection=connection+ ),+ ):+ with pytest.raises(resource_access_service.ResourceAccessError, match="invalid_resource_kind"):+ call()+ assert "show_page" not in resource_access_service.RESOURCE_KINDSfinally:engine.dispose()-def test_show_page_unpaired_configuration_remains_explicitly_unmanaged(- monkeypatch,- tmp_path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))- V2Config.default().save()- db = tmp_path / "vibe.sqlite"- run_migrations(db)- engine = create_sqlite_engine(db)- try:- with engine.connect() as connection:- ownership = resource_access_service.current_show_page_instance_ownership(- connection=connection- )- assert ownership == {- "mode": "unmanaged",- "instance_id": None,- "organization_id": None,- "source": "config",- }- finally:- engine.dispose()+def _insert_legacy_show_page_policy(connection, *, organization_id: str | None, resource_id: str = "legacy-page") -> None:+ """Write a retired-kind policy row exactly as an older release shipped it."""+ now = "2026-07-27T20:00:00.000000+00:00"+ connection.execute(+ resource_access_policies.insert().values(+ resource_kind="show_page",+ resource_id=resource_id,+ organization_id=organization_id,+ owner_user_id="owner-1",+ owner_email=None,+ access_level="public",+ created_by_user_id="owner-1",+ updated_by_user_id="owner-1",+ policy_revision=1,+ last_applied_control_plane_revision=1,+ created_at=now,+ updated_at=now,+ )+ )-def test_show_page_authorizers_adopt_legacy_policy_before_enforcing_organization_fence(- monkeypatch,- tmp_path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))- config = V2Config.default()- cloud = config.remote_access.vibe_cloud- cloud.enabled = True- cloud.backend_url = "https://backend.example"- cloud.instance_id = "inst-1"- cloud.instance_secret = "device-secret"- cloud.instance_kind = "organization"- config.save()- monkeypatch.setattr(- permissions,- "resolve_current_instance_ownership",- lambda: {- "mode": "organization",- "instance_id": "inst-1",- "organization_id": "org-1",- "source": "live",- },- )+def test_retired_show_page_rows_stay_inert_in_unscoped_queries(tmp_path) -> None:+ """§3.2 kept legacy ``show_page`` policy rows in place for load safety, but+ unscoped queries must not resurrect them: neither the sync organization+ enumeration nor an unscoped policy listing may surface a retired kind.+ """+db = tmp_path / "vibe.sqlite"run_migrations(db)engine = create_sqlite_engine(db)- owner = _context("owner-1", instance_role="editor")try:with engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="legacy-page",- organization_id=None,- owner_user_id="owner-1",- access_level="private",- )- assert resource_access_service.can_use_resource(- owner, "show_page", "legacy-page", connection=connection- )- assert resource_access_service.can_manage_resource_acl(- owner, "show_page", "legacy-page", connection=connection- )- assert resource_access_service.can_manage_show_page_access(- owner, "legacy-page", connection=connection- )- assert resource_access_service.can_control_resource_sharing(- owner, "show_page", "legacy-page", connection=connection- )- assert resource_access_service.filter_accessible_resources(- owner,- "show_page",- [{"session_id": "legacy-page"}],- connection=connection,- ) == [{"session_id": "legacy-page"}]- policy = resource_access_service.get_resource_policy(- "show_page", "legacy-page", connection=connection- )- assert policy is not None- assert policy["organization_id"] == "org-1"+ _seed_policies(connection)+ _insert_legacy_show_page_policy(connection, organization_id="legacy-org")++ with engine.connect() as connection:+ # The row is present on disk, so any exclusion below is a query+ # filter, not a failed insert.+ retained = connection.execute(+ resource_access_policies.select().where(+ resource_access_policies.c.resource_kind == "show_page"+ )+ ).mappings().all()+ assert len(retained) == 1++ assert resource_access_service.list_resource_organization_ids(connection=connection) == ["org-1"]+ policies = resource_access_service.list_resource_policies(connection=connection)+ assert [policy["resource_kind"] for policy in policies] == [+ "agent",+ "agent",+ "agent",+ ]+ assert all(policy["organization_id"] == "org-1" for policy in policies)finally:engine.dispose()-def test_show_page_legacy_reconciliation_reopens_after_authority_lookup(+def test_show_page_instance_ownership_fence_survives_config_failure(monkeypatch,tmp_path,) -> None:- """An authority lookup must finish before the legacy policy read snapshot."""+ """The pairing fence moved to ``vibe.permissions`` and still fails closed+ to ``configuration_unavailable`` when the config cannot be loaded.+ """monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))- config = V2Config.default()- cloud = config.remote_access.vibe_cloud- cloud.enabled = True- cloud.backend_url = "https://backend.example"- cloud.instance_id = "inst-1"- cloud.instance_secret = "device-secret"- cloud.instance_kind = "organization"- config.save()- db = tmp_path / "vibe.sqlite"- run_migrations(db)- engine = create_sqlite_engine(db)- owner = _context("owner-1", instance_role="editor")+ V2Config.default().save()- try:- with engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="legacy-page",- organization_id=None,- owner_user_id="owner-1",- access_level="private",- )+ def fail_load(_cls, *_args, **_kwargs):+ raise OSError("config unavailable")- def resolve_ownership() -> dict[str, str]:- # A concurrent writer commits while the authoritative lookup is- # in flight. The later reconciliation must use a fresh snapshot.- with engine.begin() as writer:- writer.execute(- state_meta.insert().values(- key="interleaved-lookup",- value_json="{}",- updated_at="now",- )- )- return {- "mode": "organization",- "instance_id": "inst-1",- "organization_id": "org-1",- "source": "live",- }+ monkeypatch.setattr(V2Config, "load", classmethod(fail_load))- monkeypatch.setattr(permissions, "resolve_current_instance_ownership", resolve_ownership)+ resolved = permissions.resolve_current_instance_ownership()+ assert resolved["mode"] == permissions.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE+ assert resolved["organization_id"] is None- with engine.begin() as connection:- assert resource_access_service.can_use_resource(- owner,- "show_page",- "legacy-page",- connection=connection,- )- with engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page",- "legacy-page",- connection=connection,- )- assert policy is not None- assert policy["organization_id"] == "org-1"- finally:- engine.dispose()+def test_show_page_instance_ownership_is_unmanaged_without_pairing(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ V2Config.default().save()++ ownership = permissions.current_show_page_instance_ownership()+ assert ownership == {+ "mode": "unmanaged",+ "instance_id": None,+ "organization_id": None,+ "source": "config",+ }@pytest.mark.parametrize(diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.pyindex 4524ed3c5..dde05863d 100644--- a/tests/test_resource_acl_show_pages.py+++ b/tests/test_resource_acl_show_pages.py@@ -1,7 +1,7 @@from __future__ import annotationsimport pytest-from sqlalchemy import insert, select+from sqlalchemy import selectfrom config import pathsfrom config.v2_config import V2Config@@ -11,7 +11,7 @@ from storage import media_service, project_access_service, projects_service, resfrom storage import workbench_sessions_service as sessions_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_sessions, show_pages+from storage.models import agent_sessionsfrom tests.ui_server_test_helpers import _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headersfrom vibe import api, internal_client, permissions, remote_access, ui_server@@ -90,64 +90,34 @@ def _ownership(}-def _seed_show_pages_with_policies() -> ShowPageStore:+def _seed_show_pages() -> ShowPageStore:if not paths.get_config_path().exists():V2Config.default().save()store = ShowPageStore()for session_id in ("ses-private", "ses-public", "ses-scope"):store.ensure(session_id)- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="ses-private",- organization_id="org-1",- owner_user_id="owner-1",- access_level="private",- )- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="ses-public",- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="ses-scope",- organization_id="org-1",- owner_user_id="owner-1",- access_level="scope",- group_ids=["group-engineering"],- )return store-def test_show_page_catalog_follows_instance_role_and_show_page_acl(monkeypatch, tmp_path) -> None:[email protected]("instance_role", ["viewer", "editor", "owner"])+def test_show_require_access_follows_instance_role_alone(+ monkeypatch, tmp_path, instance_role+) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()try:- owner_ids = {page.session_id for page in store.list(user_context=_organization_context("owner-1"))}- member_ids = {page.session_id for page in store.list(user_context=_organization_context("member-1"))}- no_group_ids = {- page.session_id- for page in store.list(user_context=_organization_context("member-2", group_ids=None))- }+ page = store.require_access(+ "ses-private",+ user_context=_organization_context("member-1", instance_role=instance_role),+ )+ assert page.session_id == "ses-private"finally:store.close()- assert owner_ids == {"ses-private", "ses-public", "ses-scope"}- assert member_ids == {"ses-public", "ses-scope"}- assert no_group_ids == {"ses-public"}--def test_show_page_email_context_bypasses_audience_only_for_its_signed_page(- monkeypatch, tmp_path-) -> None:+def test_show_require_access_denies_show_page_email_source(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()context = resource_access_service.ResourceUserContext(subject="guest-1",email="[email protected]",@@ -157,58 +127,8 @@ def test_show_page_email_context_bypasses_audience_only_for_its_signed_page(is_remote=True,)try:- with store.engine.connect() as connection:- assert resource_access_service.can_use_resource(- context,- "show_page",- "ses-private",- connection=connection,- )- assert not resource_access_service.can_use_resource(- context,- "show_page",- "ses-public",- connection=connection,- )- assert not resource_access_service.can_use_resource(- context,- "agent",- "ses-private",- connection=connection,- )- finally:- store.close()---def test_non_org_email_context_keeps_exact_page_entitlement_separate_from_role_rank(- monkeypatch, tmp_path-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()- context = resource_access_service.ResourceUserContext(- subject="member-1",- email="[email protected]",- instance_role="editor",- instance_access_source="email",- show_page_id="ses-private",- is_remote=True,- )- try:- with store.engine.connect() as connection:- assert resource_access_service.can_use_resource(- context,- "show_page",- "ses-private",- connection=connection,- )- assert not resource_access_service.can_use_resource(- context,- "show_page",- "ses-scope",- connection=connection,- )- assert context.can_chat- assert context.can_use_resource("agent")+ with pytest.raises(ShowPageError, match="Show Page access is not permitted"):+ store.require_access("ses-private", user_context=context)finally:store.close()@@ -220,7 +140,7 @@ def test_non_org_email_context_keeps_exact_page_entitlement_separate_from_role_r("member-1", "viewer", "member"),],)-def test_remote_show_page_access_does_not_bypass_acl(+def test_remote_show_page_surfaces_follow_instance_role(monkeypatch,tmp_path,subject,@@ -229,7 +149,7 @@ def test_remote_show_page_access_does_not_bypass_acl() -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()store.close()async def _runtime_response(*args, **kwargs):@@ -270,11 +190,10 @@ def test_remote_show_page_access_does_not_bypass_acl()assert catalog.status_code == 200- expected = {"ses-private", "ses-public", "ses-scope"} if instance_role == "owner" else {- "ses-public", "ses-scope"- }pages = catalog.get_json()["pages"]- assert {item["session_id"] for item in pages} == expected+ # §3.2: the catalog is the Instance role alone — no Resource ACL filter, so a+ # plain Viewer still sees every page; only manage/publish flags follow Editor.+ assert {item["session_id"] for item in pages} == {"ses-private", "ses-public", "ses-scope"}if instance_role == "owner":assert all(item.get("path") for item in pages)assert all(item["can_manage"] for item in pages)@@ -284,7 +203,8 @@ def test_remote_show_page_access_does_not_bypass_acl(assert all(not item["can_manage"] for item in pages)assert all(not item["can_publish_public"] for item in pages)assert mutation.status_code == (200 if instance_role == "owner" else 403)- assert page.status_code == (200 if instance_role == "owner" else 302)+ # §3.2: every Instance Viewer enters /show; only show_page_email is barred.+ assert page.status_code == 200def test_show_page_creation_uses_exact_instance_organization_without_request_claims(@@ -323,57 +243,42 @@ def test_show_page_creation_uses_exact_instance_organization_without_request_cla)created = store.ensure(session["id"])assert created.session_id == session["id"]+ # §3.2: show_page no longer registers a Resource ACL row, so creation+ # writes no policy and the fence is not consulted for admission.with store.engine.connect() as connection:- created_policy = resource_access_service.get_resource_policy(- "show_page", created.session_id, connection=connection- )- assert created_policy is not None- assert created_policy["organization_id"] == "org-1"- assert created_policy["owner_user_id"] is None- assert "is_trusted_local" not in created_policy+ with pytest.raises(+ resource_access_service.ResourceAccessError,+ match="invalid_resource_kind",+ ):+ resource_access_service.get_resource_policy(+ "show_page", created.session_id, connection=connection+ )page = store.ensure("ses-org-public", user_context=owner_context)- with store.engine.begin() as connection:- policy = resource_access_service.get_resource_policy(- "show_page",- page.session_id,- connection=connection,- )- assert policy is not None- assert policy["organization_id"] == "org-1"- assert policy["owner_user_id"] == "owner-1"- assert policy["access_level"] == "private"- resource_access_service.apply_control_plane_intent(- connection,- organization_id="org-1",- resource_kind="show_page",- resource_id=page.session_id,- revision=1,- access_level="public",- group_ids=[],- )- updated = store.get(page.session_id)- assert updated is not None- assert updated.visibility == "private"- assert updated.share_id+ assert page.session_id == "ses-org-public"+ assert page.visibility == "private"+ assert page.share_idfinally:store.close()-def test_show_page_scope_without_group_context_is_denied(monkeypatch, tmp_path) -> None:+def test_show_require_access_is_group_agnostic(monkeypatch, tmp_path) -> None:+ """§3.2: /show admission ignores the group claims that only /p audience uses."""+monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()try:- with pytest.raises(ShowPageError):- store.require_access("ses-scope", user_context=_organization_context("member-1", group_ids=None))+ page = store.require_access(+ "ses-scope",+ user_context=_organization_context("member-1", group_ids=None),+ )+ assert page.session_id == "ses-scope"finally:store.close()- # Missing group claims fail closed for scoped pages.-def test_organization_admin_without_instance_owner_role_cannot_manage_pages(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()admin = _organization_context("admin-1",group_ids=frozenset({"group-sales"}),@@ -383,8 +288,10 @@ def test_organization_admin_without_instance_owner_role_cannot_manage_pages(monkowner = _organization_context("owner-1", instance_role="owner")try:public_page = store.update_visibility("ses-private", "public", user_context=owner)- with pytest.raises(ShowPageError):- store.require_access("ses-private", user_context=admin)+ # §3.2: /show admission is the Instance Viewer role alone, so an+ # Organization admin that is still a plain Instance Viewer enters /show…+ assert store.require_access("ses-private", user_context=admin).session_id == "ses-private"+ # …but management stays reserved to Instance Editor/Owner.with pytest.raises(ShowPageError):store.update_visibility("ses-private", "private", user_context=admin)@@ -398,69 +305,46 @@ def test_organization_admin_without_instance_owner_role_cannot_manage_pages(monkassert rotated_share_id == rotated.share_idassert custom.share_id == "owner-link"- with pytest.raises(ShowPageError):- store.require_access("ses-scope", user_context=admin)+ assert store.require_access("ses-scope", user_context=admin).session_id == "ses-scope"finally:store.close()-def test_access_only_manager_availability_response_does_not_expose_page_payload(monkeypatch, tmp_path) -> None:+def test_availability_mutation_is_editor_gated_and_returns_payload(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- store = _seed_show_pages_with_policies()- admin = _organization_context(- "admin-1",- group_ids=frozenset({"group-sales"}),- organization_role="admin",- instance_role="viewer",- )- try:- store.update_visibility(- "ses-private",- "public",- user_context=_organization_context("owner-1", instance_role="viewer"),- )- finally:- store.close()+ store = _seed_show_pages()+ store.close()+ viewer = _organization_context("member-1", instance_role="viewer")+ editor = _organization_context("editor-1", instance_role="editor")+monkeypatch.setattr(resource_access_service,"resolve_resource_access_context",- lambda _value=None: admin,+ lambda _value=None: viewer,)-with pytest.raises(ShowPageError):api.set_show_page_availability("ses-private", True)--def test_excluded_scoped_owner_availability_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _save_config(tmp_path)- store = _seed_show_pages_with_policies()- excluded_owner = _organization_context(- "owner-1",- group_ids=frozenset({"group-sales"}),- instance_role="viewer",- )- try:- store.update_visibility("ses-scope", "public", user_context=excluded_owner)- finally:- store.close()monkeypatch.setattr(resource_access_service,"resolve_resource_access_context",- lambda _value=None: excluded_owner,+ lambda _value=None: editor,)+ offline = api.set_show_page_availability("ses-private", True)+ online = api.set_show_page_availability("ses-private", False)- offline = api.set_show_page_availability("ses-scope", True)- online = api.set_show_page_availability("ses-scope", False)-+ # §3.2: an Instance Editor both manages and uses the page, so the mutation+ # response carries the full payload (no use/management split to redact).assert offline["ok"] is True+ assert offline["offline"] is Trueassert online["ok"] is True+ assert online["offline"] is Falsedef test_remote_show_page_editor_can_control_sharing_without_instance_owner_role(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()page_owner = _organization_context("owner-1", instance_role="editor")try:published = store.update_visibility("ses-private", "public", user_context=page_owner)@@ -497,15 +381,6 @@ def test_remote_show_page_viewer_mutations_are_instance_role_denied(monkeypatch,)session_id = session["id"]store.ensure(session_id)- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=session_id,- organization_id="org-1",- owner_user_id="owner-1",- access_level="private",- )store.close()client = app.test_client()client.set_cookie(@@ -552,10 +427,10 @@ def test_remote_show_page_viewer_mutations_are_instance_role_denied(monkeypatch,assert applied.status_code == 403-def test_organization_admin_can_read_show_page_access_metadata_without_use_access(monkeypatch, tmp_path) -> None:+def test_organization_admin_viewer_reads_access_metadata_but_cannot_manage(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()store.close()admin = _organization_context("admin-1",@@ -565,8 +440,12 @@ def test_organization_admin_can_read_show_page_access_metadata_without_use_acces)monkeypatch.setattr(resource_access_service, "resolve_resource_access_context", lambda _value=None: admin)- with pytest.raises(ShowPageError):- api.get_show_page_access("ses-scope")+ # §3.2: an Organization admin that is still an Instance Viewer may read the+ # access metadata (can_use follows the Instance role) but never manage it.+ response = api.get_show_page_access("ses-scope")+ assert response["can_use"] is True+ assert response["can_manage"] is False+ assert response["can_publish_public"] is Falsedef test_existing_show_page_is_adopted_idempotently_without_changing_link_access(@@ -596,114 +475,73 @@ def test_existing_show_page_is_adopted_idempotently_without_changing_link_accesspage = store.ensure("ses-legacy")store.ensure("ses-legacy")with store.engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page",- page.session_id,- connection=connection,- )+ with pytest.raises(+ resource_access_service.ResourceAccessError,+ match="invalid_resource_kind",+ ):+ resource_access_service.get_resource_policy(+ "show_page",+ page.session_id,+ connection=connection,+ )after = store.get_access("ses-legacy")- assert policy is not None- assert policy["organization_id"] == "org-1"- assert policy["access_level"] == "private"- assert policy["policy_revision"] == 0+ # §3.2: adoption is a no-op — no policy is written and the page's link+ # access is untouched across repeated ensures.assert before == afterassert page.offlinefinally:store.close()-def test_legacy_show_page_policy_reconciliation_keeps_page_grants_read_only(+def test_show_page_access_api_follows_instance_role_and_bars_email_guests(monkeypatch,tmp_path,) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))store = ShowPageStore()- project_path = tmp_path / "project"- project_path.mkdir()- instance_editor = _organization_context("editor-1", instance_role="editor")- project_editor = _organization_context("project-editor", instance_role="editor")try:- with store.engine.begin() as connection:- project = projects_service.create_project(connection, str(project_path))- session_id = sessions_service.create_session(- connection,- scope_id=project["scope_id"],- agent_backend="codex",- )["id"]- store.ensure(session_id)+ store.ensure("ses-access-meta")_paired_config(tmp_path, instance_kind="organization")monkeypatch.setattr(permissions,"resolve_current_instance_ownership",lambda: _ownership("organization", organization_id="org-1"),)- with store.engine.begin() as connection:- project_access_service.apply_project_access_intent(- connection,- {- "project_id": project["id"],- "revision": 1,- "mode": "restricted",- "bindings": [],- },- )page_guest = resource_access_service.ResourceUserContext(subject="guest-1",email="[email protected]",instance_role="viewer",instance_access_source="show_page_email",- show_page_id=session_id,+ show_page_id="ses-access-meta",is_remote=True,)- guest_response = api.get_show_page_access(session_id, user_context=page_guest)- assert guest_response["ownership_status"] == "unchanged"- assert guest_response["can_use"] is True- assert guest_response["can_manage"] is False- with store.engine.connect() as connection:- assert resource_access_service.get_resource_policy(- "show_page",- session_id,- connection=connection,- ) is None-+ # §3.2: a signed show_page_email guest is a /p-only visitor — it never+ # reads access metadata.with pytest.raises(ShowPageError, match="Show Page access is not permitted"):- api.get_show_page_access(session_id, user_context=instance_editor)- with store.engine.connect() as connection:- assert resource_access_service.get_resource_policy(- "show_page",- session_id,- connection=connection,- ) is None+ api.get_show_page_access("ses-access-meta", user_context=page_guest)- with store.engine.begin() as connection:- project_access_service.apply_project_access_intent(- connection,- {- "project_id": project["id"],- "revision": 2,- "mode": "restricted",- "bindings": [{- "principal_kind": "email",- "principal_value": "[email protected]",- "access_role": "editor",- }],- },- )-- response = api.get_show_page_access(session_id, user_context=project_editor)- with store.engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page",- session_id,- connection=connection,- )- assert response["ownership_status"] == "created"+ instance_editor = _organization_context("editor-1", instance_role="editor")+ response = api.get_show_page_access(+ "ses-access-meta",+ user_context=instance_editor,+ )+ assert response["ownership_status"] == "unchanged"assert response["can_use"] is Trueassert response["can_manage"] is True- assert policy is not None- assert policy["owner_user_id"] == "project-editor"- assert policy["organization_id"] == "org-1"+ assert response["can_publish_public"] is True++ # §3.2: reading metadata never writes a show_page Resource ACL row.+ with store.engine.connect() as connection:+ with pytest.raises(+ resource_access_service.ResourceAccessError,+ match="invalid_resource_kind",+ ):+ resource_access_service.get_resource_policy(+ "show_page",+ "ses-access-meta",+ connection=connection,+ )finally:store.close()@@ -729,7 +567,7 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk"policy_organization_id": None,"access_level": "private","group_ids": [],- "policy_revision": 0,+ "policy_revision": None,"last_applied_control_plane_revision": None,"can_use": True,"can_manage": True,@@ -747,16 +585,6 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monkstore = ShowPageStore()try:store.ensure("ses-organization")- with store.engine.begin() as connection:- resource_access_service.apply_control_plane_intent(- connection,- organization_id="org-1",- resource_kind="show_page",- resource_id="ses-organization",- revision=4,- access_level="scope",- group_ids=["group-engineering"],- )finally:store.close()local_organization = app.test_client().get(@@ -784,18 +612,20 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk"ownership_status": "unchanged","instance_id": "inst_123","organization_id": "org-1",- "policy_organization_id": "org-1",- "access_level": "scope",- "group_ids": ["group-engineering"],- "policy_revision": 4,- "last_applied_control_plane_revision": 4,+ # §3.2: no show_page Resource ACL row exists, so the applied-audience+ # fields are the private/empty/None baseline, never a scope policy.+ "policy_organization_id": None,+ "access_level": "private",+ "group_ids": [],+ "policy_revision": None,+ "last_applied_control_plane_revision": None,"can_use": True,"can_manage": True,"can_publish_public": True,}-def test_null_organization_adoption_preserves_policy_and_show_access(monkeypatch, tmp_path) -> None:+def test_show_access_adoption_is_policy_free(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))store = ShowPageStore()try:@@ -807,18 +637,6 @@ def test_null_organization_adoption_preserves_policy_and_show_access(monkeypatchtarget_share_id="adopt-link",target_emails=["[email protected]"],)- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="ses-adopt",- organization_id=None,- owner_user_id="owner-1",- owner_email="[email protected]",- access_level="private",- policy_revision=4,- last_applied_control_plane_revision=3,- )before_access = store.get_access("ses-adopt")_paired_config(tmp_path, instance_kind="organization")monkeypatch.setattr(@@ -830,127 +648,50 @@ def test_null_organization_adoption_preserves_policy_and_show_access(monkeypatchstore.ensure("ses-adopt")store.ensure("ses-adopt")+ # §3.2: adoption never writes a show_page Resource ACL row and never+ # touches the page's link access, no matter how many times ensure runs.with store.engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page",- "ses-adopt",- connection=connection,- )+ with pytest.raises(+ resource_access_service.ResourceAccessError,+ match="invalid_resource_kind",+ ):+ resource_access_service.get_resource_policy(+ "show_page", "ses-adopt", connection=connection+ )assert applied.status == "applied"assert store.get_access("ses-adopt") == before_access- assert policy is not None- assert policy["organization_id"] == "org-1"- assert policy["owner_user_id"] == "owner-1"- assert policy["owner_email"] == "[email protected]"- assert policy["access_level"] == "private"- assert policy["group_ids"] == []- assert policy["policy_revision"] == 4- assert policy["last_applied_control_plane_revision"] == 3finally:store.close()-def test_same_organization_retry_preserves_acl_revision_and_groups(monkeypatch, tmp_path) -> None:+def test_show_access_organization_mode_never_reports_policy_conflict(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- _paired_config(tmp_path, instance_kind="organization")- monkeypatch.setattr(- permissions,- "resolve_current_instance_ownership",- lambda: _ownership("organization", organization_id="org-1"),- )store = ShowPageStore()try:- store.ensure(- "ses-same-org",- user_context=_organization_context("owner-1", instance_role="owner"),- )- with store.engine.begin() as connection:- resource_access_service.apply_control_plane_intent(- connection,- organization_id="org-1",- resource_kind="show_page",- resource_id="ses-same-org",- revision=7,- access_level="scope",- group_ids=["group-engineering"],- )- before = resource_access_service.get_resource_policy(- "show_page", "ses-same-org", connection=connection- )-- store.ensure(- "ses-same-org",- user_context=_organization_context("owner-1", instance_role="owner"),- )-- with store.engine.connect() as connection:- after = resource_access_service.get_resource_policy(- "show_page", "ses-same-org", connection=connection- )- assert after == before- finally:- store.close()---def test_cross_organization_policy_conflict_fails_closed_without_breaking_link_guest(- monkeypatch,- tmp_path,-) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = ShowPageStore()- try:- store.ensure("ses-conflict")- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="ses-conflict",- organization_id="org-other",- owner_user_id="owner-other",- access_level="public",- policy_revision=5,- last_applied_control_plane_revision=5,- )+ store.ensure("ses-org")_paired_config(tmp_path, instance_kind="organization")monkeypatch.setattr(permissions,"resolve_current_instance_ownership",lambda: _ownership("organization", organization_id="org-1"),)- store.ensure("ses-conflict")- response = api.get_show_page_access("ses-conflict")- with store.engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page", "ses-conflict", connection=connection- )- link_guest = resource_access_service.can_use_resource(- resource_access_service.ResourceUserContext(- subject="guest-1",- email="[email protected]",- instance_role="viewer",- instance_access_source="show_page_email",- show_page_id="ses-conflict",- is_remote=True,- ),- "show_page",- "ses-conflict",- connection=connection,- )- with pytest.raises(ShowPageError):+ response = api.get_show_page_access("ses-org")+ # §3.2: with no policy row to diverge from the instance organization, the+ # legacy "conflict" status is gone — every Instance Viewer may use the page.+ assert response["ownership_status"] == "unchanged"+ assert response["mode"] == "organization"+ assert response["organization_id"] == "org-1"+ assert response["policy_organization_id"] is None+ assert response["can_use"] is True+ assert (store.require_access(- "ses-conflict",+ "ses-org",user_context=_organization_context("member-1"),- )- assert store.list(user_context=_organization_context("member-1")) == []- assert response["ownership_status"] == "conflict"- assert response["organization_id"] == "org-1"- assert response["policy_organization_id"] == "org-other"- assert policy is not None- assert policy["organization_id"] == "org-other"- assert policy["access_level"] == "public"- assert policy["policy_revision"] == 5- assert link_guest is True+ ).session_id+ == "ses-org"+ )+ assert len(store.list(user_context=_organization_context("member-1"))) == 1finally:store.close()@@ -983,12 +724,16 @@ def test_organization_pending_is_stable_private_and_does_not_block_local_creatiotry:created = store.ensure("ses-pending")response = api.get_show_page_access("ses-pending")+ # §3.2: a pending fence still never writes a show_page Resource ACL row.with store.engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page", "ses-pending", connection=connection- )+ with pytest.raises(+ resource_access_service.ResourceAccessError,+ match="invalid_resource_kind",+ ):+ resource_access_service.get_resource_policy(+ "show_page", "ses-pending", connection=connection+ )assert created.session_id == "ses-pending"- assert policy is Noneassert response["mode"] == "organization_pending"assert response["ownership_status"] == "pending"assert response["access_level"] == "private"@@ -1004,7 +749,7 @@ def test_last_known_organization_binding_is_exact_instance_scoped(monkeypatch, tstore = ShowPageStore()try:with store.engine.begin() as connection:- resource_access_service.remember_show_page_instance_ownership(+ permissions.remember_show_page_instance_ownership(connection,_ownership("organization", organization_id="org-1"),)@@ -1032,59 +777,29 @@ def test_last_known_organization_binding_is_exact_instance_scoped(monkeypatch, tstore.close()-def test_reconciliation_rejects_a_pairing_switch_before_policy_write(monkeypatch, tmp_path) -> None:- """A stale ownership snapshot cannot create a policy for the old instance."""+def test_ownership_fence_rejects_stale_pairing_before_persisting(monkeypatch, tmp_path) -> None:+ """A stale ownership snapshot cannot bind the fence to a former pairing."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_paired_config(tmp_path, instance_kind="organization")store = ShowPageStore()try:with store.engine.begin() as connection:- connection.execute(- insert(show_pages).values(- session_id="ses-pairing-race",- access_mode="private",- access_revision=0,- share_id="share-pairing-race",- offline_at=None,- created_at="2026-01-01T00:00:00Z",- updated_at="2026-01-01T00:00:00Z",- )+ fence = permissions.remember_show_page_instance_ownership(+ connection,+ {+ "mode": "organization",+ "instance_id": "inst-other",+ "organization_id": "org-1",+ "source": "live",+ },)-- original_assert = resource_access_service._assert_show_page_pairing_current # noqa: SLF001- switched = False-- def switch_after_validation(ownership):- nonlocal switched- original_assert(ownership)- if not switched:- switched = True- current = V2Config.load()- current.remote_access.vibe_cloud.instance_id = "inst-new"- current.save()-- monkeypatch.setattr(- resource_access_service,- "_assert_show_page_pairing_current",- switch_after_validation,- )- monkeypatch.setattr(- permissions,- "resolve_current_instance_ownership",- lambda: _ownership("organization", organization_id="org-1"),- )-- reconciliation = store.reconcile_resource_policy("ses-pairing-race")- assert reconciliation["status"] == "pending"- assert reconciliation["ownership"]["instance_id"] == "inst-new"-- with store.engine.connect() as connection:- assert resource_access_service.get_resource_policy(- "show_page",- "ses-pairing-race",- connection=connection,- ) is None+ # The writer fails closed to the current pending fence instead of+ # persisting an organization binding for the former instance.+ assert fence["mode"] == "organization_pending"+ assert fence["instance_id"] == "inst_123"+ assert fence["organization_id"] is None+ assert permissions.current_show_page_instance_ownership()["mode"] == "organization_pending"finally:store.close()@@ -1276,7 +991,7 @@ def test_show_access_malformed_apply_is_rejected_before_ipc(monkeypatch, tmp_patdef test_show_access_non_owner_is_rejected_before_ipc(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()store.close()viewer = _organization_context("member-1", instance_role="viewer")monkeypatch.setattr(@@ -1395,10 +1110,10 @@ def test_show_access_conflict_returns_current_snapshot(monkeypatch, tmp_path) ->assert response.get_json()["show_access"]["revision"] == 3-def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> None:+def test_remote_org_dock_requires_editor_role(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()store.close()owner = _organization_context("owner-1", instance_role="owner")member = _organization_context("member-1")@@ -1408,8 +1123,8 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Nonorganization_role="admin",instance_role="owner",)- # Show Page dock/pin stays reserved to owner/admin Organization roles- # under the Resource ACL boundary (see #1343); a plain member is denied.+ # §3.2: dock pin/unpin/reorder stay reserved to Instance Editor/Owner; a+ # plain Viewer is denied the mutation even when it is an Organization admin.with pytest.raises(ShowPageError):api.pin_dock_show_page("ses-public", user_context=member)api.pin_dock_show_page("ses-scope", user_context=admin)@@ -1418,10 +1133,10 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Nondock = api.get_dock(user_context=member)["dock"]visible_ids = {pin["session_id"] for pin in dock["pins"]}- assert visible_ids == {"ses-public", "ses-scope"}- assert "show:ses-private" not in dock["order"]- # Pinning additional pages (require_management) stays denied for a plain- # member; unpin and reorder are also dock mutations and stay denied.+ # §3.2: read filtering follows the Instance Viewer role alone — every pinned+ # page is visible, private included (no Resource ACL filter to hide it).+ assert visible_ids == {"ses-private", "ses-public", "ses-scope"}+ assert sum(1 for entry in dock["order"] if entry.startswith("show:")) == 3with pytest.raises(ShowPageError):api.pin_dock_show_page("ses-private", user_context=member)with pytest.raises(ShowPageError):@@ -1446,15 +1161,13 @@ def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> Nonbase_url="https://alex.avibe.bot",environ_base=_remote_peer(),)- # A plain active Organization member is denied dock mutations under the- # Resource ACL boundary (see #1343).assert response.status_code == 403-def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_path) -> None:+def test_remote_owner_dock_order_persists(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()store.close()owner = _organization_context("owner-1", instance_role="owner")admin = _organization_context("admin-1", organization_role="admin", instance_role="owner")@@ -1481,7 +1194,7 @@ def test_remote_admin_dock_order_preserves_hidden_private_pins(monkeypatch, tmp_def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)- store = _seed_show_pages_with_policies()+ store = _seed_show_pages()store.close()owner = _organization_context("owner-1", instance_role="owner")api.pin_dock_show_page("ses-public", user_context=owner)@@ -1500,7 +1213,7 @@ def test_untrusted_dock_context_fails_closed(monkeypatch, tmp_path) -> None:)-def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_path) -> None:+def test_remote_viewer_archive_is_denied_under_instance_role(monkeypatch, tmp_path) -> None:from unittest.mock import AsyncMockmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -1517,19 +1230,23 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patscope_id=project["scope_id"],agent_backend="claude",)["id"]+ project_access_service.apply_project_access_intent(+ connection,+ {+ "project_id": project["id"],+ "revision": 1,+ "mode": "restricted",+ "bindings": [{+ "principal_kind": "email",+ "principal_value": "[email protected]",+ "access_role": "viewer",+ }],+ },+ )store = ShowPageStore()try:store.ensure(session_id)- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=session_id,- organization_id="org-1",- owner_user_id="owner-1",- access_level="private",- )finally:store.close()@@ -1539,9 +1256,9 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patarchive_session,)- # Show Page archive of another owner's page stays reserved to- # owner/admin Organization roles under the Resource ACL boundary- # (see #1343); a plain active Organization member is denied.+ # §3.2: archiving a session that has a Show Page stays reserved to the+ # Instance Editor role; a plain Instance Viewer with project read access+ # is still denied before any controller IPC.client = app.test_client()client.set_cookie(remote_access.SESSION_COOKIE_NAME,@@ -1549,7 +1266,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patconfig,subject="member-1",groups=["group-engineering"],- instance_role="editor",+ instance_role="viewer",),domain="alex.avibe.bot",)@@ -1560,7 +1277,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patenviron_base=_remote_peer(),)- assert response.status_code in {403, 404}+ assert response.status_code == 403archive_session.assert_not_awaited()with engine.connect() as connection:assert connection.execute(@@ -1570,7 +1287,7 @@ def test_remote_member_archive_is_denied_under_resource_acl(monkeypatch, tmp_patengine.dispose()-def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(+def test_remote_org_show_annotation_media_follows_instance_role(monkeypatch,tmp_path,) -> None:@@ -1584,37 +1301,28 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(try:with engine.begin() as connection:project = projects_service.create_project(connection, str(project_dir))- sessions = {- access_level: sessions_service.create_session(- connection,- scope_id=project["scope_id"],- agent_backend="claude",- )["id"]- for access_level in ("private", "public")- }+ session_id = sessions_service.create_session(+ connection,+ scope_id=project["scope_id"],+ agent_backend="claude",+ )["id"]project_access_service.apply_project_access_intent(connection,{"project_id": project["id"],"revision": 1,"mode": "restricted",- "bindings": [],+ "bindings": [{+ "principal_kind": "email",+ "principal_value": "[email protected]",+ "access_role": "viewer",+ }],},)store = ShowPageStore()try:- for access_level, session_id in sessions.items():- store.ensure(session_id)- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=session_id,- organization_id="org-1",- owner_user_id="owner-1",- access_level=access_level,- )+ store.ensure(session_id)finally:store.close()@@ -1625,16 +1333,15 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(with engine.begin() as connection:tokens = {- f"{source}:{access_level}": media_service.register(+ source: media_service.register(connection,scope_id=project["scope_id"],session_id=session_id,kind="image",source=source,- local_path=_screenshot(f"{source}-{access_level}"),+ local_path=_screenshot(source),)for source in ("show_annotation", "agent_reply")- for access_level, session_id in sessions.items()}orphan_token = media_service.register(connection,@@ -1645,31 +1352,38 @@ def test_remote_org_show_annotation_media_temporarily_follows_open_page_policy(local_path=_screenshot("orphan"),)- client = app.test_client()- client.set_cookie(- remote_access.SESSION_COOKIE_NAME,- _organization_cookie(- config,- subject="member-1",- groups=["group-engineering"],- instance_role="viewer",- ),- domain="alex.avibe.bot",- )+ def _client(subject: str):+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _organization_cookie(+ config,+ subject=subject,+ groups=["group-engineering"],+ instance_role="viewer",+ ),+ domain="alex.avibe.bot",+ )+ return client- def _media(token: str):+ def _media(client, token: str):return client.get(f"/api/media/{token}",base_url="https://alex.avibe.bot",environ_base=_remote_peer(),)- # Media access follows the associated Project and Show Page ACLs.- assert _media(tokens["show_annotation:private"]).status_code == 404- assert _media(tokens["show_annotation:public"]).status_code == 404+ in_scope = _client("member-1")+ # §3.2: a show_annotation screenshot inherits the page's /show admission+ # (Instance Viewer role) alone — the Project/session role does NOT stack+ # on top — so a viewer OUTSIDE the restricted Project still reads its own+ # page's annotation bytes, while non-annotation media keeps the project gate.+ out_of_scope = _client("member-2")+ assert _media(out_of_scope, tokens["show_annotation"]).status_code == 200+ assert _media(out_of_scope, tokens["agent_reply"]).status_code == 404+ assert _media(in_scope, tokens["show_annotation"]).status_code == 200+ assert _media(in_scope, tokens["agent_reply"]).status_code == 200# An annotation with no page to check against cannot be authorized.- assert _media(orphan_token).status_code == 404- assert _media(tokens["agent_reply:private"]).status_code == 404- assert _media(tokens["agent_reply:public"]).status_code == 404+ assert _media(in_scope, orphan_token).status_code == 404finally:engine.dispose()diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.pyindex 92a0adaf2..9a5b1e728 100644--- a/tests/test_ui_project_access.py+++ b/tests/test_ui_project_access.py@@ -191,15 +191,6 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tmmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))config, ids = _setup_state(tmp_path)engine = create_sqlite_engine()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="show_page",- resource_id=ids["session_a"],- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )with engine.begin() as conn:conn.execute(scopes.update()@@ -984,7 +975,7 @@ def test_show_page_payload_preserves_path_for_non_project_page_owner(monkeypatchassert payload["path"] == "/private/page"-def test_show_page_payload_does_not_bypass_project_viewer_with_resource_manager(monkeypatch) -> None:+def test_show_page_payload_project_viewer_downgrade_wins_over_instance_editor(monkeypatch) -> None:context = AuthorizationContext(instance_role="editor",email="[email protected]",@@ -1015,11 +1006,6 @@ def test_show_page_payload_does_not_bypass_project_viewer_with_resource_manager(lambda _conn, _session_id: "project-1",)monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: True)- monkeypatch.setattr(- resource_access_service,- "can_manage_resource_acl",- lambda _context, _kind, _resource_id, *, connection: True,- )payload = ui_server._show_page_response_for_request({"ok": True, "session_id": "project-session", "path": "/private/page"},@@ -1060,11 +1046,6 @@ def test_show_page_payload_does_not_treat_inaccessible_project_as_unscoped(monkelambda _conn, _session_id: "project-removed-binding",)monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: True)- monkeypatch.setattr(- resource_access_service,- "can_manage_resource_acl",- lambda _context, _kind, _resource_id, *, connection: True,- )payload = ui_server._show_page_response_for_request({"ok": True, "session_id": "project-session", "path": "/private/page"},@@ -1095,11 +1076,6 @@ def test_show_page_payload_redacts_path_when_session_is_missing(monkeypatch) ->monkeypatch.setattr(ui_server, "_projects_engine", lambda: _Engine())monkeypatch.setattr(project_access_service, "session_exists", lambda _conn, _session_id: False)- monkeypatch.setattr(- resource_access_service,- "can_manage_resource_acl",- lambda _context, _kind, _resource_id, *, connection: True,- )payload = ui_server._show_page_response_for_request({"ok": True, "session_id": "deleted-session", "path": "/private/page"},@@ -1122,16 +1098,6 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->organization_role="member",is_remote=True,)- engine = create_sqlite_engine()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="show_page",- resource_id=ids["session_a"],- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )visible_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_a"]}})hidden_payload = json.dumps({"type": "session.status", "data": {"session_id": ids["session_b"]}})assert ui_server._workbench_event_visible_to_context(context, "session.status", visible_payload) is True@@ -1164,11 +1130,14 @@ def test_project_access_filters_sse_and_show_websocket(monkeypatch, tmp_path) ->minimum_role="viewer",project_session_id=ids["session_a"],) is True+ # §3.2: /show admission follows the Instance role alone, independent of the+ # Project ACL, so the show websocket authorizes a page outside the caller's+ # Project access exactly like an in-Project one (a Viewer enters every page).assert ui_server._show_runtime_websocket_authorized(websocket,minimum_role="viewer",project_session_id=ids["session_b"],- ) is False+ ) is Truedef test_terminal_websocket_requires_editor_role_without_a_project(monkeypatch, tmp_path) -> None:diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 6f7487bd1..1e44eebc7 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -2744,26 +2744,13 @@ def test_workbench_events_end_a_subscriber_whose_queue_overflowed(monkeypatch, tassert not [frame for frame in frames if "workbench.events.gap" in frame]-def test_workbench_events_allow_show_events_when_show_page_acl_allows(monkeypatch, tmp_path) -> None:+def test_workbench_events_allow_show_events_when_show_gate_allows(monkeypatch, tmp_path) -> None:from vibe.authorization import AuthorizationContextfrom vibe.sse_broker import brokerfrom vibe.ui_compat import g- from storage import resource_access_service- from storage.db import create_sqlite_enginemonkeypatch.setenv("AVIBE_HOME", str(tmp_path))ensure_sqlite_state()- engine = create_sqlite_engine()- with engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="show-session-1",- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )- engine.dispose()async def collect_show_event() -> str:with app.test_request_context("/api/events"):diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 27fee2515..1eed66b2b 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -197,18 +197,9 @@ def _create_show_page(session_id: str, visibility: str) -> str | None:assert page is not Noneelse:page = store.update_visibility(session_id, visibility)- # The factory represents a page that has been published to this test- # Organization. Runtime access still requires the caller's Instance role;- # this ACL only supplies the independent Show Page entitlement.- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=session_id,- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )+ # §3.2 removed show_page from the Resource ACL: there is no page policy+ # to seed. Runtime access follows the caller's Instance role alone, and+ # `/p` admission follows the sharing axis set above.return page.share_idfinally:store.close()@@ -234,15 +225,6 @@ def _create_show_page_record(session_id: str, visibility: str) -> str | None:store = ShowPageStore()try:page = store.update_visibility(session_id, visibility)- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id=session_id,- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )return page.share_idfinally:store.close()@@ -3617,24 +3599,11 @@ def test_private_show_me_is_always_available(monkeypatch, tmp_path):assert response.headers["cache-control"] == "no-store, private"-def test_private_show_page_treats_show_page_email_viewer_as_read_only(monkeypatch, tmp_path):+def test_private_show_page_bars_show_page_email_viewer_from_show_surface(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)_create_agent_session("ses123")_create_show_page("ses123", "private")- store = ShowPageStore()- try:- with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(- connection,- resource_kind="show_page",- resource_id="ses123",- organization_id=None,- owner_user_id="user-viewer",- access_level="private",- )- finally:- store.close()manager = _FakeShowRuntimeManager(body=b'<!doctype html><html><body><script type="module" src="/src/main.tsx"></script></body></html>')@@ -3659,15 +3628,10 @@ def test_private_show_page_treats_show_page_email_viewer_as_read_only(monkeypatcfinally:set_show_runtime_manager_for_tests(None)- assert me_response.status_code == 200- assert me_response.get_json() == {"authenticated": False, "canAnnotate": False}- assert page_response.status_code == 200- body = page_response.content.decode("utf-8")- assert '"authenticated":false' in body- assert '"writeToken"' not in body- cookies = "\n".join(page_response.headers.getlist("set-cookie"))- assert "vibe_show_event_token=" in cookies- assert "Max-Age=0" in cookies+ # §3.2: a signed show_page_email grant is a /p-only visitor — it never+ # enters the private /show surface, even for its own signed page.+ assert me_response.status_code == 403+ assert page_response.status_code == 403def test_public_show_me_is_anonymous_without_oauth_session(monkeypatch, tmp_path):@@ -4877,7 +4841,7 @@ def test_private_show_events_stream_ends_at_authorization_refresh_deadline(monkeassert len(asyncio.run(_collect_until_expired())) == 1-def test_private_show_events_stream_ends_when_project_access_is_revoked(monkeypatch, tmp_path):+def test_private_show_events_stream_ignores_project_access_revocation(monkeypatch, tmp_path):from storage import project_access_servicefrom storage.db import create_sqlite_enginefrom vibe.authorization import AuthorizationContext@@ -4895,19 +4859,8 @@ def test_private_show_events_stream_ends_when_project_access_is_revoked(monkeypainstance_access_source="email",is_remote=True,)- engine = create_sqlite_engine()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="show_page",- resource_id="ses123",- organization_id=None,- owner_user_id="remote-editor",- access_level="private",- )- engine.dispose()- async def _collect_until_revoked() -> list[str | bytes]:+ async def _collect_after_project_revocation() -> str:response = await _show_events_stream("ses123",authorization_context=context,@@ -4928,20 +4881,25 @@ def test_private_show_events_stream_ends_when_project_access_is_revoked(monkeypa)assert result.changed is Truebroker.publish("authorization.changed", {"project_ids": ["proj_show"]})- with pytest.raises(StopAsyncIteration):- await asyncio.wait_for(iterator.__anext__(), timeout=1)+ # §3.2: /show admission is the Instance role alone, so a Project ACL+ # revocation must NOT close the stream — the residual Project gate is+ # gone. The stream ends only when the Instance role itself is lost.+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(iterator.__anext__(), timeout=0.2)finally:await iterator.aclose()- return chunks+ return "".join(+ chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk+ for chunk in chunks+ )- assert len(asyncio.run(_collect_until_revoked())) == 1+ assert asyncio.run(_collect_after_project_revocation()) == ": show events connected\n\n"-def test_remote_org_show_events_stream_closes_when_resource_access_is_revoked(+def test_remote_org_show_events_stream_ignores_resource_acl_changes(monkeypatch,tmp_path,):- from storage.db import create_sqlite_enginefrom vibe.authorization import AuthorizationContextfrom vibe.sse_broker import brokerfrom vibe.ui_server import _show_events_stream@@ -4961,19 +4919,8 @@ def test_remote_org_show_events_stream_closes_when_resource_access_is_revoked(instance_access_source="organization_group",is_remote=True,)- engine = create_sqlite_engine()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="show_page",- resource_id="ses123",- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )- engine.dispose()- async def _collect_after_revocation() -> str:+ async def _collect_after_acl_change() -> str:response = await _show_events_stream("ses123",authorization_context=context,@@ -4981,24 +4928,15 @@ def test_remote_org_show_events_stream_closes_when_resource_access_is_revoked(iterator = response.body_iterator.__aiter__()try:chunks = [await iterator.__anext__()]- revoke_engine = create_sqlite_engine()- with revoke_engine.begin() as conn:- resource_access_service.apply_control_plane_intent(- conn,- organization_id="org-1",- resource_kind="show_page",- resource_id="ses123",- revision=1,- access_level="private",- group_ids=[],- )- revoke_engine.dispose()+ # A Resource ACL change must not close the /show events stream:+ # /show admission is instance-role only and no longer reads a+ # resource_access_policies row for the page.broker.publish("authorization.changed",- {"project_ids": [], "resource_kinds": ["show_page"]},+ {"project_ids": [], "resource_kinds": ["agent"]},)- with pytest.raises(StopAsyncIteration):- await asyncio.wait_for(iterator.__anext__(), timeout=1)+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(iterator.__anext__(), timeout=0.2)finally:await iterator.aclose()return "".join(@@ -5006,7 +4944,7 @@ def test_remote_org_show_events_stream_closes_when_resource_access_is_revoked(for chunk in chunks)- body = asyncio.run(_collect_after_revocation())+ body = asyncio.run(_collect_after_acl_change())assert body == ": show events connected\n\n"@@ -7407,6 +7345,91 @@ def test_private_show_page_hmr_websocket_requires_remote_session(monkeypatch, tmassert exc.value.code == ui_server._AUTHORIZATION_LOGIN_REQUIRED_WEBSOCKET_CLOSE_CODE+def test_private_show_page_hmr_websocket_requires_editor(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _create_show_page("ses123", "private")+ manager = _FakeShowRuntimeManager()+ set_show_runtime_manager_for_tests(manager)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _active_org_cookie(config, "[email protected]", "viewer-1", role="viewer"),+ domain="alex.avibe.bot",+ )+ try:+ with client.websocket_connect(+ "wss://alex.avibe.bot/show/ses123/__vite_hmr",+ headers={"host": "alex.avibe.bot"},+ subprotocols=["vite-hmr"],+ ) as websocket:+ websocket.receive_text()+ raise AssertionError("viewer HMR should not connect")+ except WebSocketDisconnect as exc:+ assert exc.code == 1008+ finally:+ set_show_runtime_manager_for_tests(None)+ assert manager.calls == []+++def test_show_page_viewer_is_read_only_but_editor_can_mutate(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ _create_show_page("ses123", "private")++ def _client(role: str):+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _active_org_cookie(config, f"{role}@example.com", f"{role}-1", role=role),+ domain="alex.avibe.bot",+ )+ return client++ manager = _FakeShowRuntimeManager(body=b'{"ok":true}', extra_headers={"content-type": "application/json"})+ set_show_runtime_manager_for_tests(manager)+ try:+ viewer = _client("viewer")+ read = viewer.get(+ "/show/ses123/",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={"Accept": "text/html"},+ follow_redirects=False,+ )+ assert read.status_code == 200+ manager.calls.clear()+ for method in ("post", "put", "patch", "delete"):+ response = getattr(viewer, method)(+ "/show/ses123/api/health",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={+ "Origin": "https://alex.avibe.bot",+ "Content-Type": "application/json",+ },+ content=b'{"ping":true}',+ )+ assert response.status_code == 403+ assert manager.calls == []++ editor = _client("editor")+ mutation = editor.post(+ "/show/ses123/api/health",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ headers={+ "Origin": "https://alex.avibe.bot",+ "Content-Type": "application/json",+ },+ content=b'{"ping":true}',+ )+ assert mutation.status_code == 200+ assert [call[0] for call in manager.calls] == ["POST"]+ finally:+ set_show_runtime_manager_for_tests(None)++def test_private_show_page_hmr_websocket_accepts_remote_session(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)@@ -7461,19 +7484,6 @@ def test_private_show_page_hmr_websocket_closes_when_authorization_is_unavailablmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)_create_show_page("ses123", "private")- from storage.db import create_sqlite_engine-- engine = create_sqlite_engine()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="show_page",- resource_id="ses123",- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )- engine.dispose()monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)@@ -7482,7 +7492,7 @@ def test_private_show_page_hmr_websocket_closes_when_authorization_is_unavailablui_server,"_show_runtime_websocket_resource_context",lambda websocket, **kwargs: resource_access_service.ResourceUserContext(- instance_role="viewer",+ instance_role="editor",subject="remote-member",instance_access_source="organization_group",organization_id="org-1",@@ -7493,7 +7503,7 @@ def test_private_show_page_hmr_websocket_closes_when_authorization_is_unavailabl)remote_payload = {"sub": "remote-member",- "vibe_instance_role": "viewer",+ "vibe_instance_role": "editor","vibe_instance_access_source": "organization_group","vibe_organization_id": "org-1","vibe_organization_member_id": "membership-1",@@ -7527,11 +7537,10 @@ def test_private_show_page_hmr_websocket_closes_when_authorization_is_unavailablassert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]-def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(+def test_remote_org_show_page_hmr_ignores_resource_acl_changes(monkeypatch,tmp_path,):- from storage.db import create_sqlite_enginefrom vibe.sse_broker import brokerclass RecordingWebSocket:@@ -7562,17 +7571,6 @@ def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(_save_config(tmp_path)_create_agent_session("ses123")_create_show_page("ses123", "private")- engine = create_sqlite_engine()- with engine.begin() as conn:- resource_access_service.ensure_resource_policy(- conn,- resource_kind="show_page",- resource_id="ses123",- organization_id="org-1",- owner_user_id="owner-1",- access_level="public",- )- engine.dispose()monkeypatch.setattr(ui_server, "_show_runtime_hmr_origin_allowed", lambda websocket: True)monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)@@ -7620,34 +7618,23 @@ def test_remote_org_show_page_hmr_closes_when_resource_access_is_revoked(monkeypatch.setattr(ui_server, "_proxy_show_runtime_websocket", blocking_proxy)websocket = RecordingWebSocket()- async def _run_after_revocation() -> None:+ async def _run_after_acl_change() -> None:task = asyncio.create_task(ui_server.show_runtime_hmr_websocket(websocket, "ses123"))await asyncio.wait_for(proxy_started.wait(), timeout=1)- revoke_engine = create_sqlite_engine()- with revoke_engine.begin() as conn:- result = resource_access_service.apply_control_plane_intent(- conn,- organization_id="org-1",- resource_kind="show_page",- resource_id="ses123",- revision=1,- access_level="private",- group_ids=[],- )- revoke_engine.dispose()- assert result["status"] == "applied"+ # A Resource ACL change must not close the /show HMR socket: /show+ # admission is instance-role only and no longer reads a page policy.broker.publish("authorization.changed",- {"project_ids": [], "resource_kinds": ["show_page"]},+ {"project_ids": [], "resource_kinds": ["agent"]},)- await asyncio.wait_for(task, timeout=1)+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(task, timeout=0.2)+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)- asyncio.run(_run_after_revocation())+ asyncio.run(_run_after_acl_change())- assert websocket.calls == [- ("accept", "vite-hmr"),- ("close", ui_server._AUTHORIZATION_REVOKED_WEBSOCKET_CLOSE_CODE),- ]+ assert websocket.calls == [("accept", "vite-hmr")]assert proxy_calls == [("started", "ses123"), ("cancelled", "ses123")]diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 7d3983432..960fb8933 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -1640,7 +1640,11 @@ export const ChatPage: React.FC = () => {onAuthorizationChanged: (data) => {const currentSessionId = sessionIdRef.current;if (!currentSessionId) return;- if (data.resource_kinds?.includes('show_page')) {+ // §3.2: /show admission follows the Instance Viewer role, so it is the+ // instance authorization revision (role ladder), not a per-resource ACL,+ // that can flip this session's page access. show_page no longer appears+ // in resource_kinds, so probe on the revision change instead.+ if (data.instance_authorization_revision != null) {void probeShowPageAccess(currentSessionId);}setSessionCanChat(false);diff --git a/vibe/api.py b/vibe/api.pyindex 0c237211a..e643fdf4a 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1562,24 +1562,12 @@ def list_show_pages(*, user_context: Any = None) -> dict:try:result = store.list_page(page_request=None, user_context=user_context)pages = [show_page_payload(page, config=config) for page in result.items]- with store.engine.connect() as connection:- for payload in pages:- session_id = payload["session_id"]- payload["can_manage"] = (- resource_access_service.can_manage_show_page_access(- context,- session_id,- connection=connection,- )- )- payload["can_publish_public"] = (- resource_access_service.can_control_resource_sharing(- context,- "show_page",- session_id,- connection=connection,- )- )+ # §3.2: management and sharing control follow the Instance Editor role+ # alone — show_page no longer has a Resource ACL row to consult.+ can_manage = context.has_role("editor")+ for payload in pages:+ payload["can_manage"] = can_manage+ payload["can_publish_public"] = can_managefinally:store.close()_apply_session_meta(pages)@@ -1604,13 +1592,10 @@ def _show_page_mutation_response(from storage import resource_access_servicecontext = resource_access_service.resolve_resource_access_context(user_context)- with store.engine.connect() as connection:- can_use = resource_access_service.can_use_resource(- context,- "show_page",- page.session_id,- connection=connection,- )+ can_use = (+ context.has_role("viewer")+ and context.instance_access_source != "show_page_email"+ )if not can_use:# Access managers may take a page offline without page-use access. Do# not return page paths, URLs, share IDs, audience, or session metadata.@@ -1700,7 +1685,12 @@ def get_show_page(session_id: str, *, user_context: Any = None) -> dict:def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:- """Return the applied authenticated audience and sharing authority."""+ """Return the applied authenticated audience and sharing authority.++ §3.2 removed show_page from the Resource ACL, so there is no policy row:+ the ownership fence drives ``mode``/``ownership_status`` and the Instance+ role alone drives ``can_use``/``can_manage``/``can_publish_public``.+ """from core.show_pages import ShowPageError, ShowPageStorefrom storage import resource_access_service@@ -1711,50 +1701,31 @@ def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:page = store.get(session_id)if page is None:raise ShowPageError("This session has no Show Page.", code="show_page_not_found")- reconciliation = store.reconcile_resource_policy(- page.session_id,- user_context=context,+ reconciliation = store.reconcile_resource_policy(page.session_id)+ can_use = (+ context.has_role("viewer")+ and context.instance_access_source != "show_page_email")- with store.engine.connect() as connection:- policy = reconciliation["policy"]- can_use = resource_access_service.can_use_resource(- context,- "show_page",- page.session_id,- connection=connection,- )- can_manage = resource_access_service.can_manage_show_page_access(- context,- page.session_id,- connection=connection,- )- can_publish_public = resource_access_service.can_control_resource_sharing(- context,- "show_page",- page.session_id,- connection=connection,- )- if not (can_use or can_manage):- raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")+ can_manage = context.has_role("editor")+ can_publish_public = context.has_role("editor")+ if not (can_use or can_manage):+ raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")finally:store.close()ownership = reconciliation["ownership"]organization_id = ownership.get("organization_id")- policy_organization_id = policy.get("organization_id") if policy else Nonereturn {"ok": True,"mode": ownership["mode"],"ownership_status": reconciliation["status"],"instance_id": ownership.get("instance_id"),"organization_id": organization_id,- "policy_organization_id": policy_organization_id,- "access_level": policy.get("access_level", "private") if policy else "private",- "group_ids": list(policy.get("group_ids") or []) if policy else [],- "policy_revision": policy.get("policy_revision") if policy else None,- "last_applied_control_plane_revision": (- policy.get("last_applied_control_plane_revision") if policy else None- ),+ "policy_organization_id": None,+ "access_level": "private",+ "group_ids": [],+ "policy_revision": None,+ "last_applied_control_plane_revision": None,"can_use": can_use,"can_manage": can_manage,"can_publish_public": can_publish_public,@@ -1775,17 +1746,11 @@ def require_show_access_settings_control(page = store.get(session_id)if page is None:raise ShowPageError("This session has no Show Page.", code="show_page_not_found")- with store.engine.connect() as connection:- if not resource_access_service.can_control_resource_sharing(- context,- "show_page",- page.session_id,- connection=connection,- ):- raise ShowPageError(- "Show Page access is not permitted.",- code="resource_access_forbidden",- )+ if not context.has_role("editor"):+ raise ShowPageError(+ "Show Page access is not permitted.",+ code="resource_access_forbidden",+ )finally:store.close()diff --git a/vibe/authorization.py b/vibe/authorization.pyindex c6062c750..4a32d8c41 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -30,7 +30,6 @@ _RESOURCE_USE_MINIMUM_ROLES = {"agent": "editor","skill": "editor","vault_secret": "editor",- "show_page": "viewer",}_VIEWER_WORKBENCH_EVENTS = frozenset(@@ -163,7 +162,7 @@ class AuthorizationContext:"can_use_agents": self.can_use_resource("agent"),"can_use_skills": self.can_use_resource("skill"),"can_use_vault_secrets": self.can_use_resource("vault_secret"),- "can_use_show_pages": self.can_use_resource("show_page"),+ "can_use_show_pages": self.can_read_instance,"can_use_terminal_files": self.can_use_terminal_files,"can_use_terminal": self.can_use_terminal,"can_use_files": self.can_use_files,diff --git a/vibe/permissions.py b/vibe/permissions.pyindex eb2d61136..b41f5e623 100644--- a/vibe/permissions.py+++ b/vibe/permissions.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom dataclasses import dataclass+from datetime import datetime, timezoneimport jsonimport loggingimport os@@ -16,7 +17,13 @@ from urllib.parse import quote, urlsplitimport requestsfrom config import paths-from config.v2_config import V2Config+from config.v2_config import V2Config, config_file_lock++from sqlalchemy import select+from sqlalchemy.engine import Connection++from storage.db import get_cached_sqlite_engine+from storage.models import state_metaCACHE_SCHEMA_VERSION = 1@@ -33,7 +40,7 @@ _ACCESS_ROLES = frozenset({"viewer", "editor"})_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})_PROJECT_ACCESS_MODES = frozenset({"inherit", "restricted"})_PROJECT_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})-_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})+_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill"})_RESOURCE_ACCESS_LEVELS = frozenset({"private", "public", "scope"})_RESOURCE_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error"})_POLICY_SYNC_STATUSES = frozenset({"none", "in_sync", "applying", "offline", "error"})@@ -43,6 +50,17 @@ _PROJECT_ID_DOT_SEGMENTS = frozenset({".", ".."})logger = logging.getLogger(__name__)_CACHE_LOCK = threading.RLock()+# Show Page instance-ownership fence constants. These are pairing metadata, not+# Resource ACL: they resolve whether the paired instance is personal or bound to+# an organization so the `/p` sharing axis can stamp group/organization entries.+SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY = "show_page_instance_ownership"+SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE = "configuration_unavailable"+_CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE = object()+++def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+class PermissionsError(RuntimeError):"""Base error for the local Permissions boundary."""@@ -64,6 +82,10 @@ class PermissionsInvalidResponseError(PermissionsError):pass+class PermissionsInvalidRequestError(PermissionsError):+ """The caller asked for something the current-instance API does not serve."""++class PermissionsBackendError(PermissionsError):def __init__(self, status: int, payload: Mapping[str, Any] | None = None):self.status = status@@ -182,7 +204,8 @@ def _require_project_id(value: Any) -> None:def _require_resource_identity(resource_kind: Any, resource_id: Any) -> tuple[str, str]:- _require_enum(resource_kind, _RESOURCE_KINDS)+ if not isinstance(resource_kind, str) or resource_kind not in _RESOURCE_KINDS:+ raise PermissionsInvalidRequestError("invalid_resource_kind")if (not isinstance(resource_id, str)or resource_id != resource_id.strip()@@ -190,7 +213,7 @@ def _require_resource_identity(resource_kind: Any, resource_id: Any) -> tuple[stor len(resource_id) > 200or any(ord(char) < 32 or ord(char) == 127 for char in resource_id)):- raise PermissionsInvalidResponseError("invalid_resource_id")+ raise PermissionsInvalidRequestError("invalid_resource_id")return resource_kind, resource_id@@ -1260,13 +1283,181 @@ def update_resource_access()+def _clean_show_page_identifier(value: Any, *, limit: int = 200) -> str | None:+ if not isinstance(value, str):+ return None+ cleaned = value.strip()+ if not cleaned or len(cleaned) > limit or any(ord(char) < 32 or ord(char) == 127 for char in cleaned):+ return None+ return cleaned+++def _configured_show_page_instance() -> tuple[str, str] | None | object:+ try:+ cloud = V2Config.load().remote_access.vibe_cloud+ credentials = cloud.runtime_credentials()+ if credentials is None:+ return None+ if not isinstance(credentials, (tuple, list)) or len(credentials) != 3:+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE+ instance_id = _clean_show_page_identifier(credentials[1])+ if instance_id is None or cloud.instance_kind not in {"personal", "organization"}:+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE+ except (+ AttributeError,+ FileNotFoundError,+ IndexError,+ KeyError,+ OSError,+ TypeError,+ ValueError,+ ):+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE+ return instance_id, cloud.instance_kind+++def _show_page_configuration_unavailable_ownership() -> dict[str, Any]:+ return {+ "mode": SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,+ "instance_id": None,+ "organization_id": None,+ "source": "config",+ }+++def _stored_show_page_instance_ownership(connection: Connection) -> dict[str, Any] | None:+ raw_value = connection.execute(+ select(state_meta.c.value_json).where(+ state_meta.c.key == SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY+ )+ ).scalar_one_or_none()+ try:+ payload = json.loads(raw_value) if raw_value else None+ except (TypeError, ValueError):+ return None+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ return None+ instance_id = _clean_show_page_identifier(payload.get("instance_id"))+ mode = payload.get("mode")+ organization_id = _clean_show_page_identifier(payload.get("organization_id"))+ if instance_id is None or mode not in {"personal", "organization"}:+ return None+ if mode == "organization" and organization_id is None:+ return None+ if mode == "personal" and organization_id is not None:+ return None+ return {+ "mode": mode,+ "instance_id": instance_id,+ "organization_id": organization_id,+ "source": "stored",+ }+++def current_show_page_instance_ownership(+ *,+ connection: Connection | None = None,+) -> dict[str, Any]:+ """Return the persisted ownership fence for the exact current pairing."""++ configured = _configured_show_page_instance()+ if configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE:+ return _show_page_configuration_unavailable_ownership()+ if configured is None:+ return {+ "mode": "unmanaged",+ "instance_id": None,+ "organization_id": None,+ "source": "config",+ }+ instance_id, instance_kind = configured+ if connection is not None:+ stored = _stored_show_page_instance_ownership(connection)+ else:+ engine = get_cached_sqlite_engine()+ with engine.begin() as conn:+ stored = _stored_show_page_instance_ownership(conn)+ exact_stored = stored if stored and stored["instance_id"] == instance_id else None+ if instance_kind == "personal":+ return {+ "mode": "personal",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+ if instance_kind == "organization":+ if exact_stored and exact_stored["mode"] == "organization":+ return exact_stored+ return {+ "mode": "organization_pending",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+ if exact_stored is not None:+ return exact_stored+ return {+ "mode": "unmanaged",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+++def remember_show_page_instance_ownership(+ connection: Connection,+ ownership: Mapping[str, Any],+) -> dict[str, Any]:+ """Persist an authoritative binding only while its exact pairing is current."""++ with config_file_lock():+ return _remember_show_page_instance_ownership_locked(connection, ownership)+++def _remember_show_page_instance_ownership_locked(+ connection: Connection,+ ownership: Mapping[str, Any],+) -> dict[str, Any]:+ """Implement ownership persistence while the pairing lock is held."""++ configured = _configured_show_page_instance()+ instance_id = _clean_show_page_identifier(ownership.get("instance_id"))+ mode = ownership.get("mode")+ organization_id = _clean_show_page_identifier(ownership.get("organization_id"))+ if (+ configured is None+ or configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE+ or instance_id is None+ or instance_id != configured[0]+ or mode not in {"personal", "organization"}+ or configured[1] != mode+ or (mode == "organization") != bool(organization_id)+ ):+ return current_show_page_instance_ownership(connection=connection)+ payload = {+ "schema_version": 1,+ "instance_id": instance_id,+ "mode": mode,+ "organization_id": organization_id,+ }+ connection.execute(+ state_meta.delete().where(state_meta.c.key == SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY)+ )+ connection.execute(+ state_meta.insert().values(+ key=SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY,+ value_json=json.dumps(payload, separators=(",", ":")),+ updated_at=_utc_now_iso(),+ )+ )+ return {**payload, "source": str(ownership.get("source") or "live")}++def resolve_current_instance_ownership(config: V2Config | None = None,) -> dict[str, Any]:"""Resolve exact-instance ownership without trusting browser claims."""- from storage import resource_access_service-try:config = config or V2Config.load()credentials = config.remote_access.vibe_cloud.runtime_credentials()@@ -1280,7 +1471,7 @@ def resolve_current_instance_ownership(ValueError,):return {- "mode": resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,+ "mode": SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,"instance_id": None,"organization_id": None,"source": "config",@@ -1299,17 +1490,17 @@ def resolve_current_instance_ownership(or not credentials[1].strip()):return {- "mode": resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,+ "mode": SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,"instance_id": None,"organization_id": None,"source": "config",}- current = resource_access_service.current_show_page_instance_ownership()+ current = current_show_page_instance_ownership()if current["mode"] in {"personal","organization",- resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,+ SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,}:return currenttry:@@ -1319,20 +1510,26 @@ def resolve_current_instance_ownership(instance = result.projection["instance"]organization = instance.get("organization")if isinstance(organization, Mapping):- return {+ ownership = {"mode": "organization","instance_id": credentials[1],"organization_id": organization["id"],"source": result.source,}- if "organization" in instance or config.remote_access.vibe_cloud.instance_kind == "personal":- return {+ elif "organization" in instance or config.remote_access.vibe_cloud.instance_kind == "personal":+ ownership = {"mode": "personal","instance_id": credentials[1],"organization_id": None,"source": result.source,}- return current+ else:+ return current+ # Persist a definitive binding so a later offline resolution falls back to+ # the exact-instance fence instead of re-querying the Permissions backend.+ engine = get_cached_sqlite_engine()+ with engine.begin() as conn:+ return remember_show_page_instance_ownership(conn, ownership)def _local_instance_display(diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex f15b8acb0..fb0cc53bb 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -146,7 +146,7 @@ _RESOURCE_ACL_SYNC_LOCK = threading.Lock()_RESOURCE_ACL_SYNC_POLL_LOCK = threading.Lock()_RESOURCE_ACL_SYNC_POLL_STARTED = False_RESOURCE_ACL_SYNC_ERROR_CODE_RE = re.compile(r"\A[a-z0-9][a-z0-9_:-]{0,119}\Z")-_RESOURCE_ACL_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})+_RESOURCE_ACL_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill"})_RESOURCE_ACL_ACCESS_LEVELS = frozenset({"public", "scope", "private"})_RESOURCE_ACL_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})_RESOURCE_ACL_MAX_REVISION = (1 << 53) - 1@@ -2028,10 +2028,6 @@ def _local_resource_metadata(connection, resource_kind: str, resource_id: str) -from core.services.skills import get_skill_resource_metadatareturn get_skill_resource_metadata(resource_id)- if resource_kind == "show_page":- from core.show_pages import get_show_page_resource_metadata-- return get_show_page_resource_metadata(connection, resource_id)return Nonediff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 3cacf5000..c09326636 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2681,6 +2681,8 @@ def _permissions_error_response(error: Exception):return jsonify({"ok": False, **error.payload}), error.statusif isinstance(error, permissions.PermissionsInvalidResponseError):return jsonify({"ok": False, "error": str(error)}), 502+ if isinstance(error, permissions.PermissionsInvalidRequestError):+ return jsonify({"ok": False, "error": str(error)}), 422logger.warning("Permissions request failed: %s", error.__class__.__name__)return jsonify({"ok": False, "error": "permissions_unavailable"}), 503@@ -2939,10 +2941,11 @@ def enforce_project_role_capabilities():kind, resource_id = resourceif kind == "show_page":- # Show Page reads are governed by the page's own ACL. Project ACL is- # required by ShowPageStore for create/edit operations, but applying- # the generic project middleware here treats a session id as a project- # id and rejects valid pages (including pages without a live session).+ # Show Page ``/show`` admission is the §3.2 Instance Viewer role alone.+ # Project ACL is required by ShowPageStore for create/edit operations,+ # but applying the generic project middleware here treats a session id+ # as a project id and rejects valid pages (including pages without a+ # live session).return Noneengine = create_sqlite_engine()with engine.connect() as conn:@@ -3280,11 +3283,9 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):from vibe.authorization import context_from_session_payloadauthorization_context = context_from_session_payload(remote_payload)- if not _websocket_context_authorized(- authorization_context,- minimum_role="viewer",- project_session_id=session_id,- ):+ # §3.2: HMR drives live mutation of the page, so it is an Editor surface.+ # A Viewer may read /show but must not open HMR (nor POST/PUT/PATCH/DELETE).+ if not _show_page_mutation_allowed(authorization_context):await websocket.close(code=1008)return@@ -3316,9 +3317,7 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):from vibe.sse_broker import brokeraccess_sub_id, access_queue = broker.subscribe()- if not authorization_context.has_role("viewer") or not _show_page_resource_access_allowed(- authorization_context, session_id- ):+ if not _show_page_mutation_allowed(authorization_context):broker.unsubscribe(access_sub_id)await websocket.close(code=1008)return@@ -3621,8 +3620,8 @@ def _websocket_context_authorized(if project_session_id is None or _has_runtime_owner_access(context):return Trueif minimum_role == "viewer":- # Show Page runtime reads use the independent Show Page ACL. Project- # ACL remains an edit/create requirement in ShowPageStore.+ # §3.2: /show admission is the Instance Viewer role alone, independent of+ # the Project ACL (which stays an edit/create requirement in ShowPageStore).return context.has_role("viewer") and _show_page_resource_access_allowed(context, project_session_id)return _project_session_access_allowed(context, project_session_id, minimum_role)@@ -3679,25 +3678,39 @@ async def _wait_for_show_page_access_loss(event_type, _payload = await queue.get()if event_type != "authorization.changed":continue- if not context.has_role("viewer") or not _show_page_resource_access_allowed(context, session_id):+ if not _show_page_mutation_allowed(context):returndef _show_page_resource_access_allowed(context: Any, session_id: str) -> bool:- from storage import resource_access_service+ """§3.2 ``/show`` admission: Instance Viewer role alone, never an email grant.++ The Workbench is reachable by every Instance role (owner/editor/viewer) and+ independent of the sharing list. A signed ``show_page_email`` session is a+ ``/p``-only read visitor, so it never enters ``/show``. show_page has no+ Resource ACL row anymore, so nothing is read from ``resource_access_service``.+ ``session_id`` is retained for call-site symmetry but the decision does not+ depend on it.+ """if context is None:return False- if context.instance_access_source == "show_page_email":- return context.can_use_show_page(session_id)- try:- return resource_access_service.can_use_resource(- context,- "show_page",- session_id,- )- except resource_access_service.ResourceAccessError:+ return context.has_role("viewer") and context.instance_access_source != "show_page_email"+++def _show_page_mutation_allowed(context: Any) -> bool:+ """§3.2 mutation boundary: only an Instance Editor/owner may drive ``/show``.++ ``/show`` reads admit every Instance Viewer, but the route also forwards+ POST/PUT/PATCH/DELETE to Show Runtime and exposes a live HMR websocket —+ both mutation surfaces. Viewers stay read-only: mutations and HMR require+ ``has_role("editor")``. A ``show_page_email`` session is Viewer-only, so it+ can never pass an Editor check.+ """++ if context is None:return False+ return context.has_role("editor") and context.instance_access_source != "show_page_email"async def _wait_for_remote_session_authorization_loss(@@ -5670,7 +5683,6 @@ def _show_page_payload_for_request(payload: dict, context: Any = None) -> dict:def _show_page_payload_for_connection(payload: dict, context: Any, conn: Any) -> dict:from storage import project_access_service- from storage import resource_access_servicesession_id = str(payload.get("session_id") or "")if not project_access_service.session_exists(conn, session_id):@@ -5683,15 +5695,10 @@ def _show_page_payload_for_connection(payload: dict, context: Any, conn: Any) ->)if project_access_service.role_allows(effective_role, "editor"):return payload- # Legacy and IM-scoped pages have no project role. Their resource ACL- # remains the authority for the page owner/editor, but it must not override- # an effective project Viewer downgrade on project-attached sessions.- if project_id is None and resource_access_service.can_manage_resource_acl(- context,- "show_page",- session_id,- connection=conn,- ):+ # Legacy and IM-scoped pages have no project role. §3.2 makes the Instance+ # Editor role their authority for the page owner/editor, but it must not+ # override an effective project Viewer downgrade on project-attached sessions.+ if project_id is None and context.has_role("editor"):return payloadreturn {key: value for key, value in payload.items() if key != "path"}@@ -10394,12 +10401,12 @@ def _media_row_show_page_access_allowed(context: Any, row: dict[str, Any]) -> bo"""Whether *context* may still read a Show annotation's screenshot bytes.A `show_annotation` screenshot is part of the page it was drawn on, so it- inherits that page's resource ACL rather than only the Project/session role- the rest of the media proxy checks. Without this the media token outlives- the access that produced it: a caller who saw a private page once keeps its- screenshot readable after the page policy stops naming them, and being the- Instance owner does not override the page ACL either -- a direct read of a- page owned by another subject is denied, so its screenshot must be too.+ inherits the page's ``/show`` admission (the §3.2 Instance Viewer gate)+ rather than only the Project/session role the rest of the media proxy+ checks. Without this the media token outlives the access that produced it:+ a caller who saw the Workbench once keeps its screenshot readable after+ their Instance role is revoked, and an email-grant ``/p`` visitor never+ reaches the annotation bytes at all.Media from any other source is unaffected and keeps the Project/sessionauthorization below as its only gate.@@ -10421,6 +10428,12 @@ def _request_can_read_media_row(conn, token: str, row: dict[str, Any]) -> bool:context = getattr(g, "authorization_context", None)if not _media_row_show_page_access_allowed(context, row):return False+ if (row.get("source") or "") == "show_annotation":+ # §3.2: annotation media inherits the /show Instance Viewer gate alone+ # (already applied by _media_row_show_page_access_allowed). The+ # Project/session role below must not stack on top, or an admitted+ # Instance Viewer who is outside the page's Project loses the screenshot.+ return Trueif context is None or _has_runtime_owner_access(context):return Truesession_ids = media_service.referenced_session_ids(conn, token)@@ -11600,11 +11613,10 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)if context is None:return Trueif event_type == "show.event":- # A Show Page carries its own resource ACL, and being the Instance owner- # does not override it: a direct read of a page whose policy names- # another subject is denied, so the workbench stream must not hand the- # same page's annotation text and attachment metadata to that owner- # either. Fail closed when the frame has no session to check.+ # A Show Page's Workbench stream follows §3.2 Instance Viewer admission,+ # so any Instance role sees its page's live events while an email-grant+ # ``/p`` visitor never receives annotation text or attachment metadata.+ # Fail closed when the frame has no session to check.data = _workbench_event_data(payload)session_id = data.get("session_id") if data else Noneif not isinstance(session_id, str) or not session_id:@@ -11612,8 +11624,8 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)if not _show_page_resource_access_allowed(context, session_id):return False# Show Page event visibility is intentionally independent from Project- # ACL. Project ACL gates page creation/editing, while the page ACL gates- # Viewer reads and live event delivery.+ # ACL. Project ACL gates page creation/editing, while §3.2 instance+ # admission gates Viewer reads and live event delivery.return context.has_role("viewer")if _has_runtime_owner_access(context):return True@@ -13772,16 +13784,9 @@ async def _show_events_stream(yield _remote_authorization_sse_frame(state)returnyield ": show events connected\n\n"- if not public and (- not _project_session_access_allowed(- authorization_context,- session_id,- "viewer",- )- or not _show_page_resource_access_allowed(- authorization_context,- session_id,- )+ if not public and not _show_page_resource_access_allowed(+ authorization_context,+ session_id,):if remote_session_payload is not None:yield _remote_authorization_sse_frame("revoked")@@ -13827,11 +13832,7 @@ async def _show_events_stream(decoded = json.loads(payload)event_payload = decoded.get("data") if isinstance(decoded, dict) else Noneif event_type == "authorization.changed" and not public:- if not _project_session_access_allowed(- authorization_context,- session_id,- "viewer",- ) or not _show_page_resource_access_allowed(+ if not _show_page_resource_access_allowed(authorization_context,session_id,):@@ -14776,6 +14777,12 @@ async def serve_private_show_page(session_id, asset_path):author=show_author,page=page,)+ # §3.2: /show reads admit every Instance Viewer, but the route forwards+ # mutation methods straight to Show Runtime — keep Viewers read-only.+ if request.method not in {"GET", "HEAD"} and not _show_page_mutation_allowed(+ _request_authorization_context()+ ):+ return _show_page_access_forbidden_response()if asset_path.strip("/") == "__show/me":if request.method not in {"GET", "HEAD"}:return jsonify({"ok": False, "code": "method_not_allowed"}), 405