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): heterogeneous limited-access entries (#1595)
Max84702f736814
diff --git a/core/show_pages.py b/core/show_pages.pyindex 4b8cc2b79..c650fb06c 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -6,6 +6,7 @@ import hmacimport osimport secretsimport stat as stat_module+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom html.parser import HTMLParser@@ -23,7 +24,7 @@ from core.avibe_cloud import avibe_cloud_connect_guidance, base_public_urlfrom core.show_git import format_agent_contractfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config-from storage.models import agent_sessions, show_page_authorized_emails, show_pages+from storage.models import agent_sessions, show_page_access_entries, show_pagesfrom storage.pagination import PageRequest, PageResult, page_sequenceVISIBILITY_PRIVATE = "private"@@ -40,7 +41,33 @@ ACCESS_MODE_PRIVATE = "private"ACCESS_MODE_LIMITED = "limited"ACCESS_MODE_PUBLIC = "public"ACCESS_MODES = {ACCESS_MODE_PRIVATE, ACCESS_MODE_LIMITED, ACCESS_MODE_PUBLIC}+# The Limited audience is one heterogeneous set of read-only grants, OR-ed at+# admission: an email, an organization group, or "everyone in this+# organization". They are peers -- no kind outranks or implies another.+ACCESS_ENTRY_KIND_EMAIL = "email"+ACCESS_ENTRY_KIND_GROUP = "group"+ACCESS_ENTRY_KIND_ORGANIZATION = "organization"+ACCESS_ENTRY_KINDS = (+ ACCESS_ENTRY_KIND_EMAIL,+ ACCESS_ENTRY_KIND_GROUP,+ ACCESS_ENTRY_KIND_ORGANIZATION,+)+# Kinds whose meaning is relative to the organization that owns the page. A+# Personal instance has no organization, so it can hold none of them.+ORGANIZATION_ACCESS_ENTRY_KINDS = (+ ACCESS_ENTRY_KIND_GROUP,+ ACCESS_ENTRY_KIND_ORGANIZATION,+)SHOW_ACCESS_EMAIL_MAX_COUNT = 64+SHOW_ACCESS_GROUP_MAX_COUNT = 64+# Per-kind write caps. "This organization may read" is one switch, so it caps at+# one; the list kinds get the same bound the email audience already had.+SHOW_ACCESS_ENTRY_MAX_COUNTS = {+ ACCESS_ENTRY_KIND_EMAIL: SHOW_ACCESS_EMAIL_MAX_COUNT,+ ACCESS_ENTRY_KIND_GROUP: SHOW_ACCESS_GROUP_MAX_COUNT,+ ACCESS_ENTRY_KIND_ORGANIZATION: 1,+}+SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH = 320SHARE_ID_BYTES = 8SHOW_EVENT_WRITE_TOKEN_COOKIE = "vibe_show_event_token"SHOW_EVENT_WRITE_TOKEN_HEADER = "X-Vibe-Show-Token"@@ -118,13 +145,53 @@ class ShowPage:return VISIBILITY_OFFLINE if self.offline else self.access_mode+@dataclass(frozen=True)+class ShowAccessEntry:+ """One read-only grant in a Limited audience.++ ``organization_id`` is set for ``group`` and ``organization`` entries and is+ always the organization that owns the page -- never one the caller names.+ """++ kind: str+ value: str+ organization_id: str | None = None++@dataclass(frozen=True)class ShowAccess:page_id: straccess_mode: strshare_id: str | Nonerevision: int- normalized_emails: tuple[str, ...]+ entries: tuple[ShowAccessEntry, ...] = ()+ # Kept as a stored field so existing constructors that pass+ # ``normalized_emails=`` still construct, and so equality for those+ # callers stays email-shaped. It is always the email slice of ``entries``.+ normalized_emails: tuple[str, ...] = ()++ def __post_init__(self) -> None:+ if self.normalized_emails and not self.entries:+ object.__setattr__(+ self,+ "entries",+ tuple(+ ShowAccessEntry(kind=ACCESS_ENTRY_KIND_EMAIL, value=email)+ for email in self.normalized_emails+ ),+ )+ object.__setattr__(+ self,+ "normalized_emails",+ tuple(+ entry.value+ for entry in self.entries+ if entry.kind == ACCESS_ENTRY_KIND_EMAIL+ ),+ )++ def entries_of_kind(self, kind: str) -> tuple[ShowAccessEntry, ...]:+ return tuple(entry for entry in self.entries if entry.kind == kind)@dataclass(frozen=True)@@ -213,7 +280,123 @@ def normalize_show_access_emails(emails: list[str] | tuple[str, ...]) -> tuple[sreturn tuple(sorted({normalize_show_access_email(email) for email in emails}))+def _normalize_opaque_entry_value(raw: Any) -> str:+ """Normalize a group/organization identifier: an opaque, non-empty string."""++ if not isinstance(raw, str):+ raise ShowPageError("Invalid Show Page access entry.", code="invalid_access_entry")+ value = raw.strip()+ if not value or len(value) > SHOW_ACCESS_ENTRY_VALUE_MAX_LENGTH:+ raise ShowPageError("Invalid Show Page access entry.", code="invalid_access_entry")+ return value+++def _entry_fields(raw: Any) -> tuple[Any, Any, Any]:+ if isinstance(raw, ShowAccessEntry):+ return raw.kind, raw.value, raw.organization_id+ if isinstance(raw, Mapping):+ unexpected = set(raw) - {"kind", "value", "organization_id"}+ if unexpected:+ raise ShowPageError(+ "Invalid Show Page access entry.", code="invalid_access_entry"+ )+ return raw.get("kind"), raw.get("value"), raw.get("organization_id")+ raise ShowPageError("Invalid Show Page access entry.", code="invalid_access_entry")+++def normalize_show_access_entries(+ entries: Any,+ *,+ page_organization_id: str | None,+) -> tuple[ShowAccessEntry, ...]:+ """Validate one complete audience against the page's own organization.++ ``page_organization_id`` is the server's answer to "which organization owns+ this instance", so a group or organization entry is only ever stored for+ that organization: a caller-named one that disagrees is rejected rather than+ quietly rewritten, and a Personal instance (no organization) accepts email+ entries only.+ """++ if isinstance(entries, (str, bytes, Mapping)) or not isinstance(entries, Iterable):+ raise ShowPageError(+ "Invalid Show Page access entry list.", code="invalid_access_entry"+ )++ normalized: dict[tuple[str, str], ShowAccessEntry] = {}+ for raw in entries:+ kind, value, organization_id = _entry_fields(raw)+ if kind not in ACCESS_ENTRY_KINDS:+ raise ShowPageError(+ "Invalid Show Page access entry.", code="invalid_access_entry"+ )+ if kind == ACCESS_ENTRY_KIND_EMAIL:+ if organization_id is not None:+ raise ShowPageError(+ "An email Show Page access entry has no organization.",+ code="invalid_access_entry",+ )++ normalized_value = normalize_show_access_email(value)+ entry_organization_id = None+ else:+ if page_organization_id is None:+ raise ShowPageError(+ "This instance has no organization, so it has no "+ f"{kind} Show Page access entries.",+ code="invalid_access_entry",+ )+ # An organization entry names the page's organization in both+ # fields; a group entry only in ``organization_id``. Whatever the+ # caller supplied has to agree with the server's answer, which is+ # what gets stored -- a cross-organization group is rejected, not+ # rewritten into the local one.+ claimed = [organization_id]+ if kind == ACCESS_ENTRY_KIND_ORGANIZATION:+ claimed.append(value)+ if any(+ _normalize_opaque_entry_value(claim) != page_organization_id+ for claim in claimed+ if claim is not None+ ):+ raise ShowPageError(+ "A Show Page access entry cannot name another organization.",+ code="invalid_access_entry",+ )+ entry_organization_id = page_organization_id+ normalized_value = (+ page_organization_id+ if kind == ACCESS_ENTRY_KIND_ORGANIZATION+ else _normalize_opaque_entry_value(value)+ )+ normalized[(kind, normalized_value)] = ShowAccessEntry(+ kind=kind,+ value=normalized_value,+ organization_id=entry_organization_id,+ )++ for kind, limit in SHOW_ACCESS_ENTRY_MAX_COUNTS.items():+ if sum(1 for entry_kind, _ in normalized if entry_kind == kind) > limit:+ raise ShowPageError(+ f"A Show Page may grant access to at most {limit} {kind} entries.",+ code="invalid_access_entry",+ )+ return tuple(normalized[key] for key in sorted(normalized))+++def show_access_entry_payload(entry: ShowAccessEntry) -> dict[str, Any]:+ return {+ "kind": entry.kind,+ "value": entry.value,+ "organization_id": entry.organization_id,+ }++def show_access_payload(show_access: ShowAccess) -> dict[str, Any]:+ # The wire shape stays email-only until the admission/UI lanes consume the+ # heterogeneous set. ``show_access_entry_payload`` and ``ShowAccess.entries``+ # are the additive surface those lanes read; putting ``entries`` on this+ # payload here would change the internal-server JSON contract in this lane.return {"page_id": show_access.page_id,"access_mode": show_access.access_mode,@@ -457,9 +640,19 @@ class ShowPageStore:expected_revision: int,target_access_mode: str,target_share_id: str | None,- target_emails: list[str] | tuple[str, ...],+ target_emails: list[str] | tuple[str, ...] | None = None,+ target_entries: Any = None,user_context: Any = None,) -> ShowAccessApplyResult:+ """Replace the whole ShowAccess aggregate under a revision check.++ The audience is a complete entry set, not a delta: whatever is not in+ ``target_entries`` is revoked. ``target_emails`` is the email-only+ shorthand for the same replacement, so a caller that passes it revokes+ every group and organization entry too. Exactly one of the two may be+ given.+ """+page_id = validate_session_id(page_id)context = _resolve_resource_access_context(user_context)current = self.require_access_settings(page_id, user_context=context)@@ -473,6 +666,11 @@ class ShowPageStore:raise ShowPageError("Invalid ShowAccess revision.", code="invalid_revision")if target_access_mode not in ACCESS_MODES:raise ShowPageError("Invalid ShowAccess mode.", code="invalid_access_mode")+ if target_emails is not None and target_entries is not None:+ raise ShowPageError(+ "Pass either a ShowAccess email list or an entry list, not both.",+ code="invalid_show_access",+ )normalized_share_id = (validate_share_id(target_share_id)if target_share_id is not None@@ -480,109 +678,124 @@ class ShowPageStore:)if target_access_mode == ACCESS_MODE_PRIVATE and normalized_share_id is None:normalized_share_id = current.share_id- normalized_emails = normalize_show_access_emails(target_emails)- if target_access_mode == ACCESS_MODE_LIMITED:- if normalized_share_id is None or not normalized_emails:- raise ShowPageError(- "Limited ShowAccess requires a share ID and at least one email.",- code="invalid_show_access",- )- elif normalized_emails:- raise ShowPageError(- "Only Limited ShowAccess may contain emails.",- code="invalid_show_access",- )- if target_access_mode == ACCESS_MODE_PUBLIC and normalized_share_id is None:- raise ShowPageError(- "Public ShowAccess requires a share ID.",- code="invalid_show_access",- )except (ShowPageError, TypeError):return ShowAccessApplyResult(status="invalid", show_access=current)status = "applied"now = _utc_now_iso()try:- with self.engine.begin() as conn:- row = (- conn.execute(- select(show_pages)- .where(show_pages.c.session_id == page_id)- .limit(1)- )- .mappings()- .first()- )- if row is None:- raise ShowPageError(- "This session has no Show Page.",- code="show_page_not_found",- )- self._require_sharing_control(conn, page_id, context)- current = _show_access_from_row(conn, row)- if current.revision != expected_revision:- return ShowAccessApplyResult(- status="conflict",- show_access=current,- )- canonical_target = (- target_access_mode,- normalized_share_id,- normalized_emails,- )- canonical_current = (- current.access_mode,- current.share_id,- current.normalized_emails,- )- if canonical_target == canonical_current:- return ShowAccessApplyResult(- status="no_change",- show_access=current,+ # Organization-scoped entries are stamped with the instance's+ # current organization. Hold the pairing lock that ``ensure`` /+ # ``get_for_use`` already use across that read AND the database+ # write, so a re-pair cannot land between them and persist the+ # former organization's ID.+ with config_file_lock():+ try:+ normalized_entries = self._normalize_target_entries(+ target_emails=target_emails,+ target_entries=target_entries,)- archived = conn.execute(- select(agent_sessions.c.status)- .where(agent_sessions.c.id == page_id)- .limit(1)- ).scalar_one_or_none()- if archived == "archived":- return ShowAccessApplyResult(- status="invalid",- show_access=current,+ if target_access_mode == ACCESS_MODE_LIMITED:+ if normalized_share_id is None or not normalized_entries:+ raise ShowPageError(+ "Limited ShowAccess requires a share ID and at least one "+ "access entry.",+ code="invalid_show_access",+ )+ elif normalized_entries:+ raise ShowPageError(+ "Only Limited ShowAccess may contain access entries.",+ code="invalid_show_access",+ )+ if target_access_mode == ACCESS_MODE_PUBLIC and normalized_share_id is None:+ raise ShowPageError(+ "Public ShowAccess requires a share ID.",+ code="invalid_show_access",+ )+ except (ShowPageError, TypeError):+ return ShowAccessApplyResult(status="invalid", show_access=current)+ with self.engine.begin() as conn:+ row = (+ conn.execute(+ select(show_pages)+ .where(show_pages.c.session_id == page_id)+ .limit(1)+ )+ .mappings()+ .first())- result = conn.execute(- update(show_pages)- .where(- show_pages.c.session_id == page_id,- show_pages.c.access_revision == expected_revision,+ if row is None:+ raise ShowPageError(+ "This session has no Show Page.",+ code="show_page_not_found",+ )+ self._require_sharing_control(conn, page_id, context)+ current = _show_access_from_row(conn, row)+ if current.revision != expected_revision:+ return ShowAccessApplyResult(+ status="conflict",+ show_access=current,+ )+ canonical_target = (+ target_access_mode,+ normalized_share_id,+ normalized_entries,)- .values(- access_mode=target_access_mode,- share_id=normalized_share_id,- access_revision=expected_revision + 1,- updated_at=now,+ canonical_current = (+ current.access_mode,+ current.share_id,+ current.entries,)- )- if not result.rowcount:- status = "conflict"- else:- conn.execute(- delete(show_page_authorized_emails).where(- show_page_authorized_emails.c.session_id == page_id+ if canonical_target == canonical_current:+ return ShowAccessApplyResult(+ status="no_change",+ show_access=current,+ )+ archived = conn.execute(+ select(agent_sessions.c.status)+ .where(agent_sessions.c.id == page_id)+ .limit(1)+ ).scalar_one_or_none()+ if archived == "archived":+ return ShowAccessApplyResult(+ status="invalid",+ show_access=current,+ )+ result = conn.execute(+ update(show_pages)+ .where(+ show_pages.c.session_id == page_id,+ show_pages.c.access_revision == expected_revision,+ )+ .values(+ access_mode=target_access_mode,+ share_id=normalized_share_id,+ access_revision=expected_revision + 1,+ updated_at=now,))- if normalized_emails:+ if not result.rowcount:+ status = "conflict"+ else:conn.execute(- insert(show_page_authorized_emails),- [- {- "session_id": page_id,- "normalized_email": email,- "created_at": now,- }- for email in normalized_emails- ],+ delete(show_page_access_entries).where(+ show_page_access_entries.c.page_id == page_id+ ))+ if normalized_entries:+ conn.execute(+ insert(show_page_access_entries),+ [+ {+ "page_id": page_id,+ "kind": entry.kind,+ "value": entry.value,+ "organization_id": entry.organization_id,+ "created_at": now,+ }+ for entry in normalized_entries+ ],+ )except IntegrityError:status = "share_id_taken"@@ -594,6 +807,55 @@ class ShowPageStore:)return ShowAccessApplyResult(status=status, show_access=latest)+ def _normalize_target_entries(+ self,+ *,+ target_emails: list[str] | tuple[str, ...] | None,+ target_entries: Any,+ ) -> tuple[ShowAccessEntry, ...]:+ if target_entries is None:+ return tuple(+ ShowAccessEntry(kind=ACCESS_ENTRY_KIND_EMAIL, value=email)+ for email in normalize_show_access_emails(target_emails or ())+ )+ if isinstance(target_entries, (str, bytes, Mapping)) or not isinstance(+ target_entries, Iterable+ ):+ raise ShowPageError(+ "Invalid Show Page access entry list.", code="invalid_access_entry"+ )+ materialized = list(target_entries)+ # Resolving the instance organization reads configuration, so only an+ # audience that actually contains an organization-scoped entry pays for+ # the answer; an email-only audience never needs one.+ needs_organization = any(+ _entry_fields(raw)[0] in ORGANIZATION_ACCESS_ENTRY_KINDS+ for raw in materialized+ )+ return normalize_show_access_entries(+ materialized,+ page_organization_id=(+ self._page_organization_id() if needs_organization else None+ ),+ )++ @classmethod+ def _page_organization_id(cls) -> str | None:+ """The organization that owns this instance, or None when Personal.++ Group and organization entries are stored against this value, never+ against one a caller supplies, so a Personal instance simply has no+ organization to grant and rejects both kinds.+ """++ ownership = cls._resolve_instance_ownership()+ if not isinstance(ownership, Mapping) or ownership.get("mode") != "organization":+ return None+ organization_id = ownership.get("organization_id")+ if not isinstance(organization_id, str) or not organization_id.strip():+ return None+ return organization_id.strip()+def get_by_share_id(self, share_id: str) -> ShowPage | None:share_id = (share_id or "").strip()if not share_id:@@ -1168,7 +1430,9 @@ class ShowPageStore:expected_revision=access.revision,target_access_mode=access.access_mode,target_share_id=_new_share_id(),- target_emails=access.normalized_emails,+ # Rotating the link is not an audience edit: carry the whole+ # entry set over, not just its email slice.+ target_entries=access.entries,user_context=context,)if result.status == "share_id_taken":@@ -1221,7 +1485,9 @@ class ShowPageStore:expected_revision=access.revision,target_access_mode=access.access_mode,target_share_id=new_share_id,- target_emails=access.normalized_emails,+ # Renaming the link is not an audience edit: carry the whole entry+ # set over, not just its email slice.+ target_entries=access.entries,user_context=context,)if result.status == "share_id_taken":@@ -1265,20 +1531,35 @@ def _page_from_row(row: Any) -> ShowPage:def _show_access_from_row(connection: Connection, row: Any) -> ShowAccess:page_id = str(row["session_id"])- emails = tuple(- str(value)- for value in connection.execute(- select(show_page_authorized_emails.c.normalized_email)- .where(show_page_authorized_emails.c.session_id == page_id)- .order_by(show_page_authorized_emails.c.normalized_email.asc())- ).scalars()+ entries = tuple(+ ShowAccessEntry(+ kind=str(entry_row["kind"]),+ value=str(entry_row["value"]),+ organization_id=(+ str(entry_row["organization_id"])+ if entry_row["organization_id"]+ else None+ ),+ )+ for entry_row in connection.execute(+ select(+ show_page_access_entries.c.kind,+ show_page_access_entries.c.value,+ show_page_access_entries.c.organization_id,+ )+ .where(show_page_access_entries.c.page_id == page_id)+ .order_by(+ show_page_access_entries.c.kind.asc(),+ show_page_access_entries.c.value.asc(),+ )+ ).mappings())return ShowAccess(page_id=page_id,access_mode=str(row["access_mode"]),share_id=str(row["share_id"]) if row["share_id"] else None,revision=int(row["access_revision"]),- normalized_emails=emails,+ entries=entries,)diff --git a/storage/alembic/versions/20260820_0058_show_page_access_entries.py b/storage/alembic/versions/20260820_0058_show_page_access_entries.pynew file mode 100644index 000000000..2c870a475--- /dev/null+++ b/storage/alembic/versions/20260820_0058_show_page_access_entries.py@@ -0,0 +1,142 @@+"""widen the Show Page Limited audience from emails to heterogeneous entries++Revision ID: 20260820_0058+Revises: 20260819_0057+Create Date: 2026-08-20+"""++from __future__ import annotations++from alembic import op+import sqlalchemy as sa++revision = "20260820_0058"+down_revision = "20260819_0057"+branch_labels = None+depends_on = None++_ENTRIES_TABLE = "show_page_access_entries"+_LEGACY_EMAIL_TABLE = "show_page_authorized_emails"+_ORGANIZATION_INDEX = "uq_show_page_access_entries_organization"+_LOOKUP_INDEX = "ix_show_page_access_entries_lookup"+_LEGACY_EMAIL_INDEX = "ix_show_page_authorized_emails_email"+++def _tables() -> set[str]:+ return {+ str(row[0])+ for row in op.get_bind()+ .exec_driver_sql("select name from sqlite_master where type = 'table'")+ .fetchall()+ }+++def _create_entries_table() -> None:+ if _ENTRIES_TABLE not in _tables():+ op.create_table(+ _ENTRIES_TABLE,+ sa.Column(+ "page_id",+ sa.String(),+ sa.ForeignKey("show_pages.session_id", ondelete="CASCADE"),+ primary_key=True,+ ),+ sa.Column("kind", sa.String(), primary_key=True),+ sa.Column("value", sa.String(), primary_key=True),+ sa.Column("organization_id", sa.String(), nullable=True),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.CheckConstraint(+ "kind in ('email', 'group', 'organization')",+ name="ck_show_page_access_entries_kind",+ ),+ sa.CheckConstraint(+ "length(value) between 1 and 320",+ name="ck_show_page_access_entries_value_length",+ ),+ sa.CheckConstraint(+ "(kind = 'email' and organization_id is null) "+ "or (kind in ('group', 'organization') and organization_id is not null)",+ name="ck_show_page_access_entries_organization",+ ),+ sa.CheckConstraint(+ "kind <> 'organization' or value = organization_id",+ name="ck_show_page_access_entries_organization_value",+ ),+ )+ op.create_index(+ _LOOKUP_INDEX,+ _ENTRIES_TABLE,+ ["kind", "value"],+ if_not_exists=True,+ )+ op.create_index(+ _ORGANIZATION_INDEX,+ _ENTRIES_TABLE,+ ["page_id"],+ unique=True,+ sqlite_where=sa.text("kind = 'organization'"),+ if_not_exists=True,+ )+++def _create_legacy_email_table() -> None:+ if _LEGACY_EMAIL_TABLE not in _tables():+ op.create_table(+ _LEGACY_EMAIL_TABLE,+ sa.Column(+ "session_id",+ sa.String(),+ sa.ForeignKey("show_pages.session_id", ondelete="CASCADE"),+ primary_key=True,+ ),+ sa.Column("normalized_email", sa.String(), primary_key=True),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.CheckConstraint(+ "length(normalized_email) between 3 and 320",+ name="ck_show_page_authorized_emails_length",+ ),+ )+ op.create_index(+ _LEGACY_EMAIL_INDEX,+ _LEGACY_EMAIL_TABLE,+ ["normalized_email"],+ if_not_exists=True,+ )+++def upgrade() -> None:+ _create_entries_table()++ # The email audience moves rather than forks: copy first, then retire the+ # source. ``insert or ignore`` keeps a replay -- unversioned databases are+ # stamped at the replay floor and run every later revision again -- from+ # duplicating or overwriting an entry that is already there.+ if _LEGACY_EMAIL_TABLE in _tables():+ op.execute(+ sa.text(+ f"insert or ignore into {_ENTRIES_TABLE} "+ "(page_id, kind, value, organization_id, created_at) "+ "select session_id, 'email', normalized_email, null, created_at "+ f"from {_LEGACY_EMAIL_TABLE}"+ )+ )+ op.drop_table(_LEGACY_EMAIL_TABLE)+++def downgrade() -> None:+ _create_legacy_email_table()++ if _ENTRIES_TABLE in _tables():+ # Pre-0058 readers only understand emails. Group and organization+ # entries have no legacy representation, so they are dropped with the+ # table: the audience narrows and fails closed instead of being+ # silently widened into an email that was never granted.+ op.execute(+ sa.text(+ f"insert or ignore into {_LEGACY_EMAIL_TABLE} "+ "(session_id, normalized_email, created_at) "+ "select page_id, value, created_at "+ f"from {_ENTRIES_TABLE} where kind = 'email'"+ )+ )+ op.drop_table(_ENTRIES_TABLE)diff --git a/storage/migrations.py b/storage/migrations.pyindex 8c42aa8b9..d728ed037 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -55,7 +55,7 @@ HEAD_TABLES = INITIAL_TABLES | {"run_definitions","agent_runs","show_pages",- "show_page_authorized_emails",+ "show_page_access_entries","messages","message_deliveries","session_turns",@@ -151,7 +151,13 @@ HEAD_REQUIRED_COLUMNS = PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS | {}HEAD_ONLY_REQUIRED_COLUMNS = {"show_pages": {"access_mode", "access_revision", "share_id", "offline_at"},- "show_page_authorized_emails": {"session_id", "normalized_email", "created_at"},+ "show_page_access_entries": {+ "page_id",+ "kind",+ "value",+ "organization_id",+ "created_at",+ },"web_push_subscriptions": {"device_id"},"remote_access_authorizations": {"instance_id",diff --git a/storage/models.py b/storage/models.pyindex c91f74bd5..33c2264f8 100644--- a/storage/models.py+++ b/storage/models.py@@ -405,22 +405,54 @@ show_pages = Table(Index("ix_show_pages_access_mode", "access_mode"),)-show_page_authorized_emails = Table(- "show_page_authorized_emails",+# The Limited audience of a Show Page: one heterogeneous set of read-only+# grants, OR-ed at admission. ``email`` is instance-independent; ``group`` and+# ``organization`` only mean something relative to the organization that owns+# the page, so they carry that organization and cannot exist on a Personal+# instance. This table replaces the email-only ``show_page_authorized_emails``.+show_page_access_entries = Table(+ "show_page_access_entries",metadata,Column(- "session_id",+ "page_id",String,ForeignKey("show_pages.session_id", ondelete="CASCADE"),primary_key=True,),- Column("normalized_email", String, primary_key=True),+ Column("kind", String, primary_key=True),+ Column("value", String, primary_key=True),+ Column("organization_id", String, nullable=True),Column("created_at", String, nullable=False),CheckConstraint(- "length(normalized_email) between 3 and 320",- name="ck_show_page_authorized_emails_length",+ "kind in ('email', 'group', 'organization')",+ name="ck_show_page_access_entries_kind",+ ),+ CheckConstraint(+ "length(value) between 1 and 320",+ name="ck_show_page_access_entries_value_length",+ ),+ CheckConstraint(+ "(kind = 'email' and organization_id is null) "+ "or (kind in ('group', 'organization') and organization_id is not null)",+ name="ck_show_page_access_entries_organization",+ ),+ # An organization entry IS the organization, so its value cannot name a+ # different one than the entry is scoped to.+ CheckConstraint(+ "kind <> 'organization' or value = organization_id",+ name="ck_show_page_access_entries_organization_value",+ ),+ # Admission resolves a visitor assertion to entries by (kind, value).+ Index("ix_show_page_access_entries_lookup", "kind", "value"),+ # "This organization may read" is one switch, not a list: at most one such+ # entry per page. The composite primary key cannot say that on its own,+ # because two organization rows would differ in ``value``.+ Index(+ "uq_show_page_access_entries_organization",+ "page_id",+ unique=True,+ sqlite_where=text("kind = 'organization'"),),- Index("ix_show_page_authorized_emails_email", "normalized_email"),)show_session_events = Table(diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex 18d4549fc..9d46ebabf 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -8,6 +8,8 @@ from config import pathsfrom config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Configfrom core.show_pages import (SHOW_ACCESS_EMAIL_MAX_COUNT,+ SHOW_ACCESS_ENTRY_MAX_COUNTS,+ ShowAccessEntry,ShowPage,ShowPageError,ShowPageStore,@@ -795,6 +797,326 @@ def test_show_access_and_availability_are_independent(monkeypatch, tmp_path) ->store.close()+def _instance_ownership(monkeypatch, organization_id: str | None) -> None:+ """Pin the store's own answer to "which organization owns this instance".++ Group and organization access entries are stored against that answer and+ never against a caller-supplied one, so pinning it here is what makes an+ organization-scoped audience reachable (or, with ``None``, Personal).+ """++ ownership = (+ {"mode": "personal"}+ if organization_id is None+ else {"mode": "organization", "organization_id": organization_id}+ )+ monkeypatch.setattr(+ ShowPageStore,+ "_resolve_instance_ownership",+ staticmethod(lambda: dict(ownership)),+ )+++ "entry",+ [+ ShowAccessEntry(kind="group", value="group-7", organization_id="org-1"),+ ShowAccessEntry(kind="group", value="group-7"),+ ShowAccessEntry(kind="organization", value="org-1", organization_id="org-1"),+ {"kind": "organization"},+ ],+)+def test_show_access_personal_instance_grants_emails_only(monkeypatch, tmp_path, entry) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ page = store.ensure("ses-personal-entries")+ _instance_ownership(monkeypatch, None)+ result = store.apply_access(+ "ses-personal-entries",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[{"kind": "email", "value": "[email protected]"}, entry],+ )++ assert result.status == "invalid"+ assert result.show_access.revision == 0+ assert result.show_access.access_mode == "private"+ # A rejected audience is rejected whole: the email alongside it is not+ # written either.+ assert result.show_access.entries == ()+ assert store.get_access("ses-personal-entries").entries == ()+ finally:+ store.close()+++def test_show_access_entries_are_scoped_to_the_instance_organization(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ page = store.ensure("ses-org-entries")+ _instance_ownership(monkeypatch, "org-1")+ applied = store.apply_access(+ "ses-org-entries",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[+ {"kind": "email", "value": " [email protected] "},+ {"kind": "group", "value": " group-7 "},+ {"kind": "group", "value": "group-7", "organization_id": "org-1"},+ # "This organization may read" is one switch, not a list: every+ # organization entry names the instance's organization by+ # construction, so two of them collapse into one.+ {"kind": "organization"},+ {"kind": "organization", "value": "org-1", "organization_id": "org-1"},+ ],+ )++ assert applied.status == "applied"+ assert applied.show_access.revision == 1+ assert applied.show_access.entries == (+ ShowAccessEntry("email", "[email protected]", None),+ ShowAccessEntry("group", "group-7", "org-1"),+ ShowAccessEntry("organization", "org-1", "org-1"),+ )+ assert applied.show_access.normalized_emails == ("[email protected]",)+ assert store.get_access("ses-org-entries") == applied.show_access++ cross_organization = store.apply_access(+ "ses-org-entries",+ expected_revision=1,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[{"kind": "group", "value": "group-9", "organization_id": "org-2"}],+ )+ assert cross_organization.status == "invalid"+ assert store.get_access("ses-org-entries") == applied.show_access++ # The audience is a complete set, not a delta.+ replaced = store.apply_access(+ "ses-org-entries",+ expected_revision=1,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[{"kind": "group", "value": "group-8"}],+ )+ assert replaced.status == "applied"+ assert replaced.show_access.entries == (ShowAccessEntry("group", "group-8", "org-1"),)+ assert replaced.show_access.normalized_emails == ()++ # ``target_emails`` is the email-only shorthand for that same+ # replacement, so it revokes the group entry with it.+ shorthand = store.apply_access(+ "ses-org-entries",+ expected_revision=2,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_emails=["[email protected]"],+ )+ assert shorthand.status == "applied"+ assert shorthand.show_access.entries == (+ ShowAccessEntry("email", "[email protected]", None),+ )+ finally:+ store.close()+++def test_show_access_group_audience_over_limit_has_no_write(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ page = store.ensure("ses-group-limit")+ _instance_ownership(monkeypatch, "org-1")+ limit = SHOW_ACCESS_ENTRY_MAX_COUNTS["group"]+ allowed_groups = [{"kind": "group", "value": f"group-{index}"} for index in range(limit)]+ allowed = store.apply_access(+ "ses-group-limit",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=allowed_groups,+ )+ result = store.apply_access(+ "ses-group-limit",+ expected_revision=allowed.show_access.revision,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[*allowed_groups, {"kind": "group", "value": "one-too-many"}],+ )++ assert allowed.status == "applied"+ assert len(allowed.show_access.entries) == limit+ assert result.status == "invalid"+ assert result.show_access == allowed.show_access+ finally:+ store.close()+++def test_show_access_never_partially_replaces_the_entry_set(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ first = store.ensure("ses-entries-first")+ second = store.ensure("ses-entries-second")+ _instance_ownership(monkeypatch, "org-1")+ taken = store.apply_access(+ "ses-entries-first",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id="taken-link",+ target_entries=[{"kind": "email", "value": "[email protected]"}],+ )+ heterogeneous = store.apply_access(+ "ses-entries-second",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=second.share_id,+ target_entries=[+ {"kind": "email", "value": "[email protected]"},+ {"kind": "group", "value": "group-7"},+ {"kind": "organization"},+ ],+ )+ assert taken.status == heterogeneous.status == "applied"++ conflict = store.apply_access(+ "ses-entries-second",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=second.share_id,+ target_entries=[{"kind": "email", "value": "[email protected]"}],+ )+ collision = store.apply_access(+ "ses-entries-second",+ expected_revision=1,+ target_access_mode="limited",+ target_share_id="taken-link",+ target_entries=[{"kind": "email", "value": "[email protected]"}],+ )++ assert conflict.status == "conflict"+ assert collision.status == "share_id_taken"+ assert conflict.show_access == heterogeneous.show_access+ assert collision.show_access == heterogeneous.show_access+ assert store.get_access("ses-entries-second") == heterogeneous.show_access+ assert store.get_by_share_id("taken-link").session_id == first.session_id+ finally:+ store.close()+++def test_share_link_edits_carry_the_whole_entry_set(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ page = store.ensure("ses-entries-rotate")+ _instance_ownership(monkeypatch, "org-1")+ limited = store.apply_access(+ "ses-entries-rotate",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[+ {"kind": "email", "value": "[email protected]"},+ {"kind": "group", "value": "group-7"},+ {"kind": "organization"},+ ],+ )+ rotated, previous = store.rotate_share("ses-entries-rotate")+ after_rotate = store.get_access("ses-entries-rotate")+ renamed, _ = store.set_share_id("ses-entries-rotate", "renamed-link")+ after_rename = store.get_access("ses-entries-rotate")++ assert previous == page.share_id+ assert rotated.share_id not in {None, page.share_id}+ assert renamed.share_id == "renamed-link"+ assert after_rotate.entries == limited.show_access.entries+ assert after_rename.entries == limited.show_access.entries++ # Known-by-design: the entry set is re-validated against the instance's+ # CURRENT organization, so an instance that has left it can no longer+ # rotate the link — the audience fails closed instead of being silently+ # re-scoped. Owner/organization transfer is out of scope for this lane.+ _instance_ownership(monkeypatch, None)+ _expect_show_page_error(lambda: store.rotate_share("ses-entries-rotate"), "invalid")+ assert store.get_access("ses-entries-rotate").entries == limited.show_access.entries+ finally:+ store.close()+++def test_show_access_stamps_organization_entries_from_the_pairing_held_at_persist(+ monkeypatch, tmp_path+) -> None:+ """Organization-scoped entries are stamped with the pairing live at persist.++ Resolving ownership before the pairing lock used to let a re-pair land+ between that read and the write, so the former organization's ID could be+ stored after the new pairing was already active. Resolution and persist now+ share one lock hold: an unlocked snapshot is never the one written.+ """++ from contextlib import contextmanager++ import core.show_pages as show_pages_mod+ from config.v2_config import config_file_lock as real_config_file_lock++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ page = store.ensure("ses-pairing-lock")+ held = {"depth": 0}+ resolved_under_lock: list[bool] = []++ @contextmanager+ def tracking_lock(*args, **kwargs):+ held["depth"] += 1+ try:+ with real_config_file_lock(*args, **kwargs):+ yield+ finally:+ held["depth"] -= 1++ def resolve_ownership():+ under_lock = held["depth"] > 0+ resolved_under_lock.append(under_lock)+ organization_id = "org-live" if under_lock else "org-stale"+ return {"mode": "organization", "organization_id": organization_id}++ monkeypatch.setattr(show_pages_mod, "config_file_lock", tracking_lock)+ monkeypatch.setattr(+ ShowPageStore,+ "_resolve_instance_ownership",+ staticmethod(resolve_ownership),+ )+ applied = store.apply_access(+ "ses-pairing-lock",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id=page.share_id,+ target_entries=[+ {"kind": "email", "value": "[email protected]"},+ {"kind": "group", "value": "group-7"},+ {"kind": "organization"},+ ],+ )+ persisted = store.get_access("ses-pairing-lock")++ assert applied.status == "applied"+ assert persisted.entries == (+ ShowAccessEntry("email", "[email protected]", None),+ ShowAccessEntry("group", "group-7", "org-live"),+ ShowAccessEntry("organization", "org-live", "org-live"),+ )+ assert resolved_under_lock+ assert all(resolved_under_lock)+ assert "org-stale" not in {+ entry.organization_id for entry in persisted.entries+ }+ finally:+ store.close()++def test_set_share_id_rejects_archived_session(monkeypatch, tmp_path):from storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_statediff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 2bd2f35db..c183e9e4e 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -35,7 +35,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260819_0057"+HEAD_REVISION = "20260820_0058"# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and# Alembic cannot re-emit them when batch mode recreates a table. Every migration that# rebuilds one therefore passes this convention; the rebuild simulated below has to pass@@ -112,14 +112,24 @@ def test_local_show_access_migration_round_trip_preserves_pages_and_fails_closedassert all(row[2] for row in rows.values())show_indexes = {row[1] for row in conn.execute("pragma index_list(show_pages)")}- email_indexes = {+ # 20260820_0058 moved the audience out of ``show_page_authorized_emails``+ # into the heterogeneous entry table, so that is where the audience half+ # of this round trip lives at head.+ entry_indexes = {row[1]- for row in conn.execute("pragma index_list(show_page_authorized_emails)")+ for row in conn.execute("pragma index_list(show_page_access_entries)")}assert {"ix_show_pages_share_id", "ix_show_pages_access_mode"}.issubset(show_indexes)- assert "ix_show_page_authorized_emails_email" in email_indexes+ assert {+ "ix_show_page_access_entries_lookup",+ "uq_show_page_access_entries_organization",+ }.issubset(entry_indexes)+ assert "show_page_authorized_emails" not in {+ row[0]+ for row in conn.execute("select name from sqlite_master where type = 'table'")+ }foreign_key = conn.execute(- "pragma foreign_key_list(show_page_authorized_emails)"+ "pragma foreign_key_list(show_page_access_entries)").fetchone()assert foreign_key is not Noneassert foreign_key[2] == "show_pages"@@ -139,17 +149,16 @@ def test_local_show_access_migration_round_trip_preserves_pages_and_fails_closed"where session_id = 'private-stable'")conn.execute(- "insert into show_page_authorized_emails values (?, ?, ?)",- ("private-stable", "[email protected]", "2026-08-17T00:00:00Z"),+ "insert into show_page_access_entries values (?, ?, ?, ?, ?)",+ ("private-stable", "email", "[email protected]", None, "2026-08-17T00:00:00Z"),)conn.execute(- "insert into show_page_authorized_emails values (?, ?, ?)",- ("private-null", "[email protected]", "2026-08-17T00:00:00Z"),+ "insert into show_page_access_entries values (?, ?, ?, ?, ?)",+ ("private-null", "email", "[email protected]", None, "2026-08-17T00:00:00Z"),)conn.execute("delete from show_pages where session_id = 'private-null'")assert conn.execute(- "select count(*) from show_page_authorized_emails "- "where session_id = 'private-null'"+ "select count(*) from show_page_access_entries where page_id = 'private-null'").fetchone() == (0,)command.downgrade(migrations.alembic_config(db_path), "20260815_0054")@@ -187,11 +196,216 @@ def test_local_show_access_migration_round_trip_preserves_pages_and_fails_closed"select access_mode, access_revision, share_id from show_pages ""where session_id = 'private-stable'").fetchone()- email_count = conn.execute(- "select count(*) from show_page_authorized_emails"+ entry_count = conn.execute(+ "select count(*) from show_page_access_entries").fetchone()assert reupgraded == ("private", 0, "private-link")- assert email_count == (0,)+ assert entry_count == (0,)+++SHOW_PAGE_ACCESS_ENTRY_MIGRATION_MODULE = (+ "storage.alembic.versions.20260820_0058_show_page_access_entries"+)+++def _seed_show_pages(conn: sqlite3.Connection, session_ids: Iterable[str]) -> None:+ conn.executemany(+ """+ insert into show_pages (+ session_id, share_id, offline_at, access_mode, access_revision,+ created_at, updated_at+ ) values (?, ?, null, 'limited', 1, '2026-08-19T00:00:00Z', '2026-08-19T00:00:00Z')+ """,+ [(session_id, f"{session_id}-link") for session_id in session_ids],+ )+++def _restore_legacy_show_page_email_table(db_path: Path) -> None:+ """Put the retired pre-0058 email table back the way a replay finds it.++ An unversioned database is stamped at the replay floor, so 20260820_0058+ runs again over state it already produced. Reusing the revision's own+ downgrade helper keeps this fixture from becoming a second, drifting copy of+ that table's shape.+ """++ migration = import_module(SHOW_PAGE_ACCESS_ENTRY_MIGRATION_MODULE)+ engine = create_sqlite_engine(db_path)+ try:+ with engine.begin() as conn:+ with Operations.context(MigrationContext.configure(conn)):+ migration._create_legacy_email_table()+ finally:+ engine.dispose()+++def test_show_page_access_entry_migration_moves_every_email_row_and_narrows_on_downgrade(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260819_0057")+ # One row of every audience shape 20260819_0057 can hold: a page with+ # several addresses, a page with one, and a page with none.+ seeded_emails = [+ ("many-emails", "[email protected]", "2026-08-17T00:00:00Z"),+ ("many-emails", "[email protected]", "2026-08-18T00:00:00Z"),+ ("one-email", "[email protected]", "2026-08-18T12:00:00Z"),+ ]+ with sqlite3.connect(db_path) as conn:+ _seed_show_pages(conn, ("many-emails", "one-email", "no-emails"))+ conn.executemany(+ "insert into show_page_authorized_emails values (?, ?, ?)", seeded_emails+ )++ run_migrations(db_path)+ with sqlite3.connect(db_path) as conn:+ migrated = conn.execute(+ "select page_id, kind, value, organization_id, created_at "+ "from show_page_access_entries order by page_id, kind, value"+ ).fetchall()+ # The organization-scoped kinds have no pre-0058 representation, so they+ # only exist from here on.+ conn.executemany(+ "insert into show_page_access_entries values (?, ?, ?, ?, ?)",+ [+ ("many-emails", "group", "group-7", "org-1", "2026-08-20T00:00:00Z"),+ ("many-emails", "organization", "org-1", "org-1", "2026-08-20T00:00:00Z"),+ ],+ )+ assert migrated == [+ (page_id, "email", value, None, created_at)+ for page_id, value, created_at in sorted(seeded_emails)+ ]++ command.downgrade(migrations.alembic_config(db_path), "20260819_0057")+ with sqlite3.connect(db_path) as conn:+ restored = conn.execute(+ "select session_id, normalized_email, created_at "+ "from show_page_authorized_emails order by session_id, normalized_email"+ ).fetchall()+ legacy_indexes = {+ row[1]+ for row in conn.execute("pragma index_list(show_page_authorized_emails)")+ }+ tables = {+ row[0]+ for row in conn.execute("select name from sqlite_master where type = 'table'")+ }+ # A pre-0058 reader only understands emails, so the audience narrows and+ # fails closed: the group and organization grants are dropped, never widened+ # into an email that was never granted.+ assert restored == sorted(seeded_emails)+ assert "ix_show_page_authorized_emails_email" in legacy_indexes+ assert "show_page_access_entries" not in tables++ run_migrations(db_path)+ with sqlite3.connect(db_path) as conn:+ reupgraded = conn.execute(+ "select page_id, kind, value, organization_id, created_at "+ "from show_page_access_entries order by page_id, kind, value"+ ).fetchall()+ tables = {+ row[0]+ for row in conn.execute("select name from sqlite_master where type = 'table'")+ }+ assert reupgraded == [+ (page_id, "email", value, None, created_at)+ for page_id, value, created_at in sorted(seeded_emails)+ ]+ assert "show_page_authorized_emails" not in tables+++def test_show_page_access_entry_migration_replay_neither_duplicates_nor_overwrites(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path)+ already_migrated = [+ ("replayed", "email", "[email protected]", None, "2026-08-20T00:00:00Z"),+ ("replayed", "group", "group-7", "org-1", "2026-08-20T00:00:00Z"),+ ]+ with sqlite3.connect(db_path) as conn:+ _seed_show_pages(conn, ("replayed",))+ conn.executemany(+ "insert into show_page_access_entries values (?, ?, ?, ?, ?)", already_migrated+ )++ _restore_legacy_show_page_email_table(db_path)+ with sqlite3.connect(db_path) as conn:+ conn.executemany(+ "insert into show_page_authorized_emails values (?, ?, ?)",+ [+ # One address this revision has already moved, carrying a+ # different timestamp, and one it has never seen.+ ("replayed", "[email protected]", "2000-01-01T00:00:00Z"),+ ("replayed", "[email protected]", "2026-08-21T00:00:00Z"),+ ],+ )+ command.stamp(migrations.alembic_config(db_path), "20260819_0057")++ run_migrations(db_path)+ with sqlite3.connect(db_path) as conn:+ entries = conn.execute(+ "select page_id, kind, value, organization_id, created_at "+ "from show_page_access_entries order by kind, value"+ ).fetchall()+ tables = {+ row[0]+ for row in conn.execute("select name from sqlite_master where type = 'table'")+ }+ assert entries == [+ ("replayed", "email", "[email protected]", None, "2026-08-21T00:00:00Z"),+ *sorted(already_migrated, key=lambda row: (row[1], row[2])),+ ]+ assert "show_page_authorized_emails" not in tables+++def test_show_page_access_entry_constraints_hold_for_every_kind(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path)+ insert = "insert into show_page_access_entries values (?, ?, ?, ?, '2026-08-20T00:00:00Z')"+ accepted = [+ ("page", "email", "[email protected]", None),+ ("page", "group", "group-7", "org-1"),+ ("page", "group", "group-8", "org-1"),+ ("page", "organization", "org-1", "org-1"),+ # Another page's audience is independent, including its organization.+ ("other", "group", "group-7", "org-1"),+ ("other", "organization", "org-1", "org-1"),+ ]+ with sqlite3.connect(db_path) as conn:+ conn.execute("pragma foreign_keys = on")+ _seed_show_pages(conn, ("page", "other"))+ conn.executemany(insert, accepted)++ for row in accepted:+ # Every accepted shape is unique per (page, kind, value)...+ with pytest.raises(sqlite3.IntegrityError):+ conn.execute(insert, row)+ # ...and "this organization may read" is one switch per page, not a+ # list, which the composite key alone cannot say.+ with pytest.raises(sqlite3.IntegrityError):+ conn.execute(insert, ("page", "organization", "org-2", "org-2"))++ rejected = [+ ("page", "user", "someone", None),+ ("page", "email", "[email protected]", "org-1"),+ ("page", "group", "group-9", None),+ ("page", "organization", "org-9", "org-1"),+ ("page", "email", "", None),+ ("page", "email", "a" * 321, None),+ ("missing-page", "email", "[email protected]", None),+ ]+ for row in rejected:+ with pytest.raises(sqlite3.IntegrityError):+ conn.execute(insert, row)++ conn.execute("delete from show_pages where session_id = 'other'")+ surviving = conn.execute(+ "select page_id, kind, value, organization_id "+ "from show_page_access_entries order by page_id, kind, value"+ ).fetchall()+ assert surviving == sorted(row for row in accepted if row[0] == "page")def _index_sql(conn: sqlite3.Connection, name: str) -> str:@@ -1138,15 +1352,17 @@ def test_delivery_history_default_repair_preserves_rows_and_reverses(tmp_path: Pseeded["constraints"]["message_deliveries"])- run_migrations(db_path)+ run_migrations(db_path, revision="20260819_0057")with sqlite3.connect(db_path) as conn:upgraded = _schema_fingerprint(conn)assert _delivery_rows(conn) == rows_beforeassert conn.execute("select version_num from alembic_version").fetchone() == (- HEAD_REVISION,+ "20260819_0057",)# Only that one column's default may differ -- every other column, constraint,- # index, and table in the database is untouched.+ # index, and table in the database is untouched. Later revisions (0058+) are+ # a different change and have their own round-trip tests; pinning here keeps+ # 0057's invariant from absorbing them.assert _fingerprint_difference(seeded, upgraded) == {("message_deliveries", "delivery_history_json")}@@ -4687,7 +4903,7 @@ def test_run_migrations_backfills_existing_session_policy_only_for_targeted_defi# migration. Current metadata has already replaced the 0004-era# ``show_pages.visibility`` shape, so remove the future tables instead of# presenting 0004 with an impossible hybrid schema.- conn.execute("drop table show_page_authorized_emails")+ conn.execute("drop table show_page_access_entries")conn.execute("drop table show_pages")conn.execute("update run_definitions set session_policy = null")conn.execute(