Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(permissions): restore Editor use parity and keep the initiating caller below HTTP (#2034)

Maxa8df6b5bbcb4
diff --git a/core/caller_context.py b/core/caller_context.py
index fe7de3fae..f8d1a0285 100644
--- a/core/caller_context.py
+++ b/core/caller_context.py
@@ -242,6 +242,19 @@ def _resource_context_from_env(source: Mapping[str, str]) -> Optional[dict[str,
return dict(parsed) if isinstance(parsed, dict) else None
+def env_declares_remote_caller(env: Mapping[str, str] | None = None) -> bool:
+ """True when the invocation env declares a remote caller.
+
+ Read on its own because :func:`caller_context_from_env` answers ``None`` for a
+ missing session id, before it ever looks at this flag. An entry point that has
+ to tell a genuinely local invocation from a declared-remote one whose
+ provenance is incomplete needs the declaration itself.
+ """
+
+ source = env if env is not None else os.environ
+ return _clean(source.get(AVIBE_CALLER_REMOTE_ENV)).lower() in {"1", "true"}
+
+
def caller_resource_user_context(context: Optional[CallerContext]) -> Optional[Mapping[str, Any]]:
"""Return explicit remote ACL context for a CLI write.
@@ -255,6 +268,28 @@ def caller_resource_user_context(context: Optional[CallerContext]) -> Optional[M
return dict(context.resource_user_context or {})
+def environment_without_caller_context(env: Optional[Mapping[str, str]] = None) -> dict[str, str]:
+ """Return ``env`` with this invocation's caller provenance removed.
+
+ Avibe hands a caller's identity to a subprocess it runs ON that caller's
+ behalf — an Agent turn, a backend, a Harness call — and that hop is the whole
+ point of the contract above. A process Avibe itself owns is the opposite
+ case: the restart supervisor, a deferred activation, the service and the UI
+ server outlive the call that scheduled them and act as the installation, not
+ as whoever pressed the button. Inheriting the scheduling caller there would
+ make an independently owned process run under an authority nobody granted it
+ — and its own entry point, which is Owner work, would refuse it.
+
+ Strip at the boundary where the independent process is created, after the
+ scheduling operation has already been admitted on its own merits. ``None``
+ means "the current environment", and is materialized rather than passed on:
+ a spawn that inherits implicitly would inherit the caller too.
+ """
+
+ source = os.environ if env is None else env
+ return {key: value for key, value in source.items() if key not in CALLER_CONTEXT_ENV_NAMES}
+
+
def validated_caller_env_snapshot(source: object) -> dict[str, str]:
"""Return only caller-context fields from a persisted internal snapshot."""
@@ -379,7 +414,7 @@ def caller_context_from_env(env: Mapping[str, str] | None = None) -> Optional[Ca
session_key=_clean(source.get(AVIBE_CALLER_SESSION_KEY_ENV)) or None,
message_id=_clean(source.get(AVIBE_CALLER_MESSAGE_ID_ENV)) or None,
workspace_id=_clean(source.get(AVIBE_CALLER_WORKSPACE_ID_ENV)) or None,
- is_remote=_clean(source.get(AVIBE_CALLER_REMOTE_ENV)).lower() in {"1", "true"},
+ is_remote=env_declares_remote_caller(source),
resource_user_context=_resource_context_from_env(source),
)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 7c8225346..bd5cb165a 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -7659,15 +7659,26 @@ class ScheduledTaskService:
logger.warning("failed to persist Vault waiter outcome for %s; will retry", request_id)
return "pending"
else:
+ callback_metadata: dict[str, Any] = {
+ "vault_request_type": request_type,
+ "vault_request_status": request_status,
+ }
+ # Auto-resume is deferred work the requesting caller
+ # authorized, so it travels under the authority that was
+ # recorded when the request row was created — the same rule
+ # a Run's callback follows. Re-deriving it inside the
+ # daemon would resume a remote caller's session as local.
+ from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY
+
+ requester_context = vault_service.request_authorization_snapshot(row)
+ if requester_context:
+ callback_metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] = requester_context
enqueue_session_callback(
self.request_store,
session_id=plan.session_id,
message=plan.message,
source_actor=f"vault:{request_id}",
- metadata={
- "vault_request_type": request_type,
- "vault_request_status": request_status,
- },
+ metadata=callback_metadata,
)
status = "sent"
except ValueError:
@@ -7707,11 +7718,26 @@ class ScheduledTaskService:
if isinstance(run_metadata, dict)
else ""
)
- callback_metadata = (
- {CALLBACK_TERMINAL_TURN_ID_METADATA_KEY: terminal_turn_id}
- if terminal_turn_id
+ callback_metadata: dict[str, Any] = (
+ {CALLBACK_TERMINAL_TURN_ID_METADATA_KEY: terminal_turn_id} if terminal_turn_id else {}
+ )
+ # A callback turn is deferred work the parent Run's caller authorized, so
+ # it inherits that Run's snapshot verbatim. Re-deriving it here would run
+ # a remote caller's follow-up as local; refreshing it would hand the
+ # child authority the caller may no longer hold. The snapshot carries the
+ # initiating role and ACL attributes, which the child's own admission
+ # check re-applies against the current instance binding, Project and
+ # Agent — durable automation is deliberately not cut off by the recorded
+ # refresh window.
+ from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY
+
+ parent_resource_context = (
+ run_metadata.get(RESOURCE_USER_CONTEXT_METADATA_KEY)
+ if isinstance(run_metadata, Mapping)
else None
)
+ if isinstance(parent_resource_context, Mapping):
+ callback_metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] = dict(parent_resource_context)
if status in {"failed", "canceled"}:
terminal_message = self._fallback_callback_result(run, status=status)
terminal_callback = enqueue_session_callback(
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 976009bd3..05db576e0 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -145,6 +145,28 @@ class SourceMessageAnchor:
return self.running_turn or is_input_turn(self.author, self.message_type)
+def _require_agent_selection(
+ conn: Any,
+ context: Any,
+ *,
+ agent_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
+) -> None:
+ """Hold the Agent the fork will run as to the caller's selection authority."""
+
+ from core.vibe_agents import VibeAgentAccessError, ensure_agent_selection_access
+
+ try:
+ ensure_agent_selection_access(
+ conn, agent_id=agent_id, agent_name=agent_name, user_context=context
+ )
+ except VibeAgentAccessError as exc:
+ raise SessionForkError(
+ "agent access is not permitted",
+ code="session_fork_agent_forbidden",
+ ) from exc
+
+
def reserve_forked_session(
*,
source_session_id: str,
@@ -200,6 +222,21 @@ def reserve_forked_session(
"editor",
):
raise SessionForkError("source_not_found")
+ # A permitted source does not authorize an arbitrary
+ # destination: without this, a fork can place a copy of the
+ # transcript into a Project the caller cannot chat in. Same
+ # rule and same tier as an ordinary re-placement in
+ # ``workbench_sessions_service.update_workbench_session``, and
+ # it runs before any reserved row or native-fork metadata.
+ destination_scope_id = _clean_optional(scope_id) if scope_id is not None else None
+ if destination_scope_id and not context.can_manage_instance:
+ destination_project_id = project_access_service.project_id_from_scope_id(
+ destination_scope_id
+ )
+ if destination_project_id is None or not project_access_service.can_chat_project(
+ conn, context, destination_project_id
+ ):
+ raise SessionForkError("destination_not_permitted")
row = conn.execute(
select(agent_sessions).where(agent_sessions.c.id == str(source_session_id)).limit(1)
).mappings().first()
@@ -241,6 +278,12 @@ def reserve_forked_session(
)
effective_native_turn_started = True
source_message_id = source_anchor.message_id
+ if agent_name:
+ # The fork will RUN AS this Agent, so selecting it needs use
+ # access to that exact resource — being enabled is not the same
+ # as being one this caller may select. Ordered after the source
+ # checks so an unreachable source still answers first.
+ _require_agent_selection(conn, context, agent_name=agent_name)
override_agent = agent_store.require_enabled(agent_name) if agent_name else None
if override_agent is not None and override_agent.backend != source_backend:
raise SessionForkError(
@@ -265,6 +308,16 @@ def reserve_forked_session(
raise SessionForkError(
"source session Agent backend does not match the session backend"
)
+ # Without an override the fork still runs as the source's Agent,
+ # so that inherited identity is selected authority too. Ordered
+ # after the unavailable and backend answers so their existing
+ # meaning is unchanged.
+ _require_agent_selection(
+ conn,
+ context,
+ agent_id=inherited_agent["id"],
+ agent_name=inherited_agent["name"],
+ )
if override_agent is not None:
target_agent_id = override_agent.id
diff --git a/core/services/sessions.py b/core/services/sessions.py
index caea913f4..24f86df6e 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -33,7 +33,7 @@ Conventions (see workbench-dispatch-architecture.md §6):
from __future__ import annotations
from pathlib import Path
-from typing import Optional
+from typing import Any, Optional
from config import paths
from storage.workbench_sessions_service import (
@@ -53,6 +53,8 @@ from storage.workbench_sessions_service import (
list_sessions_page,
require_enabled_agent_backend,
require_enabled_agent_identity,
+ require_session_chat_access,
+ require_session_turn_authority,
set_agent_status,
touch_session,
touch_session_agent_activity,
@@ -76,6 +78,9 @@ __all__ = [
"is_session_archived",
"list_sessions",
"list_sessions_page",
+ "require_session_chat_access",
+ "require_session_placement_authority",
+ "require_session_turn_authority",
"set_agent_status",
"session_archived_message",
"touch_session",
@@ -170,6 +175,7 @@ def reserve_agent_session(
db_path: Optional[Path] = None,
require_enabled_agent: bool = False,
expected_reference_agent_id: Optional[str] = None,
+ authorization_context: Any = None,
) -> Optional[str]:
"""Reserve a new ``agent_sessions`` row keyed by an IM-style scope.
@@ -193,6 +199,34 @@ def reserve_agent_session(
metadata=metadata,
require_enabled_agent=require_enabled_agent,
expected_reference_agent_id=expected_reference_agent_id,
+ authorization_context=authorization_context,
+ )
+ finally:
+ service.close()
+
+
+def require_session_placement_authority(
+ *,
+ scope_key: str,
+ agent_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ db_path: Optional[Path] = None,
+ authorization_context: Any = None,
+) -> None:
+ """Admit where a stored definition will put the Sessions it has not created yet.
+
+ The reservation paths answer this as they reserve. A definition that creates one
+ Session per run has no reservation to answer it at, so it asks here — before the
+ row that would carry the placement into every future fire.
+ """
+
+ service = _open_legacy_service(db_path)
+ try:
+ service.require_placement_access(
+ scope_key=scope_key,
+ agent_id=agent_id,
+ agent_name=agent_name,
+ authorization_context=authorization_context,
)
finally:
service.close()
@@ -212,6 +246,7 @@ def reserve_standalone_agent_session(
db_path: Optional[Path] = None,
require_enabled_agent: bool = False,
expected_reference_agent_id: Optional[str] = None,
+ authorization_context: Any = None,
) -> Optional[str]:
"""Reserve a background-capable session with no Scope."""
@@ -229,6 +264,7 @@ def reserve_standalone_agent_session(
metadata=metadata,
require_enabled_agent=require_enabled_agent,
expected_reference_agent_id=expected_reference_agent_id,
+ authorization_context=authorization_context,
)
finally:
service.close()
diff --git a/core/show_session_events.py b/core/show_session_events.py
index 4be7d7aad..8f89be79b 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -142,6 +142,39 @@ def show_event_request_requests_dispatch(request_payload: dict[str, Any]) -> boo
)
+def _require_show_dispatch_authority(conn: Any, session_id: str, context: Any) -> None:
+ """Refuse a dispatching Show event the author could not start a turn with.
+
+ A dispatching event is a turn queued under the authority recorded with it,
+ so it has to clear the same chat-and-Agent check any other producer of
+ deferred work clears — and it has to clear it here, inside the transaction
+ that is about to write the event, the screenshot and the Delivery. Leaving
+ the decision to the controller would let a refused author take the session
+ anyway, and would surface the refusal where nobody is waiting for it.
+
+ Only dispatching events ask this. Annotating a page, reading it, and every
+ assistant/system event stay governed by the page capability that admitted
+ the request; none of them starts work in the session.
+ """
+
+ from core.vibe_agents import VibeAgentAccessError
+ from vibe.authorization import InstanceAuthorizationError
+
+ try:
+ workbench_sessions_service.require_session_turn_authority(
+ conn, session_id, authorization_context=context
+ )
+ except LookupError as exc:
+ # Chat access answers "not found" on purpose: someone who cannot reach
+ # the session should not learn it exists. Keep that answer.
+ raise ShowSessionEventError("Agent session not found.", code="session_not_found") from exc
+ except (InstanceAuthorizationError, VibeAgentAccessError) as exc:
+ raise ShowSessionEventError(
+ "Agent session access is not permitted.",
+ code="session_access_forbidden",
+ ) from exc
+
+
@dataclass(frozen=True)
class ShowSessionEventStore:
db_path: Path | None = None
@@ -165,7 +198,23 @@ class ShowSessionEventStore:
*,
author: dict[str, str] | None = None,
reserve_dispatch: bool = False,
+ authorization_context: Any = None,
) -> dict[str, Any]:
+ # A Show event that dispatches is deferred Agent work, and the controller
+ # rebuilds the whole prompt from the reservation it reloads — the IPC body
+ # it was woken with is discarded. So the authority the author was admitted
+ # under has to be recorded here, when the row is written, or it is lost.
+ #
+ # Producers that already validated an identity pass it (the public share
+ # route in particular: its visitor is not whoever the process would
+ # otherwise resolve to). A local CLI invocation passes nothing and the
+ # running invocation's authority answers, exactly as it does elsewhere.
+ from storage.resource_access_service import (
+ metadata_with_resource_user_context,
+ resolve_resource_access_context,
+ )
+
+ access_context = resolve_resource_access_context(authorization_context)
validate_show_event_payload_session(session_id, payload)
event_type = _validate_event_type(payload.get("type"))
actor = _actor_for_event(event_type)
@@ -205,6 +254,9 @@ class ShowSessionEventStore:
)
return existing
+ if show_event_request_requests_dispatch(payload):
+ _require_show_dispatch_authority(conn, session_id, access_context)
+
stored_payload = payload
if event_type == "assistant.mark.resolved":
stored_payload = _prepare_mark_resolution(conn, session_id, payload)
@@ -313,6 +365,10 @@ class ShowSessionEventStore:
if attachments:
content["attachments"] = attachments
metadata.update(_annotation_metadata(event_payload, anchor))
+ # Drops any authority the event payload tried to carry, then
+ # records the trusted one for a remote author. A local author
+ # leaves the metadata byte-identical to before.
+ metadata = metadata_with_resource_user_context(metadata, access_context)
if requests_dispatch:
from core.message_priority import (
delivery_intent_for_trigger,
@@ -355,7 +411,7 @@ class ShowSessionEventStore:
"state": "reserved",
},
)
- delivery = message_deliveries.delivery_payload(delivery_row)
+ delivery = message_deliveries.public_delivery_payload(delivery_row)
conn.execute(
update(show_session_events)
.where(show_session_events.c.id == event_id)
@@ -398,7 +454,7 @@ class ShowSessionEventStore:
"payload": event_payload,
"transcript_text": transcript_text,
"message_id": message_id,
- "message": message,
+ "message": _public_event_message(message),
"delivery_id": delivery_id,
"delivery": delivery,
"created_at": created_at,
@@ -1154,6 +1210,25 @@ def _format_transcript_text(
return _json_dumps(payload)
+def _public_event_message(message: dict[str, Any] | None) -> dict[str, Any] | None:
+ """A transcript message as an event audience may see it.
+
+ The stored metadata carries server-owned identity — the authority a remote
+ author was admitted under, among the fields ``public_message_metadata``
+ already hides. Every audience of an event reads this projection: the POST
+ echo, the ``show.event`` and ``message.new`` streams, the CLI's own result
+ and the local bridge. The row itself keeps the full metadata for the
+ deferred consumers that re-check it.
+ """
+
+ if not isinstance(message, dict):
+ return message
+ metadata = message.get("metadata")
+ if not isinstance(metadata, dict):
+ return message
+ return {**message, "metadata": message_deliveries.public_message_metadata(metadata)}
+
+
def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
payload = _json_loads(row.get("payload_json"), {})
if isinstance(payload, dict):
@@ -1203,10 +1278,10 @@ def _existing_event_payload(
(item for item in window["messages"] if item.get("id") == message_id),
None,
)
- event["message"] = message
+ event["message"] = _public_event_message(message)
delivery_id = event.get("delivery_id")
event["delivery"] = (
- message_deliveries.delivery_payload(delivery)
+ message_deliveries.public_delivery_payload(delivery)
if isinstance(delivery_id, str)
and delivery_id
and (delivery := message_deliveries.get_delivery(conn, delivery_id)) is not None
diff --git a/docs/plans/editor-permission-audit.md b/docs/plans/editor-permission-audit.md
new file mode 100644
index 000000000..275022fb8
--- /dev/null
+++ b/docs/plans/editor-permission-audit.md
@@ -0,0 +1,534 @@
+# Editor permission audit: findings, repairs and residuals
+
+Companion to `editor-permission-parity.md`, which holds the approved contract.
+This file records what the audit actually found, what was repaired, what was
+deliberately left alone, and what remains unproven.
+
+Baseline: `4019b704c99afe16223d475fccd9e1cb94a109d7` (includes Member PR #2030).
+Branch: `fix/editor-permission-parity`. Audit head: `885786909`.
+Implementation lane: `sesv7agy2ckwh`. Orchestrator: `sesnps2m743r5`.
+
+Three further defects were first discovered by review of the first pushed head
+(`83cc8909fc`), not by the original audit pass. They are **not** new roots: one
+completes class A at its consumer, and two are class C at boundaries the class
+already owns. They are recorded below as subordinate sections, under the same
+standard as A–D and with their first-discovery head kept, so the root ledger
+still holds four classes.
+
+## Outcome
+
+The reported defect — an authorized Editor cannot press Run on the Agents page —
+is real. Running an Agent is a *use* operation and the page gated it behind
+`can_manage_agents`, which is *management*. That is a UI gating mistake, and it
+repeats: two more surfaces mix the same two things. Repairing only the button
+would have left those, and would not have touched the more serious half of the
+audit, which is a separate structural defect below HTTP.
+
+The audit confirmed four backend root-cause groups, and review of the first
+pushed head found three more defects inside two of them rather than any new
+root. Of the four, three are kind-handling or admission mistakes local to one
+consumer. The fourth is structural:
+
+> **Ordinary product operations were missing an initiating user.** Role
+> enforcement lived at the HTTP surface, and everything reached below it acted
+> for the machine's Owner. A remote caller's Agent turn therefore reached CLI
+> commands, raw operations and deferred rows that all resolved to standalone
+> Owner — so an action the browser refuses for that same person succeeded
+> through their Agent.
+
+| Class | Actual user effect | Repair |
+| --- | --- | --- |
+| A | Editor's Harness and Vault pages never receive refetch signals; a healthy Vault bridge also disables fallback polling, so the page silently stops updating | Admit instance-scoped invalidations at the tier of the endpoint they announce, and project them to a bare signal below runtime management |
+| B | A signed Personal Editor cannot list or request owner-created secrets that an Organization Editor can | Qualify Personal use on the signed instance kind, the way `agent` already did |
+| C | Unauthorized Harness Run, callback, reservation, fork and direct CLI writes execute as local Owner operations, and deferred work (Vault request, dispatching Show event, Run callback) resumes under the daemon's authority rather than its author's | One invocation-scoped authority at the CLI entry point, a role floor for every parser leaf, reservation/fork checks that read it, and a recorded authority on every deferred row that is hidden from every outward projection |
+| D | An email-authorized Organization Project chat returns HTTP 202 and is then rejected by the final Delivery guard | Carry the normalized signed email in the durable snapshot that Project ACLs compare |
+| A, at the consumer | The Harness page an Editor may read still goes stale: `definitions.updated` is admitted and delivered, and no browser consumer listens for it | Register the listener beside the `runs.updated` one, invalidating the same read cache |
+| C, at the outward projection | The authority recorded for a deferred consumer is readable from an ordinary Harness definition or run read | Project Harness metadata outward through the `public_message_metadata` sanitizer these surfaces already had |
+| C, at the effective target | An Organization Editor can point per-run work at an Agent they may not use, by clearing the Agent and then switching the definition to a new Session per run | Decide the follow-the-Session marker from the *final* session policy, then resolve and admit the Agent every future fire will select |
+
+Three UI findings sit alongside that table and are **not** instances of class C.
+None of them loses an initiating user, and none loosens a server policy — each is
+a client gate naming the wrong one of use and management:
+
+- **Agents Run** (the reported defect): running an Agent was gated on the
+ capability to *manage* its definition. The definition stays locked.
+- **Dock pinning**: gated on instance management rather than page use.
+- **Background-work banner**: an editor-tier page offered a shared member-tier
+ preference as writable, so the switch flipped and reverted. It now reads as
+ read-only below Member and attempts no write.
+
+## What changed, by cause
+
+### A — event admission disagreed with read capability
+
+`definitions.updated`, `runs.updated` and `vaults.updated` are instance-wide
+"refetch me" signals whose endpoints are editor namespaces. They were admitted
+at the runtime-management tier, so the pages that consume them went stale for
+exactly the roles allowed to read them. They now form one named set,
+`INSTANCE_SCOPED_REFETCH_EVENTS`, with two owners: the role tier admits them,
+and the SSE projection reduces the frame to `{"type": ..., "data": {}}` below
+runtime management. Reducing the whole class rather than one field keeps a
+future publisher field from disclosing by default. `remote_access.quality.changed`
+describes the instance's own connection and stays Member-only.
+
+### B — the Personal branch was missing from Vault use
+
+`_policy_allows` already let a validated remote Organization Editor use
+`skill` and `vault_secret` without a stored policy row. A Personal Instance has
+no Organization to be an active member of, so the same rule has to qualify on
+the signed instance kind — which the `agent` branch above it already did.
+Management is untouched: metadata writes still go through
+`_require_secret_resource_management`, and protected secrets still require their
+approval and proof.
+
+### C — the initiating user was missing below HTTP
+
+Three consuming gaps, one cause:
+
+1. **Omitted context at guards that already exist.** `require_instance_role`
+ and `resolve_resource_access_context` treated "no context" as local Owner
+ wherever they ran. Both now consult the invocation authority — but only
+ *outside* an HTTP request, and they behave differently inside one. That
+ difference is a retained boundary, not a repair applied to every HTTP
+ service:
+
+ - `require_instance_role(None)` inside a request still resolves the local
+ Owner, exactly as before. An explicit signed caller owns its own
+ authorization by passing its context; a service call that passes none is
+ not re-attributed to whoever the request happens to belong to.
+ - `resolve_resource_access_context(None)` inside a request reads the
+ request's own resource context, signed or anonymous, and an anonymous one
+ fails closed at the check that consumes it. Unchanged by this PR.
+ - Neither consults the invocation carrier inside a request. It answers only
+ outside one; with neither a request nor an invocation, this is a
+ standalone local entry point and keeps Owner administration.
+
+ So this repair moves the non-HTTP half only. Re-attributing an HTTP service
+ call to the request's principal would be a different change with a different
+ blast radius, and is not made here.
+2. **Raw operations with no guard at all.** `vibe/cli.py` enters
+ `invocation_authority(_cli_invocation_authority())` once in `main()`, around
+ argparse and dispatch, and every parser leaf carries a role floor in
+ `_CLI_COMMAND_FLOORS`. A missing key is `owner`, so a new command cannot ship
+ unclassified. A below-floor command is refused before any effect is written.
+ An invocation that declares no remote caller and carries no snapshot is the
+ historical local entry point and still resolves to the local Owner. A caller
+ that *declares* itself remote, and whose snapshot is missing, malformed,
+ inconsistent with this installation or no longer valid against the current
+ ready binding, becomes anonymous remote — never local Owner. The environment
+ crosses process boundaries and outlives the pairing it was minted under, so
+ the claims alone are not provenance: they are checked against the configured
+ instance and its durable ready binding, the same way every other deferred
+ consumer checks a stored snapshot. That is a consistency check, not
+ authentication — no signature is verified and the JSON itself is not
+ authenticated — so a rejected remote caller does not become the machine's
+ owner just because its claims went stale, and a well-formed claim does not
+ become host-verifiable just because it is consistent.
+
+ The same boundary applies leaving the process. Avibe hands a caller's identity
+ to a subprocess it runs *on that caller's behalf* — an Agent turn, a backend,
+ a Harness call — and that hop is the point of the contract. A process Avibe
+ itself owns is the opposite case: the restart supervisor, a deferred
+ activation, the service and the UI server outlive the call that scheduled
+ them and act as the installation, and their own entry points are Owner work
+ that would refuse an inherited caller. `environment_without_caller_context`
+ strips the provenance at the boundary where the independent process is
+ created, after the scheduling operation has been admitted on its own merits.
+3. **Deferred and IPC producer loss.** Work decided after the call that created
+ it is rebuilt from a stored row, not from the message that woke the daemon,
+ so both the decision and the authority have to be taken where the row is
+ written. `require_reservation_access` holds a new reservation to the
+ caller's Project-placement and Agent authority; `reserve_forked_session`
+ checks source and destination independently and holds both an overridden and
+ an inherited Agent to selection authority; the deferred rows below carry the
+ resolved authority itself. A caller with no context at all is the historical
+ local entry point and reserves exactly as before.
+4. **The effective target, decided before the work exists.** Clearing a
+ command's role floor says the caller may create work of that kind; it does
+ not say they may put it in *this* Session. Every deferred producer in the CLI
+ — `agent run`'s existing and forked branches, `hook send`, an explicit
+ callback route, and `task`/`watch` `add` and `update` — now runs the existing
+ `require_session_turn_authority` over its resolved target before anything is
+ written, so a Run row, a callback route or a stored definition never lands in
+ a Session the caller cannot drive, and the refusal arrives where someone is
+ waiting for it instead of at dispatch. The target is resolved the way its own
+ dispatch resolves it: a Session id through `resolve_session_id_target`, a
+ legacy scope key through the same `(scope, anchor)` lookup the inbound message
+ path uses, and a target defaulted from the caller environment like any other.
+ New and forked reservations keep their own checked writer from (3); the
+ explicit callback is admitted before either the reservation or the parent
+ enqueue.
+
+ *Effective* is decided by the edit, not by the stored row. A `task`/`watch`
+ `update` that keeps its binding — named again, or simply left alone — is held
+ to that Session. One that **replaces** it is not: the definition will never
+ speak in the old row again, so asking for it refused an Editor for a Session
+ their own edit was removing, and passing it would have been the wrong question
+ anyway. What those edits are held to is where the work will actually land. A
+ reusable Session is admitted by the reservation writer as it reserves; a
+ definition that creates one Session per run reserves nothing while the caller
+ is present, so it asks the identical question through
+ `require_session_placement_authority` — the same `require_reservation_access`
+ policy, resolved but never committed — before the row that would carry the
+ placement into every future fire. Both `add` and `update` go through it, so
+ the two commands answer for a destination the same way.
+
+ That gate also settles the one shape with no destination at all: a per-run
+ definition with no Scope reserves a *standalone* Session on every fire, which
+ is precisely the reach an Editor is refused when they name one directly. It is
+ now refused at creation instead of quietly granted a stream of them, on both
+ instance kinds — an unplaced Session belongs to no Project, so no Personal
+ Project bypass applies. Member, Owner and local callers keep it.
+
+ "No Session" is not one answer. A well-formed legacy key whose thread nobody
+ has opened yet still says where work will land: the Session is reserved on the
+ first dispatch, in the Scope the caller named. Treating that as no target at
+ all handed the same Editor the IM thread that does not exist while refusing the
+ one that does — an IM Scope is not a Project, so both are refused for an Editor
+ and neither depends on the Personal bypass. `hook send`, `task add/update` and
+ `watch add/update` now finish the same question for it, as the placement it is,
+ once the Agent the future dispatch will select is resolved. What stays untouched
+ is every genuinely empty target — a blank argument, an ID or key that does not
+ parse, a binding whose row is gone, archived or runtime-owned — which keeps the
+ shape, lifecycle and repair behavior its own path already defines. That keeps
+ this an authorization question rather than an existence check, and keeps a
+ stale binding editable by the person who has to fix it. The refusals a creating
+ command gets are now typed like the ones a binding command gets: a denied
+ Project, instance role or Agent reaches the caller as its own code rather than
+ as `task_command_failed` with prose.
+
+ Saved automation control is deliberately outside the gate. `task run`,
+ `pause`, `resume` and `remove` steer a definition that already carries its
+ own admitted authority; revalidating that target as the current invoker would
+ restamp saved work to whoever pressed the button. Pure command tasks have no
+ Session and keep their approved semantics. This is a preflight over authority
+ that already exists, not a per-definition Harness ACL.
+
+Current floor distribution over 93 parser leaves: 6 viewer, 55 editor, 19
+member, 3 owner, 10 deliberately ungated (`status`, `version`, `check-update`,
+`screenshot`, `debug prompt export` and the Memory read family). `remote pair`
+is Owner and refuses before a pairing key is ever solicited.
+
+#### C, deferred half — the row had no author
+
+A Vault request is decided long after the call that created it, and a
+dispatching Show event resumes a turn from a reserved delivery rather than from
+the message that woke the daemon. Both now record the resolved authority at the
+producer and read it back at the consumer, with one rule on each side:
+
+- **The row keeps it.** `vault_requests.requester` carries the snapshot and
+ `request_authorization_snapshot` reads it for the auto-resume callback; the
+ reserved `message_deliveries` row carries it for the Show turn, which is the
+ only valid carrier because `_dispatch_async` overrides the IPC body.
+- **No outward view keeps it.** Request payloads, `get_request`, `list_requests`,
+ every `vault_audit` row (stripped once at the chokepoint), the Show event echo
+ and the transcript stream all project it away.
+- **A local caller is byte-for-byte unchanged.** The snapshot is written only
+ when the context is remote, so nothing is added and nothing is stripped.
+
+Recording an authority is only as good as the decision it was recorded from, so
+each producer also takes that decision once and before the row exists:
+
+- `ShowSessionEventStore.append` pre-checks chat access and Agent selection for
+ a *dispatching* event, inside the transaction that writes the event and the
+ reservation, so an author who could not start the turn never occupies the
+ session. Non-dispatching events stay governed by the page capability that
+ admitted them.
+- The Vault access/sign/provision request family refuses a request that names a
+ Session its caller could not resume, before any approval card, row or audit
+ line exists. A request that names no Session, and one whose id no Session
+ answers to, are unchanged.
+- The public `/p` write resolves its visitor exactly once. Admission, the
+ display author and the authority the reservation is written under all read
+ that one object, so pairing, claims or access changing between two awaits
+ cannot admit one person and record the turn under another. No resolved
+ visitor is a 403, never a fall through to the store's local-Owner default.
+- `vibe show event` no longer swallows a refused reservation: the reservation's
+ failure is the command's failure.
+
+The CLI reserves its own dispatching Show event under its caller, and the live
+UI POST that replays the same id preserves that authority while still returning
+a delivery, so dispatch still happens.
+
+### D — the durable snapshot omitted the email
+
+Project ACLs bind `email` and `email_domain` principals, so a snapshot without
+an email denied deferred work that the live request had allowed.
+`metadata_with_resource_user_context` now writes the signed email, normalized
+the way `_matching_binding_role` compares it, and writes it *after* dropping any
+caller-supplied copy — so untrusted metadata can neither mint nor override it.
+A historical record without an email is not given one.
+
+### A, completed at the consumer — an admitted signal nothing listened for
+
+First discovered by review of `83cc8909fc`; the same admission root as A, one
+step further along the same delivery path. A admitted `definitions.updated` at
+the tier that may read it, and the stream delivered it. Nothing in the browser
+listened for that name. `runs.updated` had a handler and `definitions.updated`
+did not, so a Task or Watch created, paused or retired anywhere else left the
+Harness page stale until an unrelated run happened to fire. Admission without a
+consumer is the same stale page the class was opened for, so the listener is now
+registered beside the one that
+already worked, invalidating the same read cache. Covered by a test that drives
+the real stream — a named frame reduced to `{"type": ..., "data": {}}`, through
+the provider's own listener, with no runs event and no reconnect.
+
+### C, at the outward projection — the recorded authority was readable
+
+First discovered by review of `83cc8909fc`; class C's own rule applied at a
+boundary that had been missed. C records the initiating caller on the durable
+row, and every Vault and Show projection of that row hides it. The Harness
+projections did not: the CLI
+Task/Watch/Run payloads and the `include_private_metadata=False` store handed
+back the whole metadata dictionary, so the snapshot written for a deferred
+consumer — subject, email, organization identifiers — was readable from an
+ordinary definition read. They now project through `public_message_metadata`,
+the sanitizer these surfaces already had. The durable original is untouched: no
+schema change, no migration, no backfill, and internal consumers that need the
+delegated owner still read it through the unchanged internal path.
+
+### C, at the effective target — decided before the policy that defines it
+
+First discovered by review of `83cc8909fc`: the same effective-target rule class
+C introduced, on the one transition where the marker had already decided the
+answer before the policy that defines it existed.
+`--clear-agent` hands the Agent choice to the Session a definition is bound to
+and marks the row `binding_follows_session`; a later edit then deliberately
+resolves no Agent, because the bound row already answers and re-resolving would
+pin today's default over it. `create_per_run` has no such row — every fire makes
+a throwaway Session from the definition itself — so on that transition the
+marker outlived what it described: the edit skipped Agent resolution while each
+future fire still selected the Scope's default, and the placement guard, handed
+no Agent, had nothing to admit. An Organization Editor could therefore point
+per-run work at an Agent they may not use. The marker is now cleared from the
+*final* session policy, before the Agent is resolved and admitted, rather than
+after the row is saved. The adjacent transitions keep their behavior on purpose:
+a retained bound Session and a `create_once` replacement both already resolve and
+check an Agent — through the turn guard and through `reserve_agent_session`'s
+`require_reservation_access` respectively — so nothing there is re-authorized.
+
+Repairing this also closed a crash that pre-dates this PR on the same code
+branch: at baseline `4019b704c` the reservation writer reads
+`agent.id if agent else None` while the follow-the-Session branch above binds
+nothing, so `--clear-agent` followed by `--create-session` raised
+`UnboundLocalError`. `agent` is initialized once, where every branch can be read
+together. Stated from the baseline source; no baseline test covers that pair.
+
+## Surface inventory and retained boundaries
+
+`V/E/M/O` are central Viewer/Editor/Member/Owner minima, not substitutes for the
+service and resource checks below them. Both instance kinds were considered;
+Personal Agent/Project bypass and Organization ACL differences are intentional.
+
+"Correct" in this table is a reviewed reading of the admission and consuming
+boundary, not a runtime result: only the rows marked **Fixed** have executed
+coverage in this PR, and the evidence section below says which. A row that is
+correct here is not a claim that its whole surface was exercised.
+
+| Surface | Admission and consuming boundary | Disposition |
+| --- | --- | --- |
+| Agents list/detail/backends, graph/running records | E; selection uses `core/vibe_agents`, runtime projections combine effective Session and Agent access. Organization no-policy Agent stays unavailable; Personal E bypass retained | Backend boundary correct. **Fixed:** the UI Run gate (UI use/management, not class C) and the CLI read/mutation family |
+| Agent defaults and definitions | M; advisory default resolves only to a usable Agent for lower roles. Bulk onboarding O | Retained. **Fixed:** one direct CLI management bypass |
+| Projects list/detail/bootstrap | V plus effective Project role; archived Project unavailable to E/V | Correct |
+| Project create/edit/order/archive/agents-md | M; access ACL PUT remains O | Retained, no Editor grant |
+| Session create/PATCH/settings/fork/archive | E plus `enforce_project_role_capabilities` and service checks | **Fixed:** CLI reservation/fork/mutation effects |
+| Session send/retry/cancel/queue/draft/attachments | E and effective Project E via middleware over `/api/sessions/{id}/...`; final Delivery guard rechecks | **Fixed:** class D email. Handlers without repeated inline ACL are not findings — the middleware consumes the route |
+| Standalone and IM Sessions | E/V effective Session role is None without a Project, including Personal | Boundary retained. **Fixed:** the alternate CLI producer that bypassed it |
+| Harness Task/Watch/Run | E namespace; producers use `ensure_harness_definition_write`; execution checks Agent, current binding and the final Session boundary | **Fixed:** class A refresh, class C Run/callback producers. The proposed org-aware Harness ACL is not shipped and was not used to manufacture a finding |
+| Skills | E; `core/services/skills.py` grants Editor use/management, project-scoped mutation also needs Project Editor | Correct as shipped |
+| Vault secrets/request/grant/audit/settings/pin/reveal/sign | E is only the HTTP floor; metadata/pin/rotation/deletion add M; proof and approval rules stand | **Fixed:** class B Personal use, class C deferred auto-resume and the request-target pre-check, direct CLI metadata |
+| Memory | V namespace with the Memory principal and its identity isolation | Correct; no Owner-like Memory principal for E/M |
+| Files | E namespace; `file_browser_service` retains path/OS/size/symlink/write-race rules | Correct. No per-Project filesystem sandbox is shipped or proposed here |
+| Terminal websocket and DELETE | WS E with signed context/origin, terminal id subject-scoped; DELETE V so a downgraded user can close their own terminal | Correct |
+| Voice/cloud token and model picker | E; native OpenCode live provider catalog stays M because it can operate daemon/config | Correct |
+| Model providers/credentials/OAuth and global prompts | M explicit methods, unknown siblings O | Retained |
+| Show page read, HMR, events, dock, publication | V read, E published controls as shipped; creation requires an authorized Session; remote paths redacted | **Fixed:** class C author provenance, the dispatching-event pre-check and the resolve-once public write, and Dock pinning follows page use. Publication is *not* raised to M from its name |
+| Inbox/search/messages/media/mark-read | V plus accessible scopes; `messages.read_at` stays shared by existing contract | Correct |
+| Web Push | V namespace, recipient identity via `_web_push_user_key` | Correct; recipients are never merged |
+| Workbench SSE | V connection, per-event role plus resource visibility and payload projection | **Fixed:** class A only; all other filters retained |
+| Diagnostics/settings/control/logs/remote transport | M explicit operations; GET config V sanitized; POST config E for whitelisted appearance/ASR fields only; workbench prefs PUT M | Correct. **Fixed:** the banner switch now reads that M tier instead of flipping and reverting |
+| Access/identity/pairing/bind codes/onboarding/users admin | O exact routes; IM admin identity separate | No new grants. **Fixed:** `vibe remote pair` now refuses at the CLI before soliciting a key |
+| SQL/CLI diagnostics | Read-only SQL `skill_usage_daily` and `agent_events` at M; raw Vault data denied | Retained. The CLI families are covered by the floor table, not by a universal Owner exception |
+
+## Scenario coverage
+
+Registered in `tests/scenarios/permissions/catalog.yaml`, with
+`OBS-PERMISSIONS-005` recording the class.
+
+| ID | Covers | Layer |
+| --- | --- | --- |
+| PERMISSIONS-020 | Running an Agent is independent of managing its definition | UI scenario |
+| PERMISSIONS-021 | Dock pinning follows page use, not instance management | UI scenario |
+| PERMISSIONS-022 | Shared banner preference stays member-tier on an editor surface | UI scenario |
+| PERMISSIONS-023 | Reservation and fork preflight follow the caller's own authority | scenario |
+| PERMISSIONS-024 | A deferred Vault request keeps the authority that created it | scenario |
+| PERMISSIONS-025 | Project email ACLs compare the principal the request carried | unit |
+| PERMISSIONS-026 | An ordinary CLI command runs under the caller that invoked it | scenario |
+| PERMISSIONS-027 | A dispatching Show event records the author who started the turn | scenario |
+| PERMISSIONS-028 | Deferred work admits its effective target before the row is written | scenario |
+
+PERMISSIONS-016 is extended rather than duplicated: an Editor now receives the
+instance-scoped invalidations as bare frames, and its `related_tests` carry the
+consumer half — the Vault refresh hook, the Vault page's pending requests and
+the Harness page all refetch from a frame with no body. A's consumer completion
+is the same scenario's missing half: one of those `related_tests` now drives the
+Harness page from a bare `definitions.updated` frame specifically, with no runs event
+and no reconnect, so admission and consumption are asserted for the same name.
+
+PERMISSIONS-024 and PERMISSIONS-027 also cover the pre-effect target checks:
+a Vault request that names an unreachable Session, and a dispatching Show event
+in one, are refused before any row exists. PERMISSIONS-027's `related_tests`
+carry the public `/p` evidence, where a changing resolver proves the visitor is
+resolved exactly once and that no resolved visitor is a 403.
+
+## Evidence: what is static and what actually ran
+
+Static classification, not runtime proof:
+
+- the registered `/api` route minimum appendix (291 methods/paths) — every route
+ was read and classified; they were not all executed
+- the CLI floor table's *values*. Completeness is a runtime assertion
+ (PERMISSIONS-026 drives the real parser), but whether each individual floor is
+ the right tier is a reviewed judgment, not an executed one
+- file-browser and voice/cloud route classification — no filesystem outside a
+ disposable fixture and no provider contact
+
+Executed:
+
+- PERMISSIONS-026 drives the real `cli.main` with the caller env written exactly
+ the way the host writes it, across the parser, the env hop, pre-effect refusal
+ and the authority's lifetime, and proves one refusal leaves the record it
+ would have written unchanged
+- PERMISSIONS-024 writes and reads back real `vault_requests` rows, paired
+ local/remote, and drives the real `_process_vault_callback_sync` and
+ `TaskExecutionStore` so the original snapshot lands on the resumed callback
+ rather than the daemon's own authority. Its reach ends there: those two
+ auto-resume cases stub `resolve_session_id_target` and assert on the child
+ request's metadata, so they prove the producer writes and the callback carries
+ — not that the Delivery guard then consumes that snapshot. They remain
+ metadata-level tests and are not restated as end-to-end ones
+- the Vault chain's own end is closed separately: PM and the auditor consumed
+ all six Vault access/sign/provision chains end to end, from the recorded
+ producer through the resumed callback to the guard that acts on it. That is
+ executed evidence held outside this repository's suites, not a property
+ PERMISSIONS-024 asserts
+- PERMISSIONS-027 exercises the real Show event store over real SQLite, paired
+ local/remote, including the CLI producer and the live UI replay, and carries a
+ producer-to-consumer chain of its own: an admitted reservation is still
+ admitted by `SessionTurnManager`'s execution guard, and revoking the Project
+ after the reservation stops that same turn
+- the real `/p` share route posts a dispatching annotation through the Flask
+ test client: one resolver call serves admission, author and the recorded
+ authority, and the reservation the controller picks up carries that visitor.
+ With PM's independent signed-HTTP callback probe, this is the executed
+ evidence that a recorded authority survives to its final consumer
+- PERMISSIONS-028 drives the real `cli.main` on a real pairing for both instance
+ kinds, over every deferred producer — Run, hook, explicit callback, Task and
+ Watch, add and update, target typed, defaulted from the caller env or named by
+ a legacy scope key. A refusal is asserted as unchanged Run, definition and
+ Session counts and, for an update, a byte-identical stored row; the permitted
+ Editor, the Member, the Owner and the local caller all still queue their work.
+ It also holds the replacement pair both ways: an edit that repoints a Task or
+ Watch at a destination the caller may use succeeds through the real reservation
+ writer, while the same edit aimed at a Project they cannot chat in is refused
+ for both placements — the one that reserves during the edit and the one that
+ only describes where every future fire will land — leaving no Session and no
+ row change. The unopened-thread branch is held both ways across all three
+ legacy-key producers and their updates: a signed Editor is refused
+ `project_access_denied` on both instance kinds with Run, definition, Session
+ AND Scope counts unchanged — the check resolves the Scope it asks about and
+ must leave nothing behind — while Member, Owner and local callers still open
+ that thread. Its saved-control case asserts `pause`/`resume` only: that control
+ does not restamp the definition's authority
+- C's effective-target gap is held by the same case family, across the whole
+ marker transition rather than at its end: per-run work whose Agent was cleared
+ is refused `agent_access_forbidden` on an Organization instance with the row —
+ marker included — and the Session count unchanged, and admitted on a Personal one
+ where it keeps the Agent it resolved. The adjacent transitions are asserted
+ *not* to have moved: a retained bound Session and a `create_once` replacement
+ both still leave the Agent to the Session and keep the marker. The direction
+ was proved by counterfactual, not by assertion alone — with the marker read
+ from the previous policy the Organization case is admitted, and with the fix
+ in place it is refused
+- C's outward projection is held at the read the consumers actually use: the CLI
+ Task, Watch and Run payloads and the `include_private_metadata=False` store
+ return metadata with no recorded authority, while the same row read internally
+ still carries it
+- PM's own round-1 probe was re-run on the repaired tree with its assertions moved
+ onto the repaired behavior rather than its old exit codes: the counterexample it
+ measured (Organization, exit 0, marker retained, no Agent admitted) is now exit 1
+ `agent_access_forbidden` with a byte-identical row, Personal still succeeds with
+ the marker cleared and the default Agent pinned, and the outward projection
+ carries no authority while the durable row still does
+- saved Task **execution** was consumed independently by PM, not by that case:
+ a Member-created Task targeting a standalone Session is admitted when a signed
+ Editor runs it, the stored Run and the definition both keep the original Member
+ snapshot, and the real `_execute_task` → `_execute_request` → persisted Delivery
+ → `SessionTurnManager` guard chain admits it — while the same Delivery carrying
+ the Editor's snapshot instead is refused `remote_project_access_forbidden`, with
+ provider submit intercepted at the final gate
+- PERMISSIONS-020/021/022 render the real authorization provider per role and
+ follow the click through to the API call, including revocation mid-session
+- the event-tier change is proved at both ends: PERMISSIONS-016 collects real
+ SSE frames per role, and its consumer tests drive the real refresh hook, the
+ real Vault page and the real Harness page from a frame with an empty body. The
+ hook test also holds the polling contract the predicate alone could not — a
+ healthy bridge stops the fallback poll, a reported disconnect restores it
+- the auditor lane ran 322 baseline tests unmodified, and PM independently ran
+ signed-HTTP, broker and CLI probes (`/tmp/avibe-editor-permissions-sesnps2m743r5/`)
+ including a 16-case `test_pm_cli_entry.py` over Personal/Organization ×
+ Viewer/Editor/Member/Owner/local with persisted effects
+
+Not claimed: exhaustive runtime verification of every route, every CLI command
+or every transport; no live service, tenant, cloud account, real key operation,
+schema change or deployment was used anywhere in this work.
+
+## Residual ledger
+
+- **Historical records carry no authority snapshot (origin UNPROVEN).** Vault
+ requests and Run callbacks written before this change record no
+ remote/local distinction. `requester.source="agent-cli"` is written by the
+ HTTP path too and cannot prove local origin; a current Session does not prove
+ its historical request author. They stay unattributed. No backfill, migration,
+ version marker or inferred principal — and this is a compatibility limit, not
+ evidence that those records were locally authorized. A historical missing
+ email is likewise not reconstructed.
+- **Host-scoped operations keep host scope.** `screenshot` and
+ `debug prompt export` act on the machine, not on instance resources.
+- **Sandboxing is a different boundary.** Terminal, filesystem, shell and SQL
+ confinement is out of this class (issue 1389) and no confinement model is
+ proposed here.
+- **Cross-surface exclusion still needs an explicit IPC hop.** `vibe/api.py` and
+ the controller are separate processes; see PR #1417's known-by-design ledger.
+- **Callback rerouting is unchanged.** A parent's callback is still marked
+ `sent` when a child is durably created; a later deferred permission denial is
+ a child outcome and is not rerouted or re-authorized to make delivery succeed.
+- **The caller environment is a trusted-origin channel, and what this handles is
+ a malformed one.** Avibe writes the carrier when it launches a command on a
+ caller's behalf, and the CLI entry point reads it once. An invocation that
+ carries nothing at all is the historical local entry point and still resolves
+ to the local Owner; no absent-byte case becomes a remote one. What was repaired
+ is what happens to an invocation that **declares** a remote caller: a snapshot
+ that is missing, malformed, inconsistent with this installation or no longer
+ valid against the current ready binding stays an anonymous remote context and
+ fails closed, never the local Owner, and the floor is evaluated against that
+ context. The binding check establishes consistency with this installation and
+ its current pairing — it does **not** authenticate the JSON and verifies no
+ signature, so nothing here makes the claims host-verifiable. That is the whole
+ claim. It is **not** protection against someone who can already
+ edit that environment or the state database directly — a principal with the
+ host has the host, sandboxing is a different boundary (issue 1389), and no
+ confinement, host signature, token issuance or second role model is proposed
+ here. Nothing in this PR should be read as raising the trust of the channel
+ itself.
+- **The raw caller snapshot forwarded by seven CLI commands was investigated and
+ closed as not a defect**, under exactly that boundary. `task add`/`update`,
+ `watch add`/`update`, `agent run`, `data query` and `data skill-usage` hand
+ their own env snapshot to the services they call. Each of those commands sits
+ behind an `editor` floor evaluated against the invocation authority the entry
+ point resolved — the declared-remote context, or the local one when nothing was
+ declared — and none of the ten deliberately ungated commands forwards one, so
+ an unusable snapshot is already an anonymous remote context that never reaches
+ them. Proved by execution rather than by reading: a stale snapshot aimed at a
+ forwarding command is refused `instance_access_forbidden` with the record
+ unchanged (PERMISSIONS-026). No second validation hop was added.
diff --git a/docs/plans/editor-permission-parity.md b/docs/plans/editor-permission-parity.md
new file mode 100644
index 000000000..8487ac08b
--- /dev/null
+++ b/docs/plans/editor-permission-parity.md
@@ -0,0 +1,281 @@
+# Editor permission audit and parity repair
+
+Status: approved bounded repair contract, audit and implementation in progress.
+Date: 2026-09-18. Orchestrator: `sesnps2m743r5`.
+Baseline: `4019b704c99afe16223d475fccd9e1cb94a109d7` (includes Member PR #2030).
+Implementation branch: `fix/editor-permission-parity`.
+
+## Outcome and authority
+
+The owner requested a complete Editor permission check and repair of confirmed
+inconsistencies after discovering that the Agents detail Run button is hidden
+from an otherwise authorized Editor. Deliver one reviewed, CI-green PR. Prior
+permission to merge #2030 does not authorize this PR's merge or any deployment.
+Do not change the dirty primary checkout or running local/tenant services.
+
+Example: an Organization Instance Editor with use access to an enabled Agent and
+Editor access to an active Project can start a chat with that Agent in that
+Project. The Agents page currently wraps Run and its dialog in
+`can_manage_agents`, preventing that operation even though the backend accepts
+it. Running an Agent is a use operation; editing its definition is management.
+
+## Frozen behavioral boundaries
+
+- Reuse the existing capabilities and effective resource/session permissions.
+ Editor may use authorized Agents, create and operate authorized Project
+ sessions, and use other existing Editor capabilities. A stronger management
+ gate must not block an operation already granted by the intended policy.
+- Preserve Personal versus Organization semantics. Organization Agent ACLs,
+ restricted Project bindings and effective Viewer downgrades still apply.
+ No-policy Organization Agents remain unavailable to Editor. Personal Editor
+ Agent/Project bypasses stay as shipped. A denied/missing/disabled resource
+ remains denied by the authoritative service even if client state is stale.
+- Preserve Editor's standalone/non-Project session boundary, archived-session
+ lifecycle, missing-resource behavior and existing execution admission checks.
+ This is policy/consumer consistency work, not the deferred four-role redesign.
+- Editor does not gain instance configuration, Agent definition management,
+ Project administration, model-provider management, access/ACL administration,
+ pairing, binding-code, identity, ownership or bulk onboarding authority.
+ Preserve existing exceptions actually granted to Editor (such as current
+ Show publication semantics) rather than redefining them from naming alone.
+- Member/Owner behavior from #2030, Viewer restrictions, Memory principals,
+ terminal identity, Web Push recipients, protected Vault proof, IM admin,
+ shared read_at and Show sharing/publication remain unchanged.
+- Unknown HTTP routes/events remain deliberately classified and fail closed;
+ do not use a broad editor bypass or loosen server policy to match a broken UI.
+- Existing appearance and controls are reused; no layout redesign or new product
+ flow. Grant/revoke transitions must leave valid controls usable and forbidden
+ actions disabled/hidden, including already-open dialogs and callbacks.
+
+## Audit scope and disposition
+
+Cover all Editor-related frontend capability/raw-role gates and their actual
+API consumers; navigation, Agents/use/selection, Projects/session creation,
+chat send/queue/retry/cancel/fork/archive/settings, file/terminal tools, Skills,
+Vault use, Memory, Harness Tasks/Watches/Runs, Show, inbox/search/notifications,
+SSE/WebSocket, diagnostics and settings. Review server route tiers and relevant
+resource/service/consumer checks for both excess and missing authority.
+
+Record each surface as: intended operation; capability and resource checks;
+actual HTTP method/path or execution consumer; evidence; disposition (correct,
+confirmed bug, retained boundary, or unresolved with specific missing evidence).
+A hidden button, a 403, or a role name alone does not establish a defect. Trace
+both the producer and consuming effect. Consolidate same-cause findings.
+
+## Work ownership and allowed changes
+
+One implementation lane owns ALL product/test changes and final audit/contract
+updates. An independent backend audit lane is read-only for production/tests
+and writes only its own audit report in its isolated workspace. Reports go to
+PM, who classifies findings and forwards approved concrete corrections; auditors
+never edit the implementation worktree or independently open a competing PR.
+
+Implementation scope: authorization gates and the directly coupled call path in
+`ui/src/components/`, `ui/src/context/`, `ui/src/lib/`, `ui/src/App.tsx`, focused
+existing UI tests/i18n; narrow traced permission defects in `vibe/authorization.py`,
+`vibe/ui_server.py`, `vibe/api.py`, permission-consuming `storage/*_service.py`
+and `core/` consumers only when the audit demonstrates an existing contract
+violation. Record the exact files and causal proof before broadening beyond the
+known Agents Run defect. Seek PM diagnosis for genuine policy ambiguity; ordinary
+reversible corrections within this contract are already authorized.
+
+Tests/scenario metadata and English docs under `docs/plans/` are in scope.
+No dependencies, schemas, migrations, cloud/backend repository, framework rewrite,
+onboarding design or unrelated feature changes. #2030 migration is not reopened.
+Other active lanes (notably shared-backend-connection) are no-touch; use an
+isolated checkout and report overlap rather than modifying their branches.
+
+## PM decisions recorded during implementation
+
+### Scope of the structural class
+
+- The structural finding is one class: **ordinary product operations were
+ missing an initiating user**, with three consuming gaps — omitted context at
+ guards that already exist, raw operations with no role/resource guard, and
+ deferred/IPC producer loss. All deferred Show, Vault and Run provenance stays
+ under that root class rather than being split into a class of its own.
+- Admitted scope for the expanded class: Agent, Session, Run/Task/Watch/Hook,
+ Vault, Show, Runtime/config, Skills, Memory.
+- Excluded: no backfill or migration for historical unstamped records (their
+ origin stays UNPROVEN); `screenshot` and `debug prompt export` keep host
+ scope; terminal/filesystem/shell/SQL sandboxing is a different boundary.
+- Not findings, on evidence: browser provenance and the reservation writer's
+ placement check were already repaired in this branch, and a synthetic public
+ `None` context is not a bypass.
+- The audit's surface inventory is a reviewed classification. Only the rows with
+ executed coverage may be reported as verified.
+- The three UI gates (Agents Run, Dock pinning, background-work banner) are
+ use-versus-management findings in the client. They are named separately and are
+ not counted into the backend A/B/C/D classes.
+
+### Frozen semantics
+
+The decisions above fix scope; these fix behavior. Together with
+`docs/plans/editor-permission-audit.md` they are the reviewable contract for
+this PR.
+
+- **Authority precedence is explicit > HTTP > invocation > local Owner.** An
+ explicitly passed context always wins. Inside an HTTP request the resolvers
+ keep their existing behavior and never consult the invocation carrier:
+ `require_instance_role(None)` still resolves the local Owner, and the resource
+ resolver still reads the request's own signed or anonymous context and fails
+ closed downstream. Outside a request the active invocation authority answers;
+ with neither, this is a standalone local entry point and keeps Owner.
+- **The invocation authority is scoped to one invocation.** One entry point sets
+ it around one dispatch and resets it in `finally`, so an exception, `SystemExit`
+ and nested or sequential invocations all restore the previous authority.
+ Activating `None` is meaningful: an explicit local invocation nested under a
+ remote one masks it and restores it on exit.
+- **A declared-remote caller with missing or malformed provenance fails closed.**
+ It becomes an anonymous remote context. It never degrades to local Owner
+ because the data it should have carried is absent. An invocation that declares
+ nothing and carries nothing is a different case: that is the historical local
+ entry point and keeps resolving to the local Owner.
+- **Claims are checked for consistency with the current binding, not merely
+ parsed — and not authenticated.** The carrier is an environment that crosses
+ process boundaries and outlives the pairing it was minted under, so a
+ well-formed claim is not yet provenance: it is accepted only for the instance
+ this installation is configured for and only while that instance holds a
+ durable ready binding — the same check every other deferred consumer applies to
+ a stored snapshot. That is a consistency check and nothing more: no signature
+ is verified and the JSON is not authenticated. A claim for another instance, or
+ one whose binding is gone, is stale rather than privileged: it becomes
+ anonymous remote, never local Owner.
+- **A process Avibe owns does not inherit the caller.** The identity hop exists
+ for a subprocess run *on a caller's behalf*. The service, the UI server, the
+ connector, the restart supervisor and a deferred activation outlive the call
+ that started them and act as the installation, so
+ `environment_without_caller_context` strips the carrier where that process is
+ created, after the scheduling operation has been admitted on its own merits.
+ `None` is materialized rather than passed to `Popen`, so an implicit inherit
+ cannot carry the caller across either.
+- **Provenance must be durable, not ambient.** Work decided after the call that
+ created it runs in another process, where no carrier reaches. The authority is
+ therefore written into the row — `vault_requests.requester`, the reserved
+ `message_deliveries` row — and read back from it. The snapshot is written only
+ for a remote context, so a local caller's bytes are unchanged, and no outward
+ view (payloads, `get_request`, `list_requests`, `vault_audit`, the Show echo,
+ the transcript stream) exposes it.
+- **Agent use is Editor; Agent definition management is Member.** Running,
+ listing, showing and reading models are Editor. Create/update/enable/disable/
+ remove/import/default are Member. The reported UI defect is exactly this line
+ drawn in the wrong place.
+- **Raw Session operations carry role and resource guards.** Reads are Viewer;
+ update, send-now and queue mutation are Editor, on top of the effective
+ Project/Session resource check that already existed.
+- **A manual Harness run is Editor control of a saved definition's authority.**
+ `task run` executes a definition whose authority was fixed when it was saved;
+ it does not re-authorize to the person pressing run. Harness namespaces stay
+ instance-wide and the scheduler is unchanged — no org-aware Harness ACL is
+ introduced by this PR.
+- **Deferred work is admitted for the target it will actually use, before the row
+ exists.** A producer that binds to an existing Session is held to that Session;
+ one that creates its own is held to the destination Scope and Agent it chose. An
+ edit decides which applies: keeping a binding — named again or simply left alone
+ — reauthorizes it, while replacing it is judged on the destination and never on
+ the Session the edit is removing, because old-target authority is not a source
+ requirement for creating a new one (this is not a fork). Which of those applies
+ is read from the edit's **final** session policy, not from the policy the row
+ arrived with. `--clear-agent` leaves the Agent choice to the Session a definition
+ is bound to and marks the row accordingly; an edit that turns the same definition
+ per-run clears that marker, because a per-run definition has no bound Session to
+ hold that authority, and it does so before resolving and admitting the Agent every
+ future fire will select. A retained binding and a `create_once` replacement keep
+ the marker: both already resolve and check an Agent elsewhere, so neither is
+ re-authorized here. A `create_per_run`
+ definition asks the reservation writer's own question through
+ `require_session_placement_authority`, since it reserves nothing while the caller
+ is present; with no Scope at all it would reserve a standalone Session per fire,
+ so an Editor is refused there on both instance kinds while Member, Owner and
+ local callers are unchanged. A target that names a Scope whose Session does not
+ exist yet — the deprecated IM key for an unopened thread, accepted by `hook send`,
+ `task add/update` and `watch add/update` — is that same placement, not an absent
+ target: it is admitted once the Agent the future dispatch will select is known.
+ An empty target stays what the path that owns it says it is — a blank argument,
+ an unparseable ID or key, or a binding whose row is gone keep their existing
+ shape, lifecycle and repair behavior and gain no authorization meaning. Saved
+ automation control — `task run`, `pause`, `resume`, `remove` —
+ stays outside this gate. No scheduler change and no per-definition Harness ACL.
+- **The caller environment stays a trusted-origin channel.** Avibe writes the
+ carrier when it launches a command on a caller's behalf; the CLI entry point
+ reads it once. An invocation that carries nothing at all is the historical
+ local entry point and still resolves to the local Owner. What this PR fixes is
+ a *malformed* origin on an invocation that **declares** a remote caller: a
+ snapshot that is missing, malformed, inconsistent with this installation, or no
+ longer valid against the current ready binding stays an anonymous remote
+ context and fails closed, never the local Owner. That check establishes
+ consistency with this installation and its current pairing; it does **not**
+ authenticate the JSON and verifies no signature, so the claims are not
+ host-verifiable and must not be described as such. It is not protection against
+ a principal who can already edit that environment or the state database
+ directly, and must not be described as one. No host signature, token issuance,
+ sandboxing, shell/SQL confinement, new expiry or second role model is
+ introduced here.
+- **An admitted instance-scoped signal has a consumer.** Raising
+ `definitions.updated` to the tier that may read it is only half the repair; the
+ page it announces has to listen for that name. The Harness page now refetches
+ from a bare `definitions.updated` frame the same way it already did for
+ `runs.updated`. No new event, no new tier, no polling fallback added.
+- **The recorded authority is internal.** The snapshot a deferred consumer needs
+ is written on the durable row and is absent from every outward projection of it,
+ Harness reads included — CLI Task/Watch/Run payloads and the public Harness
+ store go through the sanitizer those surfaces already had. Internal consumers
+ keep reading the durable original; no schema change, migration or backfill.
+- **Machine-key operations are Owner.** `vault key export` / `vault key import`
+ move the machine's key material and stay at the top floor.
+- **A callback keeps the identity that created it.** The resumed turn runs under
+ the original requester's snapshot, not the daemon's own. Records written before
+ this change carry no snapshot; their origin stays UNPROVEN and they are left
+ unattributed. No backfill, no inferred principal, and no hard-expiry redesign
+ of deferred requests.
+- **Show events resolve once and check before the effect.** The reserved
+ delivery row is the writer's carrier, because `_dispatch_async` overrides the
+ IPC body. `ShowSessionEventStore.append` pre-checks chat access and Agent
+ selection for a dispatching event inside the writing transaction. The public
+ `/p` write resolves its visitor exactly once, so admission, the display author
+ and the recorded authority cannot describe different people, and no resolved
+ visitor is a 403 rather than a fall through to the local default. The public
+ projection drops the email. Page-read ACLs for public and limited pages are
+ untouched and stay independent of this write path.
+- **The Chinese label for the `member` instance-access role is 「管理者」.** Owner
+ decision of 2026-09-18, replacing 「成员」 and superseding the four display-copy
+ statements frozen in `docs/plans/instance-access-role-member.md`, which are
+ marked there. This is display copy only: the stored and token value stays
+ `member`, English stays "Member", and organization / group / server membership
+ copy elsewhere is untouched.
+
+## Evidence and acceptance
+
+- Render the real authorization provider for Editor/Viewer/Member/Owner and
+ exercise the affected control through its existing dialog and API request;
+ prove Editor run works while configuration mutation remains unavailable.
+ Cover capability refresh/revocation and no eligible Project honestly.
+- Use real signed remote HTTP + CSRF, SQLite and service authorization for a
+ representative authorized Editor create/send flow and retained resource /
+ lower-role refusals. Stub external providers and host effects only after
+ authorization. A UI callback alone does not prove a complete workflow.
+- Any additional confirmed fix needs a consuming regression; target meaningful
+ boundaries rather than mirrored implementation assertions. Reuse the existing
+ permissions scenarios and assign unused stable IDs after checking the catalog.
+- Run focused tests, changed-file Ruff for Python, UI lint/build for UI changes,
+ and the existing relevant permission regressions. Every probe is hermetic;
+ never read/write credentials or live user state to make a test pass.
+- Publish an audit matrix, exact final changed scope, passed evidence and any
+ remaining live-browser/tenant acceptance gap in the PR/contract. Do not claim
+ exhaustive runtime verification from static enumeration alone.
+
+## Delivery
+
+Follow repository AGENTS and `.agents/skills/pr-delivery-loop/SKILL.md` plus
+`background-watch-hook`. Cyhhao automation owns Codex triggering; NEVER manually
+trigger it. Confirm pickup, retain exact-current-head PASS, all expected `lint`
+jobs green, zero unresolved threads across all heads and CLEAN merge state.
+Use one live combined forever/timeout=0 lane Watch plus an independent PM Watch
+with distinct persistent cursors; never reseed between pushes. Notify PM when
+PR opens with URL/head/Watch immediately so the independent gate can be armed.
+
+Count findings-bearing review heads by actual reviewed SHA and root cause.
+Repeated class on two heads, or three finding heads after a model rewrite,
+stops edits/push before PM diagnoses the whole inventory and records resumption.
+Deliver final evidence to PM before removing lane Watch; then quiesce. No merge,
+release/deploy/install/service restart is authorized by this contract.
diff --git a/docs/plans/instance-access-role-member.md b/docs/plans/instance-access-role-member.md
index c642aca0b..ced03e742 100644
--- a/docs/plans/instance-access-role-member.md
+++ b/docs/plans/instance-access-role-member.md
@@ -18,7 +18,7 @@ This file is the **cross-lane contract**. Field names, role identifiers, and cap
## Decisions (frozen)
1. **Identifier**: the instance access role string is `member` (not `admin`, not `instance_member`).
-2. **UI / docs copy**: display the instance access role as **"Member"** (ZH: **「成员」**). The owner accepts its overlap with the cloud organization-role copy. The stored/token value remains `member`.
+2. **UI / docs copy**: display the instance access role as **"Member"** (ZH: **「管理者」**). The stored/token value remains `member`. *(Superseded 2026-09-18: the Chinese label was 「成员」 when this was frozen, accepting the overlap with the cloud organization-role copy. The owner replaced it with 「管理者」 to end that overlap; English is unchanged. Authoritative record: `docs/plans/editor-permission-parity.md`.)*
3. **Ownership transfer stays owner-only.** `member` cannot transfer instance ownership (Personal or Organization). Treat it as member management.
4. **Applies to both Personal and Organization Avibe.**
5. **Personal vs Organization ACL**: `member` is treated as editor-or-higher for the Personal resource-use bypass (`has_role("editor")` already covers it once rank is `viewer < editor < member < owner`). Organization ACL evaluation is unchanged for *use*: `member` is still subject to Agent / Project resource ACL like any non-owner Organization principal. Agent *management* is owner-equivalent at the resource layer, including resources owned by another subject, resources bound to another organization policy, and resources with no policy row.
@@ -145,7 +145,7 @@ Project ACL (`access_role` `editor|viewer`) is **out of scope**.
- `ui/src/lib/sessionInfo.ts`: `instance_role: 'owner' | 'member' | 'editor' | 'viewer'`; `InstanceCapabilities.can_manage_access_members: boolean`.
- Permissions page (`ui/src/features/permissions/`): role picker offers `member`; controls that mutate members / roles require `can_manage_access_members` (not `can_manage_instance`).
-- i18n: EN `"Member"` / ZH `"成员"` for the instance-access role. The deliberate overlap with organization-member copy is accepted.
+- i18n: EN `"Member"` / ZH `"管理者"` for the instance-access role (ZH superseded 2026-09-18; it read `"成员"` here, accepting the overlap with organization-member copy).
- AppShell / Workbench / settings: continue to key off capabilities. After projection includes `can_manage_instance=true` for member, those surfaces light up automatically. Member-management widgets must additionally require `can_manage_access_members`.
## Tests (property, not enumerations)
@@ -160,7 +160,7 @@ Seed one principal of every existing role **plus** `member`, run the change, ass
6. Pre-`member` allowlist / token / snapshot fixtures still load.
7. Personal `member` gets the Personal editor resource-use bypass (Agent + projects); Personal `viewer` does not.
8. Organization `member` remains subject to Agent / Project ACL for *use*; Agent management is owner-equivalent at the resource layer.
-9. Instance-access role copy is `"Member"` / `"成员"` without changing the stored value.
+9. Instance-access role copy is `"Member"` / `"管理者"` (ZH superseded 2026-09-18, was `"成员"`) without changing the stored value.
## Lane split
@@ -220,7 +220,7 @@ The initial implementation left three authorization layers inconsistent. The cap
1. `member` gets owner-equivalent Agent management at the resource layer. This includes built-in Agents, Agents owned by other subjects, missing-policy rows, and Organization policies bound to another organization. Editor behavior is unchanged. Resource *use* remains ACL-governed, and `_policy_allows_owner_control` remains limited to the Instance Owner or resource owner.
2. Instance-wide default Agent selection is open to `member`: the HTTP route is member-tier and `set_default_agent_name` uses `can_manage_agents`. Bulk Agent onboarding and credential/host-lifecycle routes remain Owner-only.
-3. The instance-access role display copy is `"Member"` in English and `"成员"` in Chinese. The stored/token value remains `member`; overlap with organization-member copy is deliberate.
+3. The instance-access role display copy is `"Member"` in English and `"管理者"` in Chinese (ZH superseded 2026-09-18, was `"成员"` with deliberate organization-member overlap). The stored/token value remains `member`.
### Pre-catalog fallback audit
diff --git a/storage/background.py b/storage/background.py
index 3a19b00be..7555f1f11 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -9127,10 +9127,10 @@ class SQLiteBackgroundTaskStore:
# strength of never having looked.
row["process_alive"] = None if runtime is None else bool(runtime.get("running"))
if not self._include_private_metadata:
- from storage.message_deliveries import metadata_without_delegated_owner
+ from storage.message_deliveries import public_message_metadata
for row in rows:
- row["metadata"] = metadata_without_delegated_owner(row.get("metadata"))
+ row["metadata"] = public_message_metadata(row.get("metadata") or {})
return rows
@staticmethod
@@ -9300,10 +9300,10 @@ class SQLiteBackgroundTaskStore:
for field, blank in blanks[site.source]().items():
run.setdefault(field, blank)
if not self._include_private_metadata:
- from storage.message_deliveries import metadata_without_delegated_owner
+ from storage.message_deliveries import public_message_metadata
for run in runs:
- run["metadata"] = metadata_without_delegated_owner(run.get("metadata"))
+ run["metadata"] = public_message_metadata(run.get("metadata") or {})
return runs
@staticmethod
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 4babdbc72..1bf6629a4 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -34,6 +34,7 @@ from vibe.authorization import (
INSTANCE_ROLES,
AuthorizationContext,
context_from_session_payload,
+ default_authorization_context,
instance_owner_context,
)
@@ -224,7 +225,9 @@ def resolve_resource_access_context(
if has_request_context():
return context
- return instance_owner_context()
+ # Outside a request, the invocation that is running owns the answer; with no
+ # invocation either, this is a standalone local entry point and stays Owner.
+ return default_authorization_context()
def ensure_harness_definition_write(
@@ -261,6 +264,10 @@ def metadata_allows_harness_runtime(
return bool(context is not None and context.has_role("editor"))
+def _normalized_snapshot_email(email: str | None) -> str | None:
+ return (email or "").strip().lower() or None
+
+
def metadata_with_resource_user_context(
metadata: Mapping[str, Any] | None,
user_context: ResourceUserContext | Mapping[str, Any] | None = None,
@@ -275,6 +282,12 @@ def metadata_with_resource_user_context(
result[RESOURCE_USER_CONTEXT_METADATA_KEY] = {
"sub": context.subject,
+ # Project ACLs bind ``email`` / ``email_domain`` principals, so a
+ # snapshot without it denies deferred work the live request allowed.
+ # Normalized the way ``_matching_binding_role`` compares it. Written
+ # from the signed context after the key is dropped above, so caller
+ # metadata cannot supply one.
+ "email": _normalized_snapshot_email(context.email),
"vibe_organization_id": context.organization_id,
"vibe_organization_member_id": context.organization_member_id,
"vibe_organization_role": context.organization_role,
@@ -1410,8 +1423,19 @@ def _policy_allows(
# runtime access intentionally ignores them for validated remote sessions.
# Direct non-remote contexts still use the stored policy so service-level
# ACL checks cannot be bypassed by a caller-supplied role alone.
+ #
+ # A Personal Instance is the other half of that same rule: it has no
+ # Organization to be an active member of, so it qualifies on the SIGNED
+ # instance kind (as ``agent`` above already does) rather than on missing
+ # Organization claims. Management is unaffected — metadata writes still go
+ # through ``_require_secret_resource_management`` and protected secrets still
+ # require their approval and proof.
if resource_kind in {"skill", "vault_secret"}:
- if context.is_remote and context.is_active_organization_member and context.has_role("editor"):
+ if (
+ context.is_remote
+ and context.has_role("editor")
+ and (context.is_active_organization_member or context.is_personal_instance)
+ ):
return True
if not context.can_use_resource(resource_kind):
return False
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 1ce38c747..571154cc2 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -75,6 +75,53 @@ def _publish_definition_reclaim_hint() -> None:
logger.debug("session definition reclaim wake failed", exc_info=True)
+def require_reservation_access(
+ conn: Connection,
+ authorization_context: Any,
+ *,
+ scope_id: str | None,
+ agent_id: str | None,
+ agent_name: str | None,
+) -> None:
+ """Hold a new reservation to the caller's Project-placement and Agent authority.
+
+ A caller that HAS a context — an explicit argument, or the authority the
+ running invocation was entered under — is held to the same rule the Workbench
+ applies when it creates or re-places a session, so a Project the caller cannot
+ chat in, a standalone Session below runtime management, and an Agent they may
+ not select are all refused before the row exists.
+
+ With neither, this is the historical local entry point: the controller's own
+ IM flows and a local CLI invocation keep Owner semantics and reserve exactly
+ as before. Reading the invocation authority here is what makes the several
+ reservation paths — a direct run, a fork, a Task/Watch/Hook definition —
+ carry the caller without each one threading a parameter.
+ """
+
+ if authorization_context is None:
+ from vibe.authorization import current_invocation_authority
+
+ authorization_context = current_invocation_authority()
+ if authorization_context is None:
+ return
+
+ from core.vibe_agents import ensure_agent_selection_access
+ from storage import project_access_service
+ from storage.workbench_sessions_service import ProjectAccessDeniedError
+ from vibe.authorization import require_instance_role
+
+ context = require_instance_role(authorization_context, "editor")
+ if not context.can_manage_instance:
+ project_id = project_access_service.project_id_from_scope_id(scope_id)
+ if project_id is None or not project_access_service.can_chat_project(
+ conn, context, project_id
+ ):
+ raise ProjectAccessDeniedError
+ ensure_agent_selection_access(
+ conn, agent_id=agent_id, agent_name=agent_name, user_context=context
+ )
+
+
def _require_enabled_agent_identity(
conn: Connection,
*,
@@ -407,6 +454,7 @@ class SQLiteSessionsService:
metadata: dict[str, Any] | None = None,
require_enabled_agent: bool = False,
expected_reference_agent_id: str | None = None,
+ authorization_context: Any = None,
) -> str | None:
now = _utc_now_iso()
backend = str(agent_backend or "default")
@@ -430,6 +478,13 @@ class SQLiteSessionsService:
scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
if scope_id is None:
return None
+ require_reservation_access(
+ conn,
+ authorization_context,
+ scope_id=scope_id,
+ agent_id=agent_id,
+ agent_name=agent_name,
+ )
return create_agent_session_row(
conn,
scope_id=scope_id,
@@ -448,6 +503,37 @@ class SQLiteSessionsService:
require_workdir=False,
)
+ def require_placement_access(
+ self,
+ *,
+ scope_key: str,
+ agent_id: str | None = None,
+ agent_name: str | None = None,
+ authorization_context: Any = None,
+ ) -> None:
+ """Admit a placement whose Sessions are reserved later, under the same rule.
+
+ A stored definition that creates one Session per run describes a placement
+ without performing it, so nothing reaches ``reserve_agent_session`` while the
+ caller is still here. Asking the identical question now means the definition
+ is refused where someone is waiting for the answer, instead of every future
+ fire being refused where nobody is.
+
+ Nothing is committed: resolving a legacy key can materialise its scope, and a
+ check has no business leaving that behind.
+ """
+
+ now = _utc_now_iso()
+ with self.engine.connect() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key or ""), now=now)
+ require_reservation_access(
+ conn,
+ authorization_context,
+ scope_id=scope_id,
+ agent_id=agent_id,
+ agent_name=agent_name,
+ )
+
def reserve_standalone_agent_session(
self,
*,
@@ -462,6 +548,7 @@ class SQLiteSessionsService:
metadata: dict[str, Any] | None = None,
require_enabled_agent: bool = False,
expected_reference_agent_id: str | None = None,
+ authorization_context: Any = None,
) -> str:
"""Reserve a session with no Scope and its own lazy Show workspace."""
now = _utc_now_iso()
@@ -483,6 +570,15 @@ class SQLiteSessionsService:
agent_id = identity["id"]
agent_name = identity["name"]
backend = identity["backend"]
+ # Ahead of the id claim and the mkdir below: a refused reservation
+ # must leave no session row and no workspace directory behind.
+ require_reservation_access(
+ conn,
+ authorization_context,
+ scope_id=None,
+ agent_id=agent_id,
+ agent_name=agent_name,
+ )
session_id = new_session_id(conn)
resolved_workdir = normalize_workdir(workdir)
if resolved_workdir is None:
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 2b5a324df..63c51200e 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -818,6 +818,92 @@ def _request_audience_from_requester(requester: Any) -> str:
return REQUEST_AUDIENCE_UI
+def _requester_with_authorization(requester: Any, context: Any) -> Any:
+ """Record the authority a request was actually made under, in the requester JSON.
+
+ A request outlives the call that created it: it is decided later, and its
+ auto-resume turn is dispatched later still. The rest of the requester object
+ is descriptive provenance the caller supplies, so a deferred consumer cannot
+ trust it — the snapshot written here comes from the resolved context, and any
+ copy the caller sent is dropped first by the same helper Runs and Harness
+ definitions use.
+
+ A local caller keeps the historical shape exactly: no key, and a request that
+ had no requester at all still stores NULL.
+ """
+
+ from storage import resource_access_service
+
+ if not isinstance(requester, dict):
+ if not bool(getattr(context, "is_remote", False)):
+ return requester
+ requester = {}
+ return resource_access_service.metadata_with_resource_user_context(requester, context)
+
+
+def _require_request_session_authority(conn: Connection, session_id: Any, context: Any) -> None:
+ """Hold a request to the session its approval would resume.
+
+ A request is decided later, and deciding it resumes the session the
+ requester named — so that session is an effect of the request, not a label
+ on it. A requester who could not start a turn there has to be refused before
+ the pending row exists; otherwise the refusal arrives only after a person
+ has been asked to approve, and the request sits in their queue meanwhile.
+
+ Only a session that exists is an effect. A request naming no session, or an
+ id no session answers to, resumes nothing and stays as useful as it has
+ always been — refusing those would be a new rule about request shape rather
+ than about authority. Roles that manage the runtime already reach every
+ session, so they are not asked.
+ """
+
+ identity = str(session_id or "").strip()
+ if not identity or bool(getattr(context, "can_manage_instance", False)):
+ return
+ known = conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.id == identity).limit(1)
+ ).first()
+ if known is None:
+ return
+
+ from core.vibe_agents import VibeAgentAccessError
+ from storage.workbench_sessions_service import require_session_turn_authority
+ from vibe.authorization import InstanceAuthorizationError
+
+ try:
+ require_session_turn_authority(conn, identity, authorization_context=context)
+ except (LookupError, InstanceAuthorizationError, VibeAgentAccessError) as exc:
+ raise VaultSecretAccessError("Vault request session access is not permitted.") from exc
+
+
+def request_authorization_snapshot(row: dict[str, Any]) -> dict[str, Any] | None:
+ """The trusted authority stored with a request, for its deferred consumers."""
+
+ from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY
+
+ requester, _ = _request_json_payloads(row)
+ if not isinstance(requester, dict):
+ return None
+ snapshot = requester.get(RESOURCE_USER_CONTEXT_METADATA_KEY)
+ return dict(snapshot) if isinstance(snapshot, dict) else None
+
+
+def _public_requester_payload(requester: Any) -> Any:
+ """Strip the internal authority snapshot from an outward requester view."""
+
+ from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY
+
+ if not isinstance(requester, dict):
+ return requester
+ if RESOURCE_USER_CONTEXT_METADATA_KEY not in requester:
+ return requester
+ # A copy: the row's own payload stays intact for the internal consumers that
+ # read it after this projection has been handed out.
+ public = dict(requester)
+ public.pop(RESOURCE_USER_CONTEXT_METADATA_KEY, None)
+ return public
+
+
def _card_hydration_policy(audience: str | None) -> CardHydrationPolicy:
normalized = _normalize_request_audience(audience)
return CardHydrationPolicy(
@@ -1051,7 +1137,7 @@ def _request_row_payload(
"id": row["id"],
"request_type": row["request_type"],
"secret_name": row.get("secret_name"),
- "requester": requester if isinstance(requester, dict) else requester,
+ "requester": _public_requester_payload(requester),
"delivery": delivery if isinstance(delivery, dict) else delivery,
"status": row.get("status"),
"message_id": row.get("message_id"),
@@ -1765,13 +1851,19 @@ def audit(
if snapshot is not None and (delivery is None or isinstance(delivery, dict)):
stored_delivery = dict(delivery or {})
stored_delivery[_AUDIT_ACCESS_SNAPSHOT_KEY] = snapshot
+ # The audit trail is a non-secret summary, and callers now hand it the same
+ # requester payload the request row stores. That payload may carry the
+ # internal authorization snapshot, which belongs to the request's deferred
+ # consumers rather than to a log surface, so it is dropped here once for
+ # every event instead of at each call site.
+ stored_requester = _public_requester_payload(requester)
conn.execute(
vault_audit.insert().values(
id=_id("vau"),
ts=_now(),
event=event,
secret_name=secret_name,
- requester=json.dumps(requester) if requester is not None else None,
+ requester=json.dumps(stored_requester) if stored_requester is not None else None,
delivery=json.dumps(stored_delivery) if stored_delivery is not None else None,
request_id=request_id,
grant_id=grant_id,
@@ -2991,6 +3083,7 @@ def create_provision_request(
spec: dict[str, Any] | None = None,
requester: Any = None,
message_id: str | None = None,
+ user_context: Any = None,
) -> dict[str, Any]:
"""Record an agent's request for a missing secret (dynamic ask).
@@ -3011,8 +3104,10 @@ def create_provision_request(
raise SecretNameCaseConflictError(name, pending_name)
status = "fulfilled" if already else "pending"
normalized_spec = normalize_provision_spec(spec)
+ context = resolve_resource_access_context(user_context)
requester_payload = dict(requester) if isinstance(requester, dict) else requester
session_id = requester_payload.get("session_id") if isinstance(requester_payload, dict) else None
+ _require_request_session_authority(conn, session_id, context)
resolved_message_id = message_id
if isinstance(requester_payload, dict) and not resolved_message_id:
_, derived_turn_id = _active_session_turn_anchor(conn, session_id)
@@ -3024,13 +3119,14 @@ def create_provision_request(
delivery_payload["reason"] = reason
if normalized_spec:
delivery_payload["spec"] = normalized_spec
+ stored_requester = _requester_with_authorization(requester_payload, context)
try:
conn.execute(
vault_requests.insert().values(
id=request_id,
request_type="provision",
secret_name=name,
- requester=json.dumps(requester_payload) if requester_payload is not None else None,
+ requester=json.dumps(stored_requester) if stored_requester is not None else None,
delivery=json.dumps(delivery_payload),
status=status,
message_id=resolved_message_id,
@@ -3043,7 +3139,7 @@ def create_provision_request(
if pending_name is not None and pending_name != name:
raise SecretNameCaseConflictError(name, pending_name) from exc
raise VaultServiceError("failed to create provision request") from exc
- audit(conn, "provision_requested", secret_name=name, requester=requester_payload, request_id=request_id)
+ audit(conn, "provision_requested", secret_name=name, requester=stored_requester, request_id=request_id)
return {
"id": request_id,
"secret_name": name,
@@ -3378,6 +3474,11 @@ def create_access_request(
payload_audience = audience or _request_audience_from_requester(requester)
delivery_payload = dict(delivery or {})
requester_payload = requester if isinstance(requester, dict) else {}
+ _require_request_session_authority(
+ conn,
+ requester_payload.get("session_id") or delivery_payload.get("session_id"),
+ context,
+ )
default_selector = {"env": [name]} if name else None
selector = _source_selector_payload(source_selector or default_selector)
rows = _request_member_rows_for_selector(conn, source_selector=selector, user_context=context)
@@ -3412,12 +3513,13 @@ def create_access_request(
delivery_payload["card"] = card
delivery_payload["source_selector"] = selector
delivery_payload["purpose"] = purpose
+ stored_requester = _requester_with_authorization(requester, context)
conn.execute(
vault_requests.insert().values(
id=request_id,
request_type="access",
secret_name=str(rows[0]["name"]) if len(rows) == 1 else None,
- requester=json.dumps(requester) if requester is not None else None,
+ requester=json.dumps(stored_requester) if stored_requester is not None else None,
delivery=json.dumps(delivery_payload),
status="pending",
message_id=message_id,
@@ -3425,7 +3527,14 @@ def create_access_request(
expires_at=expires_at or _request_expiry(),
)
)
- audit(conn, "access_requested", secret_name=name, requester=requester, delivery=delivery_payload, request_id=request_id)
+ audit(
+ conn,
+ "access_requested",
+ secret_name=name,
+ requester=stored_requester,
+ delivery=delivery_payload,
+ request_id=request_id,
+ )
row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()
return _request_row_payload(dict(row), conn=conn, audience=payload_audience)
@@ -3456,6 +3565,11 @@ def create_sign_request(
request_id = _id("vrq")
delivery_payload = dict(delivery or {})
requester_payload = requester if isinstance(requester, dict) else {}
+ _require_request_session_authority(
+ conn,
+ requester_payload.get("session_id") or delivery_payload.get("session_id"),
+ context,
+ )
card = approval_card(
conn,
name,
@@ -3470,12 +3584,13 @@ def create_sign_request(
delivery_payload.update({"digest": digest, "scheme": scheme, "card": card})
if signing_context is not None:
delivery_payload["signing_context"] = signing_context
+ stored_requester = _requester_with_authorization(requester, context)
conn.execute(
vault_requests.insert().values(
id=request_id,
request_type="sign",
secret_name=name,
- requester=json.dumps(requester) if requester is not None else None,
+ requester=json.dumps(stored_requester) if stored_requester is not None else None,
delivery=json.dumps(delivery_payload),
status="pending",
message_id=message_id,
@@ -3483,7 +3598,14 @@ def create_sign_request(
expires_at=expires_at or _request_expiry(),
)
)
- audit(conn, "sign_requested", secret_name=name, requester=requester, delivery=delivery_payload, request_id=request_id)
+ audit(
+ conn,
+ "sign_requested",
+ secret_name=name,
+ requester=stored_requester,
+ delivery=delivery_payload,
+ request_id=request_id,
+ )
row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()
return _request_row_payload(dict(row), conn=conn, audience=payload_audience)
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 2b48a3aaf..b544fe471 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -291,25 +291,101 @@ def get_session(
)
-def get_active_session(conn: Connection, session_id: str) -> dict[str, Any]:
+def get_active_session(
+ conn: Connection,
+ session_id: str,
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
"""Like :func:`get_session` but treats archived sessions as absent.
Archived sessions are soft-deleted: the agent-facing ``vibe session`` surface
must never surface them, so ``get`` / ``update`` raise ``LookupError`` for an
archived id exactly as they would for a missing one.
+
+ The caller's authority is carried through rather than re-derived, so the
+ Project read check in :func:`get_session` answers for whoever asked.
"""
- payload = get_session(conn, session_id)
+ payload = get_session(conn, session_id, authorization_context=authorization_context)
if payload.get("status") == "archived":
raise LookupError(f"Session not found: {session_id}")
return payload
+def require_session_chat_access(
+ conn: Connection,
+ session_id: str,
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Active session payload for a caller allowed to drive its conversation.
+
+ Reading a session is Viewer work; changing what it will say next is chat
+ work, so inspecting, dropping or promoting queued messages resolves the same
+ effective role ``update_session`` requires — the decision the HTTP layer
+ already makes for ``/api/sessions/<id>/...`` in its Project middleware.
+
+ A refusal is ``LookupError``, matching every other guard here: someone who
+ cannot chat in the Project should not learn the session exists.
+ """
+
+ context = require_instance_role(authorization_context, "editor")
+ payload = get_active_session(conn, session_id, authorization_context=context)
+ if not _has_runtime_management_access(context):
+ role = project_access_service.get_effective_session_role(conn, context, session_id)
+ if not project_access_service.role_allows(role, "editor"):
+ raise LookupError(f"Session not found: {session_id}")
+ return payload
+
+
+def require_session_turn_authority(
+ conn: Connection,
+ session_id: str,
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Active session payload for a caller allowed to start a turn in it.
+
+ Queueing deferred work needs chat access to the session *and* use access to
+ the Agent that will run it — the same pair ``sessions_service`` requires
+ before it reserves a new session, asked here about one that already exists.
+
+ A turn is rebuilt later from its reservation, under the authority recorded
+ when the row was written, so both answers have to be known before the row
+ exists. Deciding only at execution time would let a refused caller occupy
+ the session, and leaves the refusal somewhere nobody is waiting for it.
+
+ The Agent half asks about the session's *selected* Agent, the same resource
+ check reserving a session applies to the Agent it is given. A row that
+ selects none — an IM or pre-catalog session carrying only a backend — is
+ left to the entitlement rule the turn already applies at execution, so this
+ refuses what a caller may not reach without newly refusing what they could.
+
+ A refusal keeps this module's ``LookupError`` for chat access and
+ ``VibeAgentAccessError`` for the Agent, so callers keep their own vocabulary.
+ """
+
+ context = require_instance_role(authorization_context, "editor")
+ payload = require_session_chat_access(conn, session_id, authorization_context=context)
+
+ from core.vibe_agents import ensure_agent_selection_access
+
+ ensure_agent_selection_access(
+ conn,
+ agent_name=payload.get("agent_name"),
+ agent_id=payload.get("agent_id"),
+ user_context=context,
+ )
+ return payload
+
+
def list_sessions_page(
conn: Connection,
*,
platform: Optional[str] = None,
page: int = 1,
limit: int = 10,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
) -> PageResult[dict[str, Any]]:
"""Active sessions, most-recently-active first, offset-paginated for the CLI.
@@ -321,12 +397,26 @@ def list_sessions_page(
``visibility == 'foreground'`` is positive for the reason ``list_sessions`` spells
out: runtime-owned ``system`` sessions are excluded without naming them.
+
+ Project access narrows the QUERY, exactly as it does in ``list_sessions``.
+ Filtering the rows afterwards would be a different answer: the page is built
+ from ``limit + 1`` rows, so inaccessible sessions would consume the page and
+ the caller would page through gaps whose size tells them what is there.
"""
+ context = require_instance_role(authorization_context, "viewer")
request = PageRequest(page=max(int(page), 1), limit=max(int(limit), 1))
query = select(agent_sessions).where(
agent_sessions.c.status == "active",
agent_sessions.c.visibility == "foreground",
)
+ if not _has_runtime_management_access(context):
+ accessible_scope_ids = {
+ project_access_service.project_scope_id(project_id)
+ for project_id in project_access_service.accessible_project_ids(conn, context)
+ }
+ if not accessible_scope_ids:
+ return page_result_from_limit_plus_one([], request)
+ query = query.where(agent_sessions.c.scope_id.in_(accessible_scope_ids))
if platform:
platform_filter = agent_sessions.c.scope_id.like(f"{platform}::%")
if platform == "avibe":
@@ -345,7 +435,10 @@ def list_sessions_page(
.offset(request.offset)
)
rows = [dict(row) for row in conn.execute(query).mappings().all()]
- payloads = [_row_to_payload(row) for row in rows]
+ payloads = [
+ _row_to_payload(row, include_local_details=_include_local_details(context))
+ for row in rows
+ ]
return page_result_from_limit_plus_one(payloads, request)
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index e766d95e0..de9243edd 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -222,12 +222,24 @@ capabilities:
scenario_tests:
- tests/scenarios/permissions/test_permissions_scenarios.py
- tests/scenarios/permissions/test_member_instance_operations.py
+ - tests/scenarios/permissions/test_editor_reservation_and_fork.py
+ - tests/scenarios/permissions/test_cli_invocation_authority.py
+ - tests/scenarios/permissions/test_deferred_authority_provenance.py
+ - tests/scenarios/permissions/test_effective_target_preflight.py
harness:
- tests/scenario_harness/permissions.py
unit_or_contract_tests:
- tests/test_permissions.py
+ - tests/test_resource_access_service.py
+ - tests/test_ui_show_pages.py
- ui/src/features/permissions/PermissionsPage.test.tsx
- ui/src/components/workbench/ShowPageSharingSettings.test.tsx
+ - ui/src/components/workbench/AgentsPage.test.tsx
+ - ui/src/components/workbench/ShowPageShareControl.test.tsx
+ - ui/src/components/workbench/HarnessPage.banner.test.tsx
+ - ui/src/components/workbench/HarnessPage.events.test.tsx
+ - ui/src/components/workbench/VaultsPage.test.tsx
+ - ui/src/lib/useVaultRequestRefresh.test.ts
- id: message_delivery
name: scheduled result delivery
status: active
diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yaml
index ed4c2b00a..eff1d6803 100644
--- a/tests/scenarios/permissions/catalog.yaml
+++ b/tests/scenarios/permissions/catalog.yaml
@@ -7,6 +7,11 @@ capability:
- tests/test_permissions.py
- tests/test_member_management_parity.py
- tests/scenarios/permissions/test_member_instance_operations.py
+ - tests/scenarios/permissions/test_editor_reservation_and_fork.py
+ - tests/scenarios/permissions/test_cli_invocation_authority.py
+ - tests/scenarios/permissions/test_deferred_authority_provenance.py
+ - tests/scenarios/permissions/test_effective_target_preflight.py
+ - tests/test_ui_show_pages.py
status_legend:
covered: scenario coverage exists
partial: unit or contract coverage exists but the closed loop is incomplete
@@ -160,7 +165,13 @@ scenarios:
test: tests/scenarios/permissions/test_member_instance_operations.py::test_permissions_016_real_sse_management_and_session_delivery
given: The real broker has Member Owner Editor and Viewer subscribers
when: Publisher-shaped management and session events are emitted
- then: Member and Owner receive operations while lower roles stay scoped and unknown events remain Owner-only
+ then: Member and Owner receive operations, an Editor receives instance-scoped invalidations as bare signals their pages refetch from, lower roles stay scoped and unknown events remain Owner-only
+ related_tests:
+ - ui/src/lib/useVaultRequestRefresh.test.ts::stops polling once the bridge is healthy and refetches on the event alone
+ - ui/src/components/workbench/VaultsPage.test.tsx::refetches pending requests from the signal alone
+ - ui/src/components/workbench/HarnessPage.events.test.tsx::reloads the Harness view from the signal alone
+ - ui/src/components/workbench/HarnessPage.definitionsStream.test.tsx::refetches the Harness view from the named signal alone
+ - ui/src/components/workbench/HarnessPage.definitionsStream.test.tsx::keeps waking on runs.updated and stops when the page unmounts
- id: PERMISSIONS-017
name: Broader notification visibility preserves subject identity
@@ -191,3 +202,96 @@ scenarios:
given: Test-owned Skill statistics and raw observations exist
when: All roles query statistics and managers use the diagnostics CLI
then: Member and Owner can inspect and clear statistics while lower-role denial read-only SQL and raw-secret denial remain
+
+ - id: PERMISSIONS-020
+ name: Running an Agent is independent of managing its definition
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: ui/src/components/workbench/AgentsPage.test.tsx::lets an editor launch a session from an Agent whose definition stays locked
+ given: The Agents page renders under the capabilities the server projects for each role
+ when: Each role opens the launcher and follows a Run through to the API call
+ then: An Editor launches a session while its definition stays locked and a Viewer is offered no Run at all
+
+ - id: PERMISSIONS-021
+ name: Dock pinning follows page use rather than instance management
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: ui/src/components/workbench/ShowPageShareControl.test.tsx::pins a page for a user who may use it but may not manage the instance
+ given: A Show page is rendered for roles above and below the editor-tier pins route
+ when: Each role pins and unpins the page from the share control
+ then: An Editor pins and unpins with a persisted readback while roles that cannot reach the route are offered no control
+
+ - id: PERMISSIONS-022
+ name: Shared background-work banner preference stays member-tier on an editor surface
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: ui/src/components/workbench/HarnessPage.banner.test.tsx::leaves the switch read-only for an editor and attempts no write
+ given: The Harness page is an editor surface whose banner switch writes one shared instance preference
+ when: An Editor toggles the switch and a Member is downgraded mid-render
+ then: The switch reads as read-only below member and attempts no write instead of flipping and reverting
+
+ - id: PERMISSIONS-023
+ name: Reservation and fork preflight follow the caller's own authority
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/scenarios/permissions/test_editor_reservation_and_fork.py
+ given: An Editor holds Project and Agent selection authority for only part of the instance
+ when: The caller reserves a Session and forks an existing one with inherited or overridden Agents
+ then: Source and destination are checked independently, unauthorized callers never reserve, and local callers keep Owner semantics
+
+ - id: PERMISSIONS-024
+ name: A deferred Vault request keeps the authority that created it
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/scenarios/permissions/test_deferred_authority_provenance.py
+ given: A remote caller opens a Vault access request that is decided long after the call returns
+ when: The request is read back, audited, and auto-resumed by the scheduled callback
+ then: The row keeps the trusted snapshot for the resumed turn, every outward view and the audit trail hide it, and a local caller's row is byte-for-byte unchanged
+
+ - id: PERMISSIONS-025
+ name: Project email ACLs compare the principal the request actually carried
+ status: covered
+ kind: authorization
+ layer: unit
+ test: tests/test_resource_access_service.py::test_deferred_snapshot_carries_the_signed_email_and_ignores_supplied_metadata
+ given: A deferred record carries a signed resource-user snapshot and a caller supplies its own
+ when: The binding role is matched against Project email ACLs
+ then: The normalized signed email decides the match, caller-supplied metadata is dropped, and an unstamped principal stays absent rather than inferred
+
+ - id: PERMISSIONS-026
+ name: An ordinary CLI command runs under the caller that invoked it
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/scenarios/permissions/test_cli_invocation_authority.py
+ given: The host injects a remote caller's signed snapshot into the Agent subprocess environment
+ when: The real CLI entry point dispatches commands across every parser leaf and caller role
+ then: Every command declares a role floor, below-floor commands are refused before any effect, unusable provenance fails closed as anonymous remote, and the authority lasts exactly one invocation
+
+ - id: PERMISSIONS-027
+ name: A dispatching Show event records the author who started the turn
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/scenarios/permissions/test_deferred_authority_provenance.py
+ given: A Show annotation or intent starts an Agent turn through a delivery reservation rather than the message that woke the daemon
+ when: Remote and local authors append dispatching and non-dispatching events, including the CLI reservation replayed by the live UI post and a share visitor posting to /p
+ then: The reserved delivery carries the author's snapshot for the resumed turn, the event echo and transcript stream hide it, the CLI caller's authority survives the replay, and the share route resolves its visitor once so admission, display author and recorded authority cannot describe different people
+ related_tests:
+ - tests/test_ui_show_pages.py::test_public_show_page_dispatch_records_the_visitor_that_admitted_it
+ - tests/test_ui_show_pages.py::test_public_show_page_dispatch_fails_closed_without_a_resolved_visitor
+
+ - id: PERMISSIONS-028
+ name: Deferred work admits its effective target before the row is written
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/scenarios/permissions/test_effective_target_preflight.py
+ given: A signed caller names a Session it may not drive, by Session id, by legacy scope key whose thread exists or has never been opened, or by defaulting to its own, or repoints a stored definition at a destination it may or may not use
+ when: A Run, a callback route, and a Task or Watch definition are produced or retargeted through the real CLI
+ then: Each producer refuses before writing, leaving Run definition Session and Scope counts and the stored row unchanged, a target whose Session does not exist yet is admitted as the placement it is rather than skipped for having no row, an edit that replaces its Session is judged on the destination it chooses rather than the one it abandons, work that becomes per-run admits the Agent each future fire will select with its follow-the-Session marker read from the edit's final policy, and permitted Editors Member Owner and local callers keep the reach they had while saved automation control keeps the definition's own authority
diff --git a/tests/scenarios/permissions/observations.yaml b/tests/scenarios/permissions/observations.yaml
index 39d1122da..d350da9b2 100644
--- a/tests/scenarios/permissions/observations.yaml
+++ b/tests/scenarios/permissions/observations.yaml
@@ -59,6 +59,39 @@ observations:
- retain Editor and Viewer restrictions and true signed principal identity
- preserve shared inbox read markers and existing Show publication policy
- validate actual signed HTTP storage and SSE consumers rather than capability predicates alone
+ - give every instance-scoped signal the role gate admits an actual page consumer, so a bare refetch frame wakes the view it was admitted for instead of being delivered to nobody
- include released Member deferred snapshots in binding migration without reopening unattributed or later work
- serialize migration provenance reads row decisions and marker seal with the existing SQLite writer reservation
+
+ - id: OBS-PERMISSIONS-005
+ source: approved_owner_contract
+ related_scenarios:
+ - PERMISSIONS-020
+ - PERMISSIONS-021
+ - PERMISSIONS-022
+ - PERMISSIONS-023
+ - PERMISSIONS-024
+ - PERMISSIONS-026
+ - PERMISSIONS-027
+ - PERMISSIONS-028
+ summary: Ordinary product operations need the initiating user, not the machine that happens to run them.
+ previous_assumption: Role enforcement at the HTTP surface was enough because everything below it acted for the local Owner.
+ observed_behavior: A remote caller's Agent turn reached CLI commands, raw operations and deferred rows that all resolved to standalone Owner, so a role refused in the browser succeeded through the same person's Agent.
+ required_updates:
+ - resolve one invocation-scoped authority at the CLI entry point and pass it to guards that already exist
+ - classify every parser leaf with a role floor whose default is deny, and refuse before any effect is written
+ - treat an unusable remote provenance as anonymous remote rather than falling back to local Owner
+ - record the initiating authority on deferred rows at the producer and read it back at the consumer
+ - admit the effective target before producing deferred work, so a refusal costs no Run definition or Session row rather than surfacing at dispatch where nobody is waiting
+ - let the edit decide which target is effective, so a definition that replaces its Session is admitted for the destination it chooses and never for the one it abandons
+ - read the follow-the-Session marker from the edit's final session policy, and resolve and admit the Agent every future fire will select before work becomes per-run
+ - treat a target whose Session has not been opened yet as the placement it is rather than as no target, without giving a blank or unusable target any authorization meaning
+ - keep saved automation control on the authority the definition already carries instead of restamping it to whoever pressed run or pause
+ - keep every outward projection of a deferred row free of the recorded authority
+ - keep a genuinely local invocation byte-for-byte unchanged so standalone administration is unaffected
+ - separate use from management on the surfaces that mix them, without turning Member-tier controls into Editor ones
+ known_by_design:
+ - historical rows written before this change carry no authority snapshot; they stay unattributed rather than being backfilled or inferred (UNPROVEN)
+ - host screenshot and prompt-template export remain host-scoped operations
+ - terminal, filesystem, shell and SQL sandboxing is a separate boundary and is out of this class
diff --git a/tests/scenarios/permissions/test_cli_invocation_authority.py b/tests/scenarios/permissions/test_cli_invocation_authority.py
new file mode 100644
index 000000000..35ac7f471
--- /dev/null
+++ b/tests/scenarios/permissions/test_cli_invocation_authority.py
@@ -0,0 +1,724 @@
+"""PERMISSIONS-026: an ordinary CLI command runs under the caller that invoked it.
+
+Avibe already injects a remote caller's signed authorization snapshot into the
+Agent subprocess environment. What was missing is the other half: every ``vibe``
+command resolved to this machine's Owner, so a remote Viewer's Agent turn could
+run management commands the same person's browser refuses.
+
+The repair is one invocation-scoped authority resolved at ``main``, plus a role
+floor for every parser leaf. These cases drive the real parser and the real
+``main`` dispatch with the caller env written exactly the way the host writes it,
+so the classification table, the env hop, the pre-effect refusal and the
+authority's lifetime are covered at the entry point a user actually types.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from core.caller_context import (
+ AVIBE_CALLER_RESOURCE_CONTEXT_ENV,
+ CALLER_CONTEXT_ENV_NAMES,
+ CallerContext,
+)
+from storage.importer import ensure_sqlite_state
+from storage.resource_access_service import (
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ metadata_with_resource_user_context,
+)
+from vibe import cli
+from vibe.authorization import (
+ AuthorizationContext,
+ current_invocation_authority,
+ default_authorization_context,
+)
+
+
+_INSTANCE_ID = "inst-cli"
+
+
+def _pair_instance(*, instance_id: str = _INSTANCE_ID, instance_kind: str = "organization") -> None:
+ """Leave this installation paired the way a completed binding transition does.
+
+ The caller env is not self-certifying. It crosses a process boundary and
+ outlives the pairing it was minted under, so it is validated against the
+ instance this machine is currently bound to — which means the fixtures have
+ to be a real pairing rather than claims alone.
+ """
+
+ from config.v2_config import V2Config
+ from storage import remote_access_authorization_service as binding
+
+ config = V2Config.default()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.instance_id = instance_id
+ cloud.instance_kind = instance_kind
+ cloud.instance_secret = "instance-secret"
+ config.save()
+
+ ensure_sqlite_state()
+ started = binding.begin_instance_binding_transition(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ )
+ assert binding.complete_instance_binding_transition(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ generation=started["generation"],
+ )
+
+
[email protected](autouse=True)
+def paired_instance():
+ """Every case below runs on a currently valid Organization pairing."""
+
+ _pair_instance()
+
+
+def _snapshot(
+ role: str,
+ *,
+ instance_kind: str = "organization",
+ instance_id: str = _INSTANCE_ID,
+) -> dict:
+ """The signed snapshot the host records for a remote caller."""
+
+ organization = instance_kind == "organization"
+ context = AuthorizationContext(
+ instance_role=role,
+ subject=f"{role}-subject",
+ email=f"{role}@example.com",
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ instance_access_source="email",
+ # A Personal instance has no Organization membership to carry.
+ organization_id="org-1" if organization else None,
+ organization_member_id="org-member" if organization else None,
+ organization_role="member" if organization else None,
+ is_remote=True,
+ )
+ return dict(metadata_with_resource_user_context({}, context)[RESOURCE_USER_CONTEXT_METADATA_KEY])
+
+
+def _caller_env(
+ role: str | None,
+ *,
+ instance_kind: str = "organization",
+ instance_id: str = _INSTANCE_ID,
+) -> dict[str, str]:
+ """The subprocess env for a caller, or an empty env for a local invocation."""
+
+ if role is None:
+ return {}
+ return CallerContext(
+ session_id="ses_cli_caller",
+ is_remote=True,
+ resource_user_context=_snapshot(role, instance_kind=instance_kind, instance_id=instance_id),
+ ).to_env()
+
+
+def _parser_paths(parser: argparse.ArgumentParser, prefix: tuple[str, ...] = ()):
+ """Every path the parser can reach, and whether it is a terminal command."""
+
+ action = next(
+ (item for item in parser._actions if isinstance(item, argparse._SubParsersAction)),
+ None,
+ )
+ if action is None:
+ yield prefix, True
+ return
+ yield prefix, False
+ for name, sub in action.choices.items():
+ yield from _parser_paths(sub, prefix + (name,))
+
+
+def invoke(monkeypatch):
+ """Run the real CLI entry point under a caller env, and report its exit code."""
+
+ def run(argv: list[str], *, caller: dict[str, str] | None = None) -> int:
+ for name in CALLER_CONTEXT_ENV_NAMES:
+ monkeypatch.delenv(name, raising=False)
+ for name, value in (caller or {}).items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(sys, "argv", ["vibe", *argv])
+ with pytest.raises(SystemExit) as exited:
+ cli.main()
+ return int(exited.value.code or 0)
+
+ return run
+
+
+def _refusal(capsys) -> dict:
+ payload = json.loads(capsys.readouterr().err.strip())
+ assert payload["ok"] is False
+ return payload
+
+
+def test_permissions_026_every_cli_command_declares_a_role_floor():
+ """PERMISSIONS-026: no command can be added without being classified."""
+ paths = list(_parser_paths(cli.build_parser()))
+ commands = {path for path, terminal in paths if terminal}
+ reachable = {path for path, _ in paths}
+
+ assert commands - set(cli._CLI_COMMAND_FLOORS) == set()
+ # And nothing is classified that the parser cannot reach, so a renamed
+ # command cannot leave a floor behind that silently guards nothing.
+ assert set(cli._CLI_COMMAND_FLOORS) - reachable == set()
+ # Only the two namespaces that are themselves runnable carry a floor
+ # without being a leaf: bare ``vibe`` and bare ``vibe remote``.
+ assert set(cli._CLI_COMMAND_FLOORS) & (reachable - commands) == {(), ("remote",)}
+
+
+ ("caller", "expected_role", "expected_remote"),
+ [
+ ("local", None, False),
+ ("editor", "editor", True),
+ ("owner", "owner", True),
+ ],
+)
+def test_permissions_026_authority_comes_from_the_caller_env(caller, expected_role, expected_remote):
+ """PERMISSIONS-026: the snapshot the host injected is the authority the CLI runs under."""
+ env = _caller_env(None if caller == "local" else caller)
+ authority = cli._cli_invocation_authority(env)
+
+ if caller == "local":
+ # A genuinely local invocation keeps standalone Owner administration.
+ assert authority is None
+ return
+ assert authority.instance_role == expected_role
+ assert authority.is_remote is expected_remote
+ assert authority.email == f"{caller}@example.com"
+
+
[email protected]("provenance", ["missing", "malformed", "not_an_object"])
+def test_permissions_026_a_declared_remote_caller_without_provenance_fails_closed(provenance):
+ """PERMISSIONS-026: unusable provenance is anonymous remote, never local Owner."""
+ env = _caller_env("editor")
+ if provenance == "missing":
+ env.pop(AVIBE_CALLER_RESOURCE_CONTEXT_ENV)
+ elif provenance == "malformed":
+ env[AVIBE_CALLER_RESOURCE_CONTEXT_ENV] = "{not json"
+ else:
+ env[AVIBE_CALLER_RESOURCE_CONTEXT_ENV] = json.dumps(["editor"])
+
+ authority = cli._cli_invocation_authority(env)
+ assert authority is not None
+ assert authority.is_remote is True
+ assert authority.instance_role is None
+ assert authority.has_role("viewer") is False
+
+
+def test_permissions_026_a_personal_pairing_admits_a_snapshot_without_organization_claims():
+ """PERMISSIONS-026: validation is about the pairing, not about carrying Org claims."""
+ _pair_instance(instance_kind="personal")
+
+ authority = cli._cli_invocation_authority(_caller_env("editor", instance_kind="personal"))
+
+ assert authority.instance_role == "editor"
+ assert authority.is_remote is True
+ assert authority.instance_kind == "personal"
+ assert authority.organization_id is None
+
+
[email protected]("mismatch", ["instance_id", "instance_kind", "reconciling"])
+def test_permissions_026_a_snapshot_from_another_pairing_is_anonymous_remote(mismatch):
+ """PERMISSIONS-026: claims that no longer describe this installation carry no role.
+
+ The environment outlives the pairing it was minted under. A snapshot naming
+ another instance, another kind, or a binding that is mid-reconciliation is
+ unusable here — and unusable means anonymous remote, not local Owner.
+ """
+ from storage import remote_access_authorization_service as binding
+
+ if mismatch == "instance_id":
+ env = _caller_env("owner", instance_id="inst-somewhere-else")
+ elif mismatch == "instance_kind":
+ env = _caller_env("owner", instance_kind="personal")
+ else:
+ # The snapshot still names the configured pairing; what it cannot name
+ # is a binding that is mid-reconciliation and has published nothing.
+ env = _caller_env("owner")
+ binding.begin_instance_binding_transition(
+ instance_id="inst-cli-reconciling",
+ instance_kind="organization",
+ )
+
+ authority = cli._cli_invocation_authority(env)
+
+ assert authority.is_remote is True
+ assert authority.instance_role is None
+ assert authority.has_role("viewer") is False
+
+
+def test_permissions_026_a_stale_snapshot_is_refused_and_writes_nothing(invoke, capsys):
+ """PERMISSIONS-026: the same env admits before the pairing moves and is refused after.
+
+ Real ``main``, real signed snapshot, real binding transition. The refusal has
+ to land in front of the effect, so the record the admitted call wrote is the
+ same record the refused call leaves behind.
+ """
+ from core.vibe_agents import VibeAgentStore
+
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agent(backend="codex")
+ finally:
+ store.close()
+
+ caller = _caller_env("member")
+ assert invoke(["agent", "update", "codex", "--description", "admitted"], caller=caller) == 0
+ store = VibeAgentStore()
+ try:
+ assert store.require("codex").description == "admitted"
+ finally:
+ store.close()
+
+ # This installation re-pairs to another instance. The Agent process still
+ # carries the environment the previous pairing minted.
+ _pair_instance(instance_id="inst-cli-repaired")
+
+ assert invoke(["agent", "update", "codex", "--description", "stale"], caller=caller) == 1
+ payload = _refusal(capsys)
+ assert payload["code"] == "instance_access_forbidden"
+ assert payload["details"]["minimum_role"] == cli._CLI_COMMAND_FLOORS[("agent", "update")]
+
+ store = VibeAgentStore()
+ try:
+ assert store.require("codex").description == "admitted"
+ finally:
+ store.close()
+
+
+def test_permissions_026_a_stale_snapshot_cannot_reach_a_command_that_forwards_it(invoke, capsys):
+ """PERMISSIONS-026: the commands that hand their own env to a service sit behind admission.
+
+ Every producer that passes the caller snapshot on as an explicit context
+ reads it from the same environment the invocation authority was validated
+ from, and each declares an Editor floor. So the explicit precedence above is
+ only ever fed claims this installation already accepted: once the pairing
+ moves, the invocation is anonymous remote and the command never runs. The
+ property is asserted where it matters -- nothing reserved, nothing queued --
+ rather than inferred from the two mechanisms separately.
+ """
+
+ from sqlalchemy import func, select
+
+ from core.vibe_agents import VibeAgentStore
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_runs, agent_sessions
+
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agent(backend="codex")
+ finally:
+ store.close()
+
+ caller = _caller_env("editor")
+ _pair_instance(instance_id="inst-cli-repaired")
+
+ engine = create_sqlite_engine()
+
+ def counts() -> tuple[int, int]:
+ with engine.connect() as conn:
+ return (
+ conn.execute(select(func.count()).select_from(agent_sessions)).scalar_one(),
+ conn.execute(select(func.count()).select_from(agent_runs)).scalar_one(),
+ )
+
+ try:
+ before = counts()
+ argv = ["agent", "run", "--create-session", "--message", "hi", "--async", "--no-callback"]
+ assert invoke(argv, caller=caller) == 1
+ payload = _refusal(capsys)
+ assert payload["code"] == "instance_access_forbidden"
+ assert counts() == before
+ finally:
+ engine.dispose()
+
+
+_CREATE_AGENT = ["agent", "create", "probe", "--backend", "codex"]
+
+
+ ("role", "argv", "path", "admitted"),
+ [
+ ("viewer", ["session", "list"], ("session", "list"), True),
+ ("viewer", ["agent", "list"], ("agent", "list"), False),
+ ("editor", ["agent", "list"], ("agent", "list"), True),
+ ("editor", _CREATE_AGENT, ("agent", "create"), False),
+ ("editor", ["data", "retention"], ("data", "retention"), False),
+ ("member", _CREATE_AGENT, ("agent", "create"), True),
+ ("member", ["vault", "key", "export"], ("vault", "key", "export"), False),
+ ("owner", ["vault", "key", "export"], ("vault", "key", "export"), True),
+ ],
+)
+def test_permissions_026_each_namespace_admits_at_its_own_floor(
+ monkeypatch, invoke, capsys, role, argv, path, admitted
+):
+ """PERMISSIONS-026: the floor decides admission, and a refusal never dispatches."""
+ dispatched: list[tuple[str, ...]] = []
+ monkeypatch.setattr(
+ cli,
+ "_dispatch_parsed_command",
+ lambda parser, args: dispatched.append(path) or sys.exit(0),
+ )
+
+ exit_code = invoke(argv, caller=_caller_env(role))
+
+ if admitted:
+ assert exit_code == 0
+ assert dispatched == [path]
+ return
+ assert exit_code == 1
+ assert dispatched == []
+ payload = _refusal(capsys)
+ assert payload["code"] == "instance_access_forbidden"
+ assert payload["details"]["command"] == " ".join(("vibe", *path))
+ assert payload["details"]["minimum_role"] == cli._CLI_COMMAND_FLOORS[path]
+
+
+def test_permissions_026_a_refused_command_leaves_the_record_it_would_have_written(invoke, capsys):
+ """PERMISSIONS-026: the refusal happens before the product effect, not after it."""
+ from core.vibe_agents import VibeAgentStore
+
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agent(backend="codex")
+ before = store.require("codex").description
+ finally:
+ store.close()
+
+ assert invoke(["agent", "update", "codex", "--description", "rewritten"], caller=_caller_env("editor")) == 1
+ assert _refusal(capsys)["code"] == "instance_access_forbidden"
+
+ store = VibeAgentStore()
+ try:
+ assert store.require("codex").description == before
+ finally:
+ store.close()
+
+ assert invoke(["agent", "update", "codex", "--description", "rewritten"], caller=_caller_env("member")) == 0
+ store = VibeAgentStore()
+ try:
+ assert store.require("codex").description == "rewritten"
+ finally:
+ store.close()
+
+
[email protected]("caller", ["editor", "member", "local"])
+def test_permissions_026_an_existing_resource_guard_now_sees_the_invocation_caller(caller):
+ """PERMISSIONS-026: namespace admission is not the answer; the resource's own policy still is.
+
+ ``vibe vault edit`` is Editor work as a namespace, exactly as it is over HTTP,
+ and the secret's own management policy decides the rest. That policy always
+ existed — it simply never saw a CLI caller, because an omitted context
+ resolved to Owner. Now it sees the invocation.
+ """
+ from storage import vault_service as vs
+ from storage.db import create_sqlite_engine
+ from storage.models import metadata as sqlite_metadata
+ from storage.vault_crypto import Sealed
+ from vibe.authorization import invocation_authority
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ sqlite_metadata.create_all(engine)
+ with engine.begin() as conn:
+ vs.create_secret(conn, name="EDIT_KEY", sealed=Sealed(ciphertext="ct", nonce="n", wrap_meta="wm"))
+
+ authority = None if caller == "local" else cli._cli_invocation_authority(_caller_env(caller))
+ with invocation_authority(authority):
+ with engine.begin() as conn:
+ if caller == "editor":
+ with pytest.raises(vs.VaultSecretAccessError):
+ vs.update_secret_metadata(conn, "EDIT_KEY", description="rewritten")
+ else:
+ assert vs.update_secret_metadata(conn, "EDIT_KEY", description="rewritten")
+
+ with engine.connect() as conn:
+ stored = vs.get_secret_meta(conn, "EDIT_KEY")
+ assert (stored.get("description") == "rewritten") is (caller != "editor")
+
+
+def test_permissions_026_an_explicit_context_still_outranks_the_invocation():
+ """PERMISSIONS-026: validating the env changed who the ambient caller is, not the precedence.
+
+ A stale snapshot leaves an anonymous remote invocation, which cannot manage
+ a secret. A context the caller passes explicitly is still the one that
+ answers, exactly as it did before the env was validated.
+ """
+ from storage import vault_service as vs
+ from storage.db import create_sqlite_engine
+ from storage.models import metadata as sqlite_metadata
+ from storage.vault_crypto import Sealed
+ from vibe.authorization import instance_owner_context, invocation_authority
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ sqlite_metadata.create_all(engine)
+ with engine.begin() as conn:
+ vs.create_secret(conn, name="EXPLICIT_KEY", sealed=Sealed(ciphertext="ct", nonce="n", wrap_meta="wm"))
+
+ stale = cli._cli_invocation_authority(_caller_env("owner", instance_id="inst-somewhere-else"))
+ assert stale.instance_role is None
+
+ with invocation_authority(stale):
+ with engine.begin() as conn:
+ with pytest.raises(vs.VaultSecretAccessError):
+ vs.update_secret_metadata(conn, "EXPLICIT_KEY", description="ambient")
+ with engine.begin() as conn:
+ assert vs.update_secret_metadata(
+ conn,
+ "EXPLICIT_KEY",
+ description="explicit",
+ user_context=instance_owner_context(),
+ )
+
+ with engine.connect() as conn:
+ assert vs.get_secret_meta(conn, "EXPLICIT_KEY").get("description") == "explicit"
+
+
+def test_permissions_026_authority_lasts_exactly_one_invocation(monkeypatch, invoke):
+ """PERMISSIONS-026: the authority is entered and reset around each dispatch, including on exit."""
+ seen: list[object] = []
+ monkeypatch.setattr(
+ cli,
+ "_dispatch_parsed_command",
+ lambda parser, args: seen.append(current_invocation_authority()) or sys.exit(0),
+ )
+
+ assert current_invocation_authority() is None
+ assert invoke(["agent", "list"], caller=_caller_env("editor")) == 0
+ assert seen[-1].instance_role == "editor"
+ # ``sys.exit`` unwinds through the context manager, so nothing survives it.
+ assert current_invocation_authority() is None
+ assert default_authorization_context().instance_role == "owner"
+
+ # A later local invocation in the same process is local, not the previous caller.
+ assert invoke(["agent", "list"], caller=None) == 0
+ assert seen[-1] is None
+ assert current_invocation_authority() is None
+
+
+def test_permissions_026_a_below_floor_command_is_refused_while_a_remote_owner_is_not(monkeypatch, invoke):
+ """PERMISSIONS-026: a remote caller is refused by role, not by being remote."""
+ dispatched: list[str] = []
+ monkeypatch.setattr(
+ cli,
+ "_dispatch_parsed_command",
+ lambda parser, args: dispatched.append(args.command) or sys.exit(0),
+ )
+
+ assert invoke(["restart"], caller=_caller_env("editor")) == 1
+ assert dispatched == []
+ assert invoke(["restart"], caller=_caller_env("member")) == 0
+ assert dispatched == ["restart"]
+
+
+def test_permissions_026_internal_activation_entry_points_stay_owner_work(monkeypatch, invoke, capsys):
+ """PERMISSIONS-026: the supervisor and installer argv are not an alternate door."""
+ activated: list[str] = []
+ monkeypatch.setattr(
+ cli,
+ "_dispatch_restart_supervisor",
+ lambda argv: activated.append("restart-supervisor") or 0,
+ )
+
+ assert invoke(["__restart-supervisor"], caller=_caller_env("member")) == 1
+ assert activated == []
+ assert "__restart-supervisor: Instance role 'owner' is required" in capsys.readouterr().err
+
+ assert invoke(["__restart-supervisor"], caller=None) == 0
+ assert activated == ["restart-supervisor"]
+
+
+def test_permissions_026_guided_remote_setup_refuses_before_a_pairing_key_is_solicited(
+ monkeypatch, invoke, capsys
+):
+ """PERMISSIONS-026: ``vibe remote`` reads status at the management floor but pairs only as Owner."""
+ from vibe import remote_access
+
+ solicited: list[str] = []
+ paired: list[str] = []
+ monkeypatch.setattr(remote_access, "status", lambda: {"ok": True, "paired": False})
+ monkeypatch.setattr(remote_access, "pair", lambda *a, **k: paired.append("pair") or {"ok": True})
+ monkeypatch.setattr(cli, "_wait_for_pairing_key_ready", lambda: solicited.append("key") or False)
+
+ assert invoke(["remote"], caller=_caller_env("member")) == 1
+ payload = _refusal(capsys)
+ assert payload["code"] == "instance_access_forbidden"
+ assert payload["details"]["command"] == "vibe remote pair"
+ # Nothing was solicited and nothing was spent: the refusal is in front of both.
+ assert solicited == []
+ assert paired == []
+
+ # The status branch a Member is admitted for still answers.
+ monkeypatch.setattr(remote_access, "status", lambda: {"ok": True, "paired": True, "device_name": "avibe"})
+ assert invoke(["remote"], caller=_caller_env("member")) == 0
+ assert paired == []
+
+
+def caller_environment(monkeypatch):
+ """Put a real caller env on this process, the way an Agent subprocess has it."""
+
+ def apply(role: str) -> dict[str, str]:
+ env = _caller_env(role)
+ for name in CALLER_CONTEXT_ENV_NAMES:
+ monkeypatch.delenv(name, raising=False)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ return env
+
+ return apply
+
+
+def test_permissions_026_an_admitted_restart_hands_the_supervisor_no_caller(
+ monkeypatch, invoke, tmp_path, caller_environment
+):
+ """PERMISSIONS-026: the caller's authority ends at the process Avibe owns.
+
+ A Member may restart, and the restart is admitted on that. What a Member may
+ not do is enter ``__restart-supervisor``, which is Owner work — so the
+ detached job cannot be handed the Member's provenance, or it would fail its
+ own entry and leave the restart stuck at ``scheduled``. The job is created
+ after the parent operation has already been admitted, so dropping the caller
+ there costs the parent nothing.
+ """
+ from vibe import restart_supervisor
+
+ caller = caller_environment("member")
+ assert cli._cli_invocation_authority().instance_role == "member"
+
+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)
+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)
+ spawned: dict = {}
+
+ def fake_popen(command, **kwargs):
+ spawned["command"] = command
+ spawned["env"] = kwargs["env"]
+
+ class Proc:
+ pid = 45678
+
+ return Proc()
+
+ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)
+
+ result = restart_supervisor.schedule_restart(delay_seconds=0, vibe_path="/bin/vibe", trigger="agent")
+
+ assert result["state"] == "scheduled"
+ assert "__restart-supervisor" in spawned["command"]
+ # ``None`` would have inherited this process silently, caller and all.
+ assert spawned["env"] is not None
+ assert set(spawned["env"]) & CALLER_CONTEXT_ENV_NAMES == set()
+ assert spawned["env"]["PATH"] == os.environ["PATH"]
+ # The parent kept its own authority; only the child's environment lost it.
+ assert cli._cli_invocation_authority().instance_role == "member"
+ assert os.environ[AVIBE_CALLER_RESOURCE_CONTEXT_ENV] == caller[AVIBE_CALLER_RESOURCE_CONTEXT_ENV]
+
+ # The real child entry point, over the environment it was actually given.
+ activated: list[str] = []
+ monkeypatch.setattr(cli, "_dispatch_restart_supervisor", lambda argv: activated.append("ran") or 0)
+ assert invoke(["__restart-supervisor"], caller=spawned["env"]) == 0
+ assert activated == ["ran"]
+
+ # And with the caller still attached it is refused, so the strip is what
+ # admits the child rather than a floor that stopped guarding the door.
+ assert invoke(["__restart-supervisor"], caller=caller) == 1
+ assert activated == ["ran"]
+
+
+def test_permissions_026_a_deferred_activation_runs_as_the_installation(
+ monkeypatch, tmp_path, caller_environment
+):
+ """PERMISSIONS-026: the deferred activation spawn is the same boundary as the restart.
+
+ It is the Windows path: activation happens after this process releases the
+ launcher, so it is Avibe's own work by construction. The interpreter
+ isolation this spawn already needs is unchanged — only the caller hop ends.
+ """
+ from vibe import upgrade
+
+ caller_environment("member")
+ monkeypatch.setenv("PYTHONPATH", str(tmp_path / "checkout"))
+ candidate = tmp_path / "generation" / "python"
+ candidate.parent.mkdir(parents=True, exist_ok=True)
+ candidate.touch()
+ monkeypatch.setattr(upgrade, "_candidate_python", lambda launcher: candidate)
+ spawned: dict = {}
+
+ def fake_popen(command, **kwargs):
+ spawned["command"] = command
+ spawned["env"] = kwargs["env"]
+
+ class Proc:
+ pid = 99001
+
+ return Proc()
+
+ monkeypatch.setattr(upgrade.subprocess, "Popen", fake_popen)
+
+ upgrade.defer_upgrade_activation(
+ SimpleNamespace(
+ launcher=tmp_path / "stable" / "vibe",
+ candidate_launcher=tmp_path / "generation" / "vibe",
+ source_generation=None,
+ ),
+ parent_pid=os.getpid(),
+ )
+
+ assert "__activate-upgrade" in spawned["command"]
+ assert set(spawned["env"]) & CALLER_CONTEXT_ENV_NAMES == set()
+ # The isolation this spawn already had is still what it was.
+ assert "PYTHONPATH" not in spawned["env"]
+ assert "PYTHONHOME" not in spawned["env"]
+ assert spawned["env"]["PATH"] == os.environ["PATH"]
+
+
+def test_permissions_026_a_runtime_owned_process_starts_without_the_caller(
+ monkeypatch, tmp_path, caller_environment
+):
+ """PERMISSIONS-026: the service and UI processes Avibe starts are its own.
+
+ A real child reports the environment it actually received, so this covers
+ the ``env=None`` case too: the spawn materializes the environment instead of
+ letting the child inherit this process — caller included.
+ """
+ from vibe import runtime
+
+ monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)
+ caller_environment("editor")
+ assert os.environ[AVIBE_CALLER_RESOURCE_CONTEXT_ENV]
+
+ probe = "import json, os; print(json.dumps(sorted(k for k in os.environ if k.startswith('AVIBE_'))))"
+ process = runtime.spawn_service_background_process(
+ [sys.executable, "-c", probe],
+ "service_stdout.log",
+ "service_stderr.log",
+ )
+ assert process.wait(timeout=30) == 0
+
+ stdout_path = tmp_path / "service_stdout.log"
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline and not stdout_path.exists():
+ time.sleep(0.05)
+ inherited = set(json.loads(stdout_path.read_text(encoding="utf-8").strip()))
+
+ assert inherited & CALLER_CONTEXT_ENV_NAMES == set()
+ # Only the caller set was removed: the rest of the environment is intact.
+ assert "AVIBE_HOME" in inherited
diff --git a/tests/scenarios/permissions/test_deferred_authority_provenance.py b/tests/scenarios/permissions/test_deferred_authority_provenance.py
new file mode 100644
index 000000000..828cd5a4c
--- /dev/null
+++ b/tests/scenarios/permissions/test_deferred_authority_provenance.py
@@ -0,0 +1,827 @@
+"""PERMISSIONS-024/027: deferred work keeps the authority it was authorized under.
+
+A Vault request and a dispatching Show event are both decided long after the call
+that created them, and both resume an Agent turn from a row rather than from the
+message that woke the daemon. So the authority has to be recorded by the producer,
+at the moment it is still known, and read back by the consumer.
+
+Three properties are checked together, because any one alone is a bug:
+
+* the producer refuses a target the caller could not start a turn in, before the
+ row that would carry the work exists,
+* the row it does write keeps the trusted snapshot for its deferred consumer, and
+* every outward projection of that row — request payloads, the audit trail, the
+ event echo and the transcript stream — hides it.
+
+The first and second are checked against the same consumer the controller
+actually runs: a reserved Delivery is carried to
+``SessionTurnManager._remote_delivery_execution_denial``, the seam that decides
+whether a rebuilt turn may execute. Admission and execution have to agree while
+access is unchanged, and execution alone has to refuse once it is revoked.
+
+A local caller keeps the historical shape byte for byte: no snapshot is written
+and nothing is stripped.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import time
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import func, select
+
+from core.show_session_events import ShowSessionEventError, ShowSessionEventStore
+from storage import message_deliveries
+from storage import vault_service as vs
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions, metadata as sqlite_metadata, vault_audit, vault_requests
+from storage.models import message_deliveries as message_deliveries_table
+from storage.models import show_session_events as show_session_events_table
+from storage.resource_access_service import (
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ metadata_with_resource_user_context,
+)
+from storage.settings_service import upsert_scope
+from storage.vault_crypto import Sealed
+from vibe import cli
+from vibe.authorization import AuthorizationContext, invocation_authority
+
+ORG_EDITOR_EMAIL = "[email protected]"
+# The instance id the paired test configuration binds to. A stored snapshot is
+# only honoured while it still belongs to this installation, so a context that
+# will be read back through the execution guard has to carry it.
+PAIRED_INSTANCE_ID = "inst_123"
+# A context with no issued-at claim gets an expiry counted from the moment the
+# snapshot is written, so the row and a freshly recomputed expectation disagree
+# whenever a second ticks between them -- the assertion below compares two
+# timestamps taken at different times, not two authorities. Stamping one issued-at
+# for the whole module makes both sides derive the same expiry while keeping the
+# context current, so what is compared is the identity it was meant to be about.
+CLAIMS_ISSUED_AT = int(time.time())
+
+
+def _remote(role: str = "editor", *, instance_kind: str = "personal") -> AuthorizationContext:
+ return AuthorizationContext(
+ instance_role=role,
+ subject=f"{role}-subject",
+ email=f"{role}@example.com",
+ instance_id=PAIRED_INSTANCE_ID,
+ instance_kind=instance_kind,
+ instance_access_source="email",
+ organization_id="org-1",
+ organization_member_id="org-member",
+ organization_role="member",
+ claims_issued_at=CLAIMS_ISSUED_AT,
+ is_remote=True,
+ )
+
+
+def _expected_snapshot(context: AuthorizationContext) -> dict:
+ return dict(metadata_with_resource_user_context({}, context)[RESOURCE_USER_CONTEXT_METADATA_KEY])
+
+
+def _org_editor() -> AuthorizationContext:
+ """An Organization Editor: the one role a Project policy can actually revoke.
+
+ Personal instances hand every Editor their instance role regardless of
+ policy, so a Personal caller cannot express "reachable" and "unreachable" as
+ two different sessions.
+ """
+
+ return _remote("editor", instance_kind="organization")
+
+
+def _bind_project(conn, project_id: str, *, revision: int, emails: list[str]) -> None:
+ from storage import project_access_service
+
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": project_id,
+ "revision": revision,
+ "mode": "restricted",
+ "organization_id": "org-1",
+ "bindings": [
+ {"principal_kind": "email", "principal_value": email, "access_role": "editor"}
+ for email in emails
+ ],
+ },
+ )
+
+
+def turn_targets(tmp_path):
+ """One real Agent on two real sessions: one this Editor may drive, one they may not.
+
+ Both rows are written the way the product writes them — through
+ ``create_session``, with the Agent pinned — so the Agent half of the
+ preflight and of the execution guard is asked about a Session that has one.
+ """
+
+ from core.vibe_agents import VibeAgentStore
+ from storage import projects_service, resource_access_service
+ from storage.workbench_sessions_service import create_session
+ from tests.ui_server_test_helpers import _save_config
+
+ # A stored snapshot is re-decided against the current pairing, so the
+ # execution guard only answers at all on a paired installation whose durable
+ # binding exists — the interactive path bootstraps it, exactly like this.
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
+ ensure_sqlite_state()
+
+ from vibe import remote_access
+
+ assert remote_access.binding_is_ready(config)
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agent(backend="codex")
+ agent = store.require("codex")
+ finally:
+ store.close()
+
+ engine = create_sqlite_engine()
+ folder = tmp_path / "authority-project"
+ folder.mkdir()
+ with engine.begin() as conn:
+ # Public, so the Agent ACL admits this Editor and the Project policy is
+ # the only thing separating the two targets.
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="agent",
+ resource_id=agent.id,
+ owner_user_id="someone-else",
+ organization_id="org-1",
+ access_level="public",
+ group_ids=[],
+ )
+ project = projects_service.create_project(conn, str(folder), display_name="授权项目")
+ _bind_project(conn, project["id"], revision=1, emails=[ORG_EDITOR_EMAIL])
+ reachable = create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend=agent.backend,
+ agent_name=agent.name,
+ )
+ # No scope: a standalone session belongs to no Project, so only runtime
+ # management reaches it. This is the canonical forbidden target.
+ unreachable = create_session(
+ conn,
+ scope_id=None,
+ agent_backend=agent.backend,
+ agent_name=agent.name,
+ )
+ assert reachable["agent_id"] and unreachable["agent_id"]
+
+ return SimpleNamespace(
+ engine=engine,
+ agent=agent,
+ project=project,
+ reachable=reachable["id"],
+ unreachable=unreachable["id"],
+ )
+
+
+def _run_cli(monkeypatch, argv: list[str], context: AuthorizationContext | None) -> int:
+ """Drive the real CLI entry point under the env the host writes for a caller."""
+
+ from core.caller_context import CALLER_CONTEXT_ENV_NAMES, CallerContext
+
+ for name in CALLER_CONTEXT_ENV_NAMES:
+ monkeypatch.delenv(name, raising=False)
+ if context is not None:
+ env = CallerContext(
+ session_id="ses_cli_show",
+ is_remote=True,
+ resource_user_context=_expected_snapshot(context),
+ ).to_env()
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(sys, "argv", ["vibe", *argv])
+ with pytest.raises(SystemExit) as exited:
+ cli.main()
+ return int(exited.value.code or 0)
+
+
+# --- PERMISSIONS-024: Vault requests ---------------------------------------------------------
+
+
+def vault(tmp_path):
+ vs.GRANT_RUNTIME_CACHE.clear()
+ engine = create_sqlite_engine(tmp_path / "vault_provenance.sqlite")
+ sqlite_metadata.create_all(engine)
+ return engine
+
+
+def _sealed() -> Sealed:
+ return Sealed(ciphertext="ct", nonce="n", wrap_meta="wm")
+
+
+def _request_row(conn, request_id: str) -> dict:
+ return dict(
+ conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()
+ )
+
+
+def _audit_requesters(conn, request_id: str) -> list:
+ return [
+ json.loads(value) if value else None
+ for value in conn.execute(
+ select(vault_audit.c.requester).where(vault_audit.c.request_id == request_id)
+ ).scalars()
+ ]
+
+
[email protected]("caller", ["remote", "local"])
+def test_permissions_024_a_vault_request_records_the_authority_that_made_it(vault, caller):
+ """PERMISSIONS-024: the request row is the carrier; a local caller's row is unchanged."""
+ context = _remote() if caller == "remote" else None
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="P_KEY", sealed=_sealed(), protection="protected")
+ request = vs.create_access_request(
+ conn,
+ "P_KEY",
+ requester={"session_id": "ses_req", "source": "agent-cli"},
+ delivery={"session_id": "ses_req"},
+ user_context=context,
+ )
+ stored = json.loads(_request_row(conn, request["id"])["requester"])
+
+ if caller == "local":
+ # Byte for byte the historical shape: no key added, nothing to strip.
+ assert stored == {"session_id": "ses_req", "source": "agent-cli"}
+ assert vs.request_authorization_snapshot(_row_for(vault, request["id"])) is None
+ return
+
+ assert stored[RESOURCE_USER_CONTEXT_METADATA_KEY] == _expected_snapshot(context)
+ assert stored["session_id"] == "ses_req"
+ assert vs.request_authorization_snapshot(_row_for(vault, request["id"])) == _expected_snapshot(context)
+
+
+def _row_for(engine, request_id: str) -> dict:
+ with engine.connect() as conn:
+ return _request_row(conn, request_id)
+
+
+def test_permissions_024_a_caller_cannot_forge_the_recorded_authority(vault):
+ """PERMISSIONS-024: a requester-supplied snapshot is dropped, not trusted."""
+ context = _remote()
+ forged = {"vibe_instance_role": "owner", "sub": "attacker"}
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="F_KEY", sealed=_sealed(), protection="protected")
+ request = vs.create_access_request(
+ conn,
+ "F_KEY",
+ requester={"session_id": "ses_forge", RESOURCE_USER_CONTEXT_METADATA_KEY: forged},
+ user_context=context,
+ )
+
+ assert vs.request_authorization_snapshot(_row_for(vault, request["id"])) == _expected_snapshot(context)
+
+
+def test_permissions_024_outward_request_views_hide_the_recorded_authority(vault):
+ """PERMISSIONS-024: the snapshot is for the deferred consumer, not for any reader."""
+ context = _remote()
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="V_KEY", sealed=_sealed(), protection="protected")
+ request = vs.create_access_request(
+ conn,
+ "V_KEY",
+ requester={"session_id": "ses_view"},
+ user_context=context,
+ )
+ fetched = vs.get_request(conn, request["id"])
+ listed = vs.list_requests(conn)
+ audited = _audit_requesters(conn, request["id"])
+
+ for payload in (request, fetched, *[item for item in listed if item["id"] == request["id"]]):
+ assert payload["requester"] == {"session_id": "ses_view"}
+ # The audit trail is a non-secret summary and passes through one chokepoint,
+ # so no event of any type can persist the snapshot to a log surface.
+ assert audited
+ for entry in audited:
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in (entry or {})
+ # The row itself still holds it.
+ assert vs.request_authorization_snapshot(_row_for(vault, request["id"])) == _expected_snapshot(context)
+
+
+def test_permissions_024_auto_resume_runs_under_the_requesting_caller(monkeypatch, tmp_path):
+ """PERMISSIONS-024: the callback turn carries the original snapshot, not the daemon's own."""
+ from types import SimpleNamespace
+
+ from core import scheduled_tasks as st
+
+ ensure_sqlite_state()
+ context = _remote()
+ engine = create_sqlite_engine()
+ sqlite_metadata.create_all(engine)
+ with engine.begin() as conn:
+ vs.create_secret(conn, name="R_KEY", sealed=_sealed(), protection="protected")
+ request = vs.create_access_request(
+ conn,
+ "R_KEY",
+ requester={"session_id": "ses_resume"},
+ delivery={"session_id": "ses_resume"},
+ user_context=context,
+ )
+ option = request["card"]["grant_options"][0]
+ vs.create_grant(
+ conn,
+ member_names=option["member_snapshot"],
+ source_selector=option["source_selector"],
+ purpose=option["purpose"],
+ request_id=request["id"],
+ cache_ready=True,
+ )
+ row = _request_row(conn, request["id"])
+
+ target = SimpleNamespace(
+ session_key=SimpleNamespace(to_key=lambda: "avibe::scope::ses_resume"),
+ agent_name="codex",
+ agent_id="aid",
+ agent_backend="codex",
+ model=None,
+ reasoning_effort=None,
+ )
+ monkeypatch.setattr(st, "resolve_session_id_target", lambda session_id: target)
+ request_store = st.TaskExecutionStore(tmp_path / "task_requests")
+ service = st.ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=st.ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ assert service._process_vault_callback_sync(row) == "sent"
+ [callback] = request_store.list_pending()
+ assert callback.metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] == _expected_snapshot(context)
+ assert callback.metadata["vault_request_type"] == "access"
+
+
+def test_permissions_024_a_local_requests_auto_resume_stays_local(monkeypatch, tmp_path):
+ """PERMISSIONS-024: with no recorded authority the callback metadata is unchanged."""
+ from types import SimpleNamespace
+
+ from core import scheduled_tasks as st
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ sqlite_metadata.create_all(engine)
+ with engine.begin() as conn:
+ vs.create_secret(conn, name="L_KEY", sealed=_sealed(), protection="protected")
+ request = vs.create_access_request(
+ conn,
+ "L_KEY",
+ requester={"session_id": "ses_local"},
+ delivery={"session_id": "ses_local"},
+ )
+ option = request["card"]["grant_options"][0]
+ vs.create_grant(
+ conn,
+ member_names=option["member_snapshot"],
+ source_selector=option["source_selector"],
+ purpose=option["purpose"],
+ request_id=request["id"],
+ cache_ready=True,
+ )
+ row = _request_row(conn, request["id"])
+
+ target = SimpleNamespace(
+ session_key=SimpleNamespace(to_key=lambda: "avibe::scope::ses_local"),
+ agent_name="codex",
+ agent_id="aid",
+ agent_backend="codex",
+ model=None,
+ reasoning_effort=None,
+ )
+ monkeypatch.setattr(st, "resolve_session_id_target", lambda session_id: target)
+ request_store = st.TaskExecutionStore(tmp_path / "task_requests")
+ service = st.ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=st.ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ assert service._process_vault_callback_sync(row) == "sent"
+ [callback] = request_store.list_pending()
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in callback.metadata
+
+
[email protected]("request_kind", ["access", "provision"])
+def test_permissions_024_a_request_cannot_name_a_session_its_caller_cannot_resume(
+ monkeypatch, turn_targets, request_kind
+):
+ """PERMISSIONS-024: the session an approval would resume is an effect, checked first.
+
+ The approval card is the first thing a request composes, so failing it proves
+ the refusal lands before anything is composed, asked of a person, or stored —
+ not merely rolled back afterwards. ``create_sign_request`` reaches the same
+ seam with the same arguments; only its keypair setup differs.
+ """
+
+ def composed(*args, **kwargs):
+ pytest.fail("the request was composed before its target was checked")
+
+ monkeypatch.setattr(vs, "approval_card", composed)
+ monkeypatch.setattr(vs, "_secure_input_card", composed)
+ context = _org_editor()
+ with turn_targets.engine.begin() as conn:
+ vs.create_secret(conn, name="TARGET_KEY", sealed=_sealed(), protection="protected")
+ with turn_targets.engine.connect() as conn:
+ audit_before = conn.execute(select(func.count()).select_from(vault_audit)).scalar_one()
+
+ with pytest.raises(vs.VaultSecretAccessError):
+ with turn_targets.engine.begin() as conn:
+ if request_kind == "access":
+ vs.create_access_request(
+ conn,
+ "TARGET_KEY",
+ requester={"session_id": turn_targets.unreachable},
+ delivery={"session_id": turn_targets.unreachable},
+ user_context=context,
+ )
+ else:
+ vs.create_provision_request(
+ conn,
+ "MISSING_KEY",
+ requester={"session_id": turn_targets.unreachable},
+ user_context=context,
+ )
+
+ with turn_targets.engine.connect() as conn:
+ assert conn.execute(select(func.count()).select_from(vault_requests)).scalar_one() == 0
+ assert conn.execute(select(func.count()).select_from(vault_audit)).scalar_one() == audit_before
+
+
[email protected]("caller", ["editor", "member", "local"])
+def test_permissions_024_a_reachable_target_still_records_the_request(turn_targets, caller):
+ """PERMISSIONS-024: the check narrows nothing a caller could already reach.
+
+ The Editor is bound to the Project; runtime management reaches every session
+ without one; and a local caller is unchanged, target and shape both.
+ """
+
+ context = None if caller == "local" else _remote(caller, instance_kind="organization")
+ session_id = turn_targets.unreachable if caller != "editor" else turn_targets.reachable
+ with turn_targets.engine.begin() as conn:
+ vs.create_secret(conn, name=f"OK_KEY_{caller}", sealed=_sealed(), protection="protected")
+ request = vs.create_access_request(
+ conn,
+ f"OK_KEY_{caller}",
+ requester={"session_id": session_id},
+ delivery={"session_id": session_id},
+ user_context=context,
+ )
+ stored = json.loads(_request_row(conn, request["id"])["requester"])
+
+ assert stored["session_id"] == session_id
+ if caller == "local":
+ assert stored == {"session_id": session_id}
+ else:
+ assert stored[RESOURCE_USER_CONTEXT_METADATA_KEY] == _expected_snapshot(context)
+
+
+def test_permissions_024_a_request_that_names_no_session_is_unchanged(turn_targets):
+ """PERMISSIONS-024: a request resuming nothing keeps working; this is not a shape rule."""
+ context = _org_editor()
+ with turn_targets.engine.begin() as conn:
+ vs.create_secret(conn, name="FREE_KEY", sealed=_sealed(), protection="protected")
+ anonymous = vs.create_access_request(
+ conn, "FREE_KEY", requester={"source": "agent-cli"}, user_context=context
+ )
+ # An id no session answers to resumes nothing either, so it stays as
+ # useful as it has always been.
+ unknown = vs.create_access_request(
+ conn, "FREE_KEY", requester={"session_id": "ses_never_existed"}, user_context=context
+ )
+
+ for request in (anonymous, unknown):
+ assert vs.request_authorization_snapshot(_row_for(turn_targets.engine, request["id"])) == (
+ _expected_snapshot(context)
+ )
+
+
+# --- PERMISSIONS-027: Show events ------------------------------------------------------------
+
+
+def show_session():
+ from storage import messages_service
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_show_authority",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_show_authority",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_show_authority",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return "ses_show_authority"
+
+
+def _dispatching_payload(event_id: str = "show_evt_authority") -> dict:
+ return {
+ "id": event_id,
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "Run this for me.", "dispatch": True},
+ }
+
+
+def _stored_delivery_metadata(delivery_id: str) -> dict:
+ with create_sqlite_engine().connect() as conn:
+ row = message_deliveries.get_delivery(conn, delivery_id)
+ assert row is not None
+ return message_deliveries.delivery_payload(row)["metadata"]
+
+
[email protected]("caller", ["remote", "local"])
+def test_permissions_027_a_dispatching_show_event_records_its_author(show_session, caller):
+ """PERMISSIONS-027: the reservation carries the authority; the outward payload does not."""
+ context = _remote() if caller == "remote" else None
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ show_session,
+ _dispatching_payload(),
+ reserve_dispatch=True,
+ authorization_context=context,
+ )
+ finally:
+ store.close()
+
+ stored = _stored_delivery_metadata(event["delivery_id"])
+ if caller == "local":
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in stored
+ else:
+ assert stored[RESOURCE_USER_CONTEXT_METADATA_KEY] == _expected_snapshot(context)
+ # Every audience of the event reads the projection, not the row.
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in event["delivery"]["metadata"]
+
+
+def test_permissions_027_a_non_dispatching_event_hides_the_author_from_the_transcript(show_session):
+ """PERMISSIONS-027: the transcript message an event returns and streams is projected too."""
+ context = _remote()
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ show_session,
+ {
+ "id": "show_evt_transcript",
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "Just a note."},
+ },
+ authorization_context=context,
+ )
+ listed = store.list(show_session)
+ finally:
+ store.close()
+
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in event["message"]["metadata"]
+ for item in listed["events"]:
+ message = item.get("message")
+ if isinstance(message, dict) and isinstance(message.get("metadata"), dict):
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in message["metadata"]
+
+ from storage.models import messages
+
+ with create_sqlite_engine().connect() as conn:
+ stored = json.loads(
+ conn.execute(
+ select(messages.c.metadata_json).where(messages.c.id == event["message_id"])
+ ).scalar_one()
+ )
+ assert stored[RESOURCE_USER_CONTEXT_METADATA_KEY] == _expected_snapshot(context)
+
+
+def test_permissions_027_the_cli_reserves_a_dispatching_event_under_its_own_caller(show_session):
+ """PERMISSIONS-027: the live-UI hop cannot relabel a remote caller as this machine."""
+ context = _remote()
+ payload = _dispatching_payload("show_evt_cli")
+
+ with invocation_authority(context):
+ cli._reserve_dispatching_show_event(show_session, payload)
+
+ store = ShowSessionEventStore()
+ try:
+ # The POST that follows reaches a separate process with no caller env, so it
+ # resolves as this machine's Owner — and must replay the reservation rather
+ # than write a second, differently-authorized one.
+ replayed = store.append(show_session, payload, reserve_dispatch=True)
+ finally:
+ store.close()
+
+ assert replayed["id"] == "show_evt_cli"
+ assert replayed["delivery"], "the replay still hands the live path a delivery to dispatch"
+ stored = _stored_delivery_metadata(replayed["delivery_id"])
+ assert stored[RESOURCE_USER_CONTEXT_METADATA_KEY] == _expected_snapshot(context)
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in replayed["delivery"]["metadata"]
+
+
+def test_permissions_027_the_cli_reserves_nothing_for_an_event_that_starts_no_turn(show_session):
+ """PERMISSIONS-027: only deferred work is pre-reserved; ordinary events stay single-write."""
+ quiet = {
+ "id": "show_evt_quiet",
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "No turn, please."},
+ }
+
+ with invocation_authority(_remote()):
+ cli._reserve_dispatching_show_event(show_session, quiet)
+
+ with create_sqlite_engine().connect() as conn:
+ assert conn.execute(select(show_session_events_table.c.id)).scalars().all() == []
+
+
+# --- PERMISSIONS-027: admission, the stored row, and the execution guard ----------------------
+
+
+def _reserve_dispatch(session_id: str, event_id: str, context: AuthorizationContext | None) -> dict:
+ store = ShowSessionEventStore()
+ try:
+ return store.append(
+ session_id,
+ _dispatching_payload(event_id),
+ reserve_dispatch=True,
+ authorization_context=context,
+ )
+ finally:
+ store.close()
+
+
+def test_permissions_027_an_admitted_reservation_is_still_admitted_at_execution(turn_targets):
+ """PERMISSIONS-027: the preflight answers what the execution guard will answer.
+
+ Admission that disagreed with execution would be either an escalation or a
+ turn that queues and then quietly dies, so the same Delivery is carried from
+ the producer to the seam the controller consults before it runs.
+ """
+
+ from core.session_turns import SessionTurnManager
+
+ context = _org_editor()
+ event = _reserve_dispatch(turn_targets.reachable, "show_evt_chain", context)
+
+ with turn_targets.engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, event["delivery_id"])
+ assert message_deliveries.delivery_has_remote_resource_context(delivery)
+ assert SessionTurnManager._remote_delivery_execution_denial(conn, delivery) is None
+
+
+def test_permissions_027_revoking_access_after_the_reservation_stops_the_turn(turn_targets):
+ """PERMISSIONS-027: the recorded snapshot is re-decided, not trusted as a past approval."""
+ from core.session_turns import SessionTurnManager
+
+ event = _reserve_dispatch(turn_targets.reachable, "show_evt_revoked", _org_editor())
+
+ with turn_targets.engine.begin() as conn:
+ _bind_project(
+ conn,
+ turn_targets.project["id"],
+ revision=2,
+ emails=["[email protected]"],
+ )
+
+ with turn_targets.engine.connect() as conn:
+ delivery = message_deliveries.get_delivery(conn, event["delivery_id"])
+ assert (
+ SessionTurnManager._remote_delivery_execution_denial(conn, delivery)
+ == "remote_project_access_forbidden"
+ )
+
+
+def test_permissions_027_an_unreachable_session_is_refused_before_the_reservation(turn_targets):
+ """PERMISSIONS-027: a forbidden target costs no row, no Delivery and no queued turn.
+
+ The refusal reads as "not found", which is what chat access answers
+ everywhere else: someone who cannot reach a session should not learn from the
+ refusal that it exists.
+ """
+
+ with pytest.raises(ShowSessionEventError) as refused:
+ _reserve_dispatch(turn_targets.unreachable, "show_evt_refused", _org_editor())
+ assert refused.value.code == "session_not_found"
+
+ with turn_targets.engine.connect() as conn:
+ assert conn.execute(select(func.count()).select_from(show_session_events_table)).scalar_one() == 0
+ assert (
+ conn.execute(
+ select(func.count())
+ .select_from(message_deliveries_table)
+ .where(message_deliveries_table.c.session_id == turn_targets.unreachable)
+ ).scalar_one()
+ == 0
+ )
+
+
[email protected]("caller", ["local", "member", "owner"])
+def test_permissions_027_local_and_management_callers_keep_the_same_targets(turn_targets, caller):
+ """PERMISSIONS-027: the new refusal narrows nobody who could already reach the session."""
+ context = None if caller == "local" else _remote(caller, instance_kind="organization")
+ event = _reserve_dispatch(turn_targets.unreachable, f"show_evt_{caller}", context)
+
+ stored = _stored_delivery_metadata(event["delivery_id"])
+ assert (RESOURCE_USER_CONTEXT_METADATA_KEY in stored) is (caller != "local")
+ assert RESOURCE_USER_CONTEXT_METADATA_KEY not in event["delivery"]["metadata"]
+
+
+def test_permissions_027_the_cli_fails_the_command_when_its_reservation_is_refused(
+ monkeypatch, turn_targets
+):
+ """PERMISSIONS-027: a refused reservation ends the command instead of falling through.
+
+ Both fall-through paths resolve as this machine's Owner, so either one would
+ have turned a refusal into an escalation. Neither may run.
+ """
+
+ from vibe import ui_server
+
+ wrote: list[str] = []
+ monkeypatch.setattr(cli, "_post_show_event_to_live_ui", lambda *a, **k: wrote.append("live"))
+ monkeypatch.setattr(ui_server, "record_local_show_event", lambda *a, **k: wrote.append("local"))
+
+ exit_code = _run_cli(
+ monkeypatch,
+ [
+ "show",
+ "event",
+ "--session-id",
+ turn_targets.unreachable,
+ "--dispatch",
+ "--event-json",
+ json.dumps(_dispatching_payload("show_evt_cli_refused")),
+ "--json",
+ ],
+ _org_editor(),
+ )
+
+ assert exit_code == 1
+ assert wrote == []
+ with turn_targets.engine.connect() as conn:
+ assert conn.execute(select(func.count()).select_from(show_session_events_table)).scalar_one() == 0
+
+
+def test_permissions_027_an_offline_cli_dispatch_still_runs_as_its_caller(monkeypatch, turn_targets):
+ """PERMISSIONS-027: with no live UI the local fallback replays the reservation.
+
+ The fallback resolves no caller at all, so without the pre-reservation it
+ would write this turn as the host Owner. One Delivery exists afterwards, and
+ it belongs to the Editor who typed the command.
+ """
+
+ from vibe import ui_server
+
+ context = _org_editor()
+ monkeypatch.setattr(cli, "_post_show_event_to_live_ui", lambda *a, **k: None)
+
+ async def settled(event_payload):
+ return ui_server._ShowEventDispatchOutcome.ACCEPTED
+
+ monkeypatch.setattr(ui_server, "_run_show_event_dispatch", settled)
+
+ exit_code = _run_cli(
+ monkeypatch,
+ [
+ "show",
+ "event",
+ "--session-id",
+ turn_targets.reachable,
+ "--dispatch",
+ "--event-json",
+ json.dumps(_dispatching_payload("show_evt_cli_offline")),
+ "--json",
+ ],
+ context,
+ )
+
+ assert exit_code == 0
+ with turn_targets.engine.connect() as conn:
+ delivery_ids = conn.execute(
+ select(message_deliveries_table.c.id).where(
+ message_deliveries_table.c.session_id == turn_targets.reachable
+ )
+ ).scalars().all()
+ assert len(delivery_ids) == 1
+ assert _stored_delivery_metadata(delivery_ids[0])[RESOURCE_USER_CONTEXT_METADATA_KEY] == (
+ _expected_snapshot(context)
+ )
diff --git a/tests/scenarios/permissions/test_editor_reservation_and_fork.py b/tests/scenarios/permissions/test_editor_reservation_and_fork.py
new file mode 100644
index 000000000..eefa1a64b
--- /dev/null
+++ b/tests/scenarios/permissions/test_editor_reservation_and_fork.py
@@ -0,0 +1,436 @@
+"""PERMISSIONS-023: reservation and fork preflight follow the caller's own authority.
+
+A remote Editor's ``vibe agent run`` is deferred work: the CLI resolves that
+caller's signed snapshot and the reservation/fork writers apply it before any
+Session row, workspace directory or native-fork metadata exists. Only the
+external backend fork is out of scope here — the snapshot serializer and parser,
+scope resolution, Project ACL, Agent ACL and persistence are all real.
+
+A local caller keeps the historical Owner semantics (no context, no change), and
+Personal instances keep their signed-kind Editor bypass, so the same call that an
+Organization refuses is expected to succeed there.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import func, select
+
+from core.caller_context import CallerContext, caller_resource_user_context
+from core.services import sessions as sessions_service
+from core.services.session_fork import SessionForkError, reserve_forked_session
+from core.vibe_agents import VibeAgentAccessError, VibeAgentStore
+from config import paths
+from storage import project_access_service, projects_service, resource_access_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions, resource_access_policies
+from storage.resource_access_service import (
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ metadata_with_resource_user_context,
+)
+from storage.workbench_sessions_service import ProjectAccessDeniedError, create_session
+from tests.ui_server_test_helpers import _save_config
+from vibe.authorization import AuthorizationContext, InstanceAuthorizationError
+
+EDITOR_EMAIL = "[email protected]"
+
+
[email protected](params=["personal", "organization"])
+def reservations(request, tmp_path):
+ config = _save_config(tmp_path, paired=True, instance_kind=request.param)
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ store.ensure_builtin_default_agent(backend="codex")
+ agent = store.require("codex")
+ engine = create_sqlite_engine()
+ open_folder = tmp_path / "open"
+ closed_folder = tmp_path / "closed"
+ open_folder.mkdir()
+ closed_folder.mkdir()
+ with engine.begin() as conn:
+ open_project = projects_service.create_project(conn, str(open_folder), display_name="开放项目")
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": open_project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "organization_id": "org-1",
+ # An email principal: the deferred caller only matches it when
+ # the stored snapshot actually carries the signed email.
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": EDITOR_EMAIL,
+ "access_role": "editor",
+ }
+ ],
+ },
+ )
+ closed_project = projects_service.create_project(conn, str(closed_folder), display_name="受限项目")
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": closed_project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "organization_id": "foreign-org",
+ "bindings": [
+ {
+ "principal_kind": "organization_group",
+ "principal_value": "other-group",
+ "access_role": "viewer",
+ }
+ ],
+ },
+ )
+ sources = {
+ name: create_session(
+ conn,
+ scope_id=scope,
+ agent_backend=agent.backend,
+ agent_name=agent.name,
+ title=f"源会话 {name}",
+ )
+ for name, scope in (
+ ("open", open_project["scope_id"]),
+ ("closed", closed_project["scope_id"]),
+ ("standalone", None),
+ )
+ }
+ for session in sources.values():
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == session["id"])
+ .values(native_session_id="native-test")
+ )
+
+ def usable_agent():
+ """Give the Agent an ACL an Organization Editor can select."""
+
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="agent",
+ resource_id=agent.id,
+ owner_user_id="someone-else",
+ organization_id="org-1",
+ access_level="public",
+ group_ids=[],
+ )
+
+ def unusable_agent():
+ """Leave the Agent policy-less, which an Organization Editor cannot select."""
+
+ with engine.begin() as conn:
+ conn.execute(
+ resource_access_policies.delete().where(resource_access_policies.c.resource_id == agent.id)
+ )
+
+ def authorization(role="editor", subject="editor", drop_email=False):
+ context = AuthorizationContext(
+ instance_role=role,
+ subject=subject,
+ email=f"{subject}@example.com",
+ instance_id=config.remote_access.vibe_cloud.instance_id,
+ instance_kind=request.param,
+ instance_access_source="email",
+ organization_id="org-1",
+ organization_member_id="org-member",
+ organization_role="member",
+ is_remote=True,
+ )
+ snapshot = dict(
+ metadata_with_resource_user_context({}, context)[RESOURCE_USER_CONTEXT_METADATA_KEY]
+ )
+ if drop_email:
+ snapshot.pop("email", None)
+ # Exactly the CLI hop: the host writes the snapshot into the caller env
+ # and the command reads its own authority back out of it.
+ return caller_resource_user_context(
+ CallerContext(session_id="ses-caller", is_remote=True, resource_user_context=snapshot)
+ )
+
+ def session_count():
+ with engine.connect() as conn:
+ return conn.execute(select(func.count()).select_from(agent_sessions)).scalar_one()
+
+ def native_session_ids():
+ with engine.connect() as conn:
+ return dict(
+ conn.execute(select(agent_sessions.c.id, agent_sessions.c.native_session_id)).all()
+ )
+
+ unusable_agent()
+ yield SimpleNamespace(
+ kind=request.param,
+ agent=agent,
+ open_project=open_project,
+ closed_project=closed_project,
+ sources=sources,
+ authorization=authorization,
+ usable_agent=usable_agent,
+ unusable_agent=unusable_agent,
+ session_count=session_count,
+ native_session_ids=native_session_ids,
+ tmp_path=tmp_path,
+ )
+ store.close()
+ engine.dispose()
+
+
+def _reserve(state, *, scope_key, authorization_context, workdir=None):
+ return sessions_service.reserve_agent_session(
+ scope_key=scope_key,
+ agent_backend=state.agent.backend,
+ session_anchor=f"{scope_key}:run_test",
+ agent_id=state.agent.id,
+ agent_name=state.agent.name,
+ workdir=workdir,
+ visibility="background",
+ authorization_context=authorization_context,
+ )
+
+
+def test_permissions_023_editor_reserves_only_a_project_and_agent_it_may_use(reservations):
+ """PERMISSIONS-023: a permitted placement succeeds; a forbidden one writes nothing."""
+ state = reservations
+ state.usable_agent()
+ editor = state.authorization()
+
+ reserved = _reserve(state, scope_key=state.open_project["scope_id"], authorization_context=editor)
+ assert reserved
+ before = state.session_count()
+
+ if state.kind == "organization":
+ with pytest.raises(ProjectAccessDeniedError):
+ _reserve(state, scope_key=state.closed_project["scope_id"], authorization_context=editor)
+ else:
+ # A Personal instance has no Organization to restrict against, so its
+ # signed-kind Editor bypass is the intended answer, not a gap.
+ assert _reserve(state, scope_key=state.closed_project["scope_id"], authorization_context=editor)
+ before += 1
+ assert state.session_count() == before
+
+
+def test_permissions_023_reservation_requires_agent_selection_authority(reservations):
+ """PERMISSIONS-023: an Agent the caller cannot select is refused before the row."""
+ state = reservations
+ state.unusable_agent()
+ editor = state.authorization()
+ before = state.session_count()
+
+ if state.kind == "organization":
+ with pytest.raises(VibeAgentAccessError):
+ _reserve(state, scope_key=state.open_project["scope_id"], authorization_context=editor)
+ assert state.session_count() == before
+ else:
+ assert _reserve(state, scope_key=state.open_project["scope_id"], authorization_context=editor)
+ assert state.session_count() == before + 1
+
+
[email protected]("caller", ["viewer", "malformed", "missing_email"])
+def test_permissions_023_unauthorized_callers_never_reserve(reservations, caller):
+ """PERMISSIONS-023: below Editor, malformed remote and legacy snapshots fail closed."""
+ state = reservations
+ state.usable_agent()
+ before = state.session_count()
+ if caller == "viewer":
+ context, expected = state.authorization(role="viewer"), InstanceAuthorizationError
+ elif caller == "malformed":
+ # A remote caller with unusable provenance is anonymous remote, never local.
+ context, expected = {}, InstanceAuthorizationError
+ else:
+ # A record written before the snapshot carried the signed email cannot
+ # match an email Project binding, and no email is invented for it.
+ context, expected = state.authorization(drop_email=True), ProjectAccessDeniedError
+
+ if caller == "missing_email" and state.kind == "personal":
+ assert _reserve(state, scope_key=state.open_project["scope_id"], authorization_context=context)
+ assert state.session_count() == before + 1
+ return
+ with pytest.raises(expected):
+ _reserve(state, scope_key=state.open_project["scope_id"], authorization_context=context)
+ assert state.session_count() == before
+
+
+def test_permissions_023_standalone_reservation_keeps_runtime_management_boundary(reservations):
+ """PERMISSIONS-023: a refused standalone reservation leaves no row and no workspace."""
+ state = reservations
+ state.usable_agent()
+ workspace = state.tmp_path / "standalone-workspace"
+ before = state.session_count()
+
+ with pytest.raises(ProjectAccessDeniedError):
+ sessions_service.reserve_standalone_agent_session(
+ agent_backend=state.agent.backend,
+ session_anchor="standalone_test",
+ agent_id=state.agent.id,
+ agent_name=state.agent.name,
+ workdir=str(workspace),
+ authorization_context=state.authorization(),
+ )
+ assert state.session_count() == before
+ assert not workspace.exists()
+
+ allowed = sessions_service.reserve_standalone_agent_session(
+ agent_backend=state.agent.backend,
+ session_anchor="standalone_test",
+ agent_id=state.agent.id,
+ agent_name=state.agent.name,
+ workdir=str(workspace),
+ authorization_context=state.authorization(role="member"),
+ )
+ assert allowed
+ assert workspace.exists()
+
+
+def test_permissions_023_local_callers_keep_owner_reservation_semantics(reservations):
+ """PERMISSIONS-023: no context is still the local Owner path, unchanged."""
+ state = reservations
+ state.unusable_agent()
+ before = state.session_count()
+ assert _reserve(state, scope_key=state.closed_project["scope_id"], authorization_context=None)
+ assert sessions_service.reserve_standalone_agent_session(
+ agent_backend=state.agent.backend,
+ session_anchor="standalone_local",
+ agent_id=state.agent.id,
+ agent_name=state.agent.name,
+ workdir=str(state.tmp_path / "local-workspace"),
+ )
+ assert state.session_count() == before + 2
+
+
+def test_permissions_023_fork_of_a_permitted_source_and_agent_succeeds(reservations):
+ """PERMISSIONS-023: the permitted case still forks, and into a permitted Project."""
+ state = reservations
+ state.usable_agent()
+ editor = state.authorization()
+ # ``--fork-self`` resolves to the caller's own session id, so it reaches this
+ # same source-authority check rather than a separate path.
+ result = reserve_forked_session(
+ source_session_id=state.sources["open"]["id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=editor,
+ )
+ assert result.session_id
+ placed = reserve_forked_session(
+ source_session_id=state.sources["open"]["id"],
+ scope_id=state.open_project["scope_id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=editor,
+ )
+ assert placed.session_id != result.session_id
+
+
+def test_permissions_023_fork_inherited_agent_needs_selection_authority(reservations):
+ """PERMISSIONS-023: without an override the fork still runs as the source's Agent."""
+ state = reservations
+ state.unusable_agent()
+ before, natives = state.session_count(), state.native_session_ids()
+
+ if state.kind == "organization":
+ with pytest.raises(SessionForkError) as denied:
+ reserve_forked_session(
+ source_session_id=state.sources["open"]["id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=state.authorization(),
+ )
+ assert denied.value.code == "session_fork_agent_forbidden"
+ assert state.session_count() == before
+ assert state.native_session_ids() == natives
+ else:
+ assert reserve_forked_session(
+ source_session_id=state.sources["open"]["id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=state.authorization(),
+ ).session_id
+
+
+def test_permissions_023_fork_override_agent_needs_selection_authority(reservations):
+ """PERMISSIONS-023: an override Agent is checked the same way, not instead."""
+ state = reservations
+ if state.kind != "organization":
+ pytest.skip("a Personal instance grants Editors Agent use by signed instance kind")
+ state.unusable_agent()
+ before = state.session_count()
+ with pytest.raises(SessionForkError) as denied:
+ reserve_forked_session(
+ source_session_id=state.sources["open"]["id"],
+ agent_name=state.agent.name,
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=state.authorization(),
+ )
+ assert denied.value.code == "session_fork_agent_forbidden"
+ assert state.session_count() == before
+
+
+def test_permissions_023_fork_checks_source_and_destination_independently(reservations):
+ """PERMISSIONS-023: a permitted destination cannot rescue a forbidden source."""
+ state = reservations
+ if state.kind != "organization":
+ pytest.skip("a Personal instance Editor reaches every Project by signed instance kind")
+ state.usable_agent()
+ editor = state.authorization()
+ before, natives = state.session_count(), state.native_session_ids()
+
+ with pytest.raises(SessionForkError) as unreachable_source:
+ reserve_forked_session(
+ source_session_id=state.sources["closed"]["id"],
+ scope_id=state.open_project["scope_id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=editor,
+ )
+ assert "source_not_found" in str(unreachable_source.value)
+
+ with pytest.raises(SessionForkError) as unreachable_destination:
+ reserve_forked_session(
+ source_session_id=state.sources["open"]["id"],
+ scope_id=state.closed_project["scope_id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=editor,
+ )
+ assert "destination_not_permitted" in str(unreachable_destination.value)
+
+ with pytest.raises(SessionForkError):
+ reserve_forked_session(
+ source_session_id=state.sources["standalone"]["id"],
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=editor,
+ )
+ assert state.session_count() == before
+ assert state.native_session_ids() == natives
+
+
[email protected]("source", ["missing", "archived"])
+def test_permissions_023_fork_preserves_existing_source_answers(reservations, source):
+ """PERMISSIONS-023: real resource checks keep their existing meaning."""
+ state = reservations
+ state.usable_agent()
+ engine = create_sqlite_engine()
+ source_session_id = "missing-session"
+ if source == "archived":
+ source_session_id = state.sources["open"]["id"]
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == source_session_id)
+ .values(status="archived")
+ )
+ engine.dispose()
+ before = state.session_count()
+ for context in (state.authorization(), None):
+ with pytest.raises(SessionForkError) as denied:
+ reserve_forked_session(
+ source_session_id=source_session_id,
+ db_path=paths.get_sqlite_state_path(),
+ authorization_context=context,
+ )
+ if context is None:
+ # The local Owner path reaches the real resource checks, so their
+ # existing wording is what a caller still gets.
+ assert source_session_id in str(denied.value)
+ assert state.session_count() == before
diff --git a/tests/scenarios/permissions/test_effective_target_preflight.py b/tests/scenarios/permissions/test_effective_target_preflight.py
new file mode 100644
index 000000000..6697a8f73
--- /dev/null
+++ b/tests/scenarios/permissions/test_effective_target_preflight.py
@@ -0,0 +1,1019 @@
+"""PERMISSIONS-028: deferred work admits its effective target before it is written.
+
+A Run row, a callback route and a stored Task/Watch definition are all replayed
+later under the authority recorded when the row was written. Passing the command's
+role floor only says the caller may create work of that kind; it does not say they
+may put it in *this* Session. Without that second question the CLI wrote the row
+first and discovered the refusal at dispatch, where nobody is waiting for it, and a
+caller who cannot chat in a Project — or cannot use the Agent that Session runs on
+— could occupy the target anyway.
+
+These cases drive the real ``main`` dispatch with the caller env the host writes,
+against a real pairing, real Projects, real Agent ACLs and the real stores. A
+refusal has to leave the counts and the stored row exactly as they were; being
+refused later at execution is not the property under test.
+
+Saved automation control is deliberately outside this gate: running, pausing or
+resuming a stored definition steers work that already carries its own authority
+and must not restamp itself to whoever asked.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from dataclasses import asdict
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import func, select
+
+from config import paths
+from config.v2_config import V2Config
+from core.caller_context import CALLER_CONTEXT_ENV_NAMES, CallerContext
+from core.scheduled_tasks import BINDING_FOLLOWS_SESSION_METADATA_KEY, ScheduledTaskStore
+from core.vibe_agents import VibeAgentStore
+from core.watches import ManagedWatchStore
+from storage import project_access_service, projects_service, resource_access_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_runs, agent_sessions, resource_access_policies, scopes
+from storage.sessions_service import SQLiteSessionsService
+from storage.workbench_sessions_service import create_session
+from vibe import cli
+
+from tests.scenarios.permissions.test_cli_invocation_authority import (
+ _INSTANCE_ID,
+ _pair_instance,
+ _snapshot,
+)
+
+EDITOR_EMAIL = "[email protected]"
+IM_SCOPE_KEY = "slack::channel::C123"
+IM_ANCHOR = "slack_C123"
+#: A well-formed legacy key with no Scope and no Session behind it yet. Each case
+#: suffixes it so one case's placement never becomes the next one's existing row.
+FRESH_SCOPE_KEY = "slack::channel::C_NEW"
+
+
[email protected](params=["personal", "organization"])
+def targets(request, tmp_path):
+ """One instance holding every kind of target a deferred command can name."""
+
+ kind = request.param
+ _pair_instance(instance_kind=kind)
+ ensure_sqlite_state()
+
+ # Legacy scope keys are an IM shape, and a task/watch target is refused on an
+ # unenabled platform before any authorization runs. Enable the transport the
+ # keys below name so those cases reach the gate under test; no credential is
+ # configured and nothing connects.
+ config = V2Config.load()
+ if "slack" not in config.platforms.enabled:
+ config.platforms.enabled.append("slack")
+ config.save()
+
+ store = VibeAgentStore()
+ store.ensure_builtin_default_agent(backend="codex")
+ agent = store.require("codex")
+ engine = create_sqlite_engine()
+
+ open_folder = tmp_path / "open"
+ closed_folder = tmp_path / "closed"
+ open_folder.mkdir()
+ closed_folder.mkdir()
+ with engine.begin() as conn:
+ open_project = projects_service.create_project(conn, str(open_folder), display_name="开放项目")
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": open_project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "organization_id": "org-1",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": EDITOR_EMAIL,
+ "access_role": "editor",
+ }
+ ],
+ },
+ )
+ closed_project = projects_service.create_project(conn, str(closed_folder), display_name="受限项目")
+ project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": closed_project["id"],
+ "revision": 1,
+ "mode": "restricted",
+ "organization_id": "foreign-org",
+ "bindings": [
+ {
+ "principal_kind": "organization_group",
+ "principal_value": "other-group",
+ "access_role": "viewer",
+ }
+ ],
+ },
+ )
+ sessions = {
+ name: create_session(
+ conn,
+ scope_id=scope,
+ agent_backend=agent.backend,
+ agent_name=agent.name,
+ title=f"目标会话 {name}",
+ )["id"]
+ for name, scope in (
+ ("open", open_project["scope_id"]),
+ ("closed", closed_project["scope_id"]),
+ ("standalone", None),
+ )
+ }
+
+ # The legacy target: an IM thread, resolved by ``(scope, anchor)`` exactly the
+ # way an inbound message resolves it.
+ service = SQLiteSessionsService(paths.get_sqlite_state_path())
+ try:
+ sessions["legacy"] = service.reserve_agent_session(
+ scope_key=IM_SCOPE_KEY,
+ agent_backend=agent.backend,
+ session_anchor=IM_ANCHOR,
+ agent_name=agent.name,
+ )
+ finally:
+ service.close()
+
+ def usable_agent():
+ with engine.begin() as conn:
+ resource_access_service.ensure_resource_policy(
+ conn,
+ resource_kind="agent",
+ resource_id=agent.id,
+ owner_user_id="someone-else",
+ organization_id="org-1",
+ access_level="public",
+ group_ids=[],
+ )
+
+ def unusable_agent():
+ with engine.begin() as conn:
+ conn.execute(
+ resource_access_policies.delete().where(
+ resource_access_policies.c.resource_id == agent.id
+ )
+ )
+
+ def counts():
+ with engine.connect() as conn:
+ return {
+ "sessions": conn.execute(
+ select(func.count()).select_from(agent_sessions)
+ ).scalar_one(),
+ # A placement check has to resolve the Scope it is asked about, and
+ # resolving a legacy key can create one. Counting Scopes is how a
+ # refusal proves it left nothing behind.
+ "scopes": conn.execute(select(func.count()).select_from(scopes)).scalar_one(),
+ "runs": conn.execute(select(func.count()).select_from(agent_runs)).scalar_one(),
+ "tasks": len(ScheduledTaskStore().list_tasks()),
+ "watches": len(ManagedWatchStore().list_watches()),
+ }
+
+ def task_rows():
+ return {item.id: asdict(item) for item in ScheduledTaskStore().list_tasks()}
+
+ def watch_rows():
+ return {item.id: asdict(item) for item in ManagedWatchStore().list_watches()}
+
+ usable_agent()
+ yield SimpleNamespace(
+ kind=kind,
+ agent=agent,
+ sessions=sessions,
+ open_project=open_project,
+ closed_project=closed_project,
+ usable_agent=usable_agent,
+ unusable_agent=unusable_agent,
+ counts=counts,
+ task_rows=task_rows,
+ watch_rows=watch_rows,
+ tmp_path=tmp_path,
+ )
+ store.close()
+ engine.dispose()
+
+
+def run_cli(monkeypatch, capsys):
+ """Run the real entry point as a caller, and report its exit code and refusal."""
+
+ # No waiter process runs in a hermetic test, so startup would never be
+ # confirmed. Observe the definition the command actually stored instead of
+ # waiting for it: the write still has to have happened for this to answer.
+ monkeypatch.setattr(
+ cli,
+ "_wait_for_watch_startup",
+ lambda store, runtime_store, watch_id, **kwargs: (
+ store.get_watch(watch_id),
+ runtime_store.load().get("watches", {}).get(watch_id),
+ ),
+ )
+
+ def run(argv, *, role="editor", kind="organization", caller_session=None):
+ for name in CALLER_CONTEXT_ENV_NAMES:
+ monkeypatch.delenv(name, raising=False)
+ if role is not None:
+ env = CallerContext(
+ session_id=caller_session or "ses_cli_caller",
+ is_remote=True,
+ resource_user_context=_snapshot(
+ role, instance_kind=kind, instance_id=_INSTANCE_ID
+ ),
+ ).to_env()
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(sys, "argv", ["vibe", *argv])
+ capsys.readouterr()
+ with pytest.raises(SystemExit) as exited:
+ cli.main()
+ captured = capsys.readouterr()
+ payload = None
+ if captured.err.strip():
+ try:
+ payload = json.loads(captured.err.strip())
+ except json.JSONDecodeError:
+ payload = None
+ return int(exited.value.code or 0), payload
+
+ return run
+
+
+def _editor_email_snapshot_matches_open_project() -> bool:
+ """The signed Editor snapshot carries the email the open Project binds."""
+
+ return _snapshot("editor")["email"] == EDITOR_EMAIL
+
+
+def _message_task_argv(session_flag, value, *, name="t"):
+ return [
+ "task",
+ "add",
+ "--name",
+ name,
+ session_flag,
+ value,
+ "--cron",
+ "0 9 * * *",
+ "--message",
+ "hello",
+ ]
+
+
+def _watch_argv(session_flag, value, *, name="w"):
+ return [
+ "watch",
+ "add",
+ "--name",
+ name,
+ session_flag,
+ value,
+ "--message",
+ "hello",
+ "--",
+ "true",
+ ]
+
+
+def _placed_argv(kind_of_work, placement, scope_id, *, name="p"):
+ """Create work whose Sessions are placed in ``scope_id``, not bound to one.
+
+ A watch's own command follows ``--``, so its placement flags have to precede
+ that terminator -- appended after it they are silently the command's arguments,
+ and the definition falls back to the caller's own Session.
+ """
+
+ flags = [placement, "--scope-id", scope_id]
+ if kind_of_work == "task":
+ return ["task", "add", "--name", name, "--cron", "0 9 * * *", "--message", "hello", *flags]
+ return ["watch", "add", "--name", name, "--message", "hello", *flags, "--", "true"]
+
+
+def test_permissions_028_the_open_project_binds_the_signed_editor():
+ """The fixture's positive control is the caller the Project actually names."""
+
+ assert _editor_email_snapshot_matches_open_project()
+
+
+ "command",
+ ["agent_run", "hook_send", "task_add", "watch_add"],
+)
+def test_permissions_028_every_producer_refuses_an_unreachable_target(targets, run_cli, command):
+ """PERMISSIONS-028: no producer writes work into a Session its caller cannot drive."""
+
+ state = targets
+ standalone = state.sessions["standalone"]
+ before = state.counts()
+
+ argv = {
+ "agent_run": ["agent", "run", "--session-id", standalone, "--message", "hi", "--async", "--no-callback"],
+ "hook_send": ["hook", "send", "--session-id", standalone, "--message", "hi"],
+ "task_add": _message_task_argv("--session-id", standalone),
+ "watch_add": _watch_argv("--session-id", standalone),
+ }[command]
+
+ code, payload = run_cli(argv, kind=state.kind)
+
+ # A standalone Session belongs to no Project, so it is runtime-management
+ # work on either instance kind -- the one negative that does not depend on
+ # a Personal instance's signed-kind Editor bypass.
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ assert state.counts() == before
+
+
+def test_permissions_028_a_legacy_key_names_the_same_session(targets, run_cli):
+ """PERMISSIONS-028: the deprecated scope key resolves to the row it would speak in."""
+
+ state = targets
+ before = state.counts()
+
+ code, payload = run_cli(
+ ["hook", "send", "--session-key", IM_SCOPE_KEY, "--message", "hi"],
+ kind=state.kind,
+ )
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ assert payload["details"]["session_id"] == state.sessions["legacy"]
+ assert state.counts() == before
+
+ # A key naming a thread that does not exist yet is a creation, not a
+ # refusal: it is admitted as a placement instead (see below), so a local
+ # caller opening new IM work is unaffected by the gate.
+ fresh = run_cli(
+ ["hook", "send", "--session-key", "slack::channel::C999", "--message", "hi"],
+ role=None,
+ )
+ assert fresh[0] == 0
+
+
+def test_permissions_028_the_callers_own_session_is_an_effective_target(targets, run_cli):
+ """PERMISSIONS-028: a target Avibe defaulted from the caller env is still checked."""
+
+ state = targets
+ before = state.counts()
+
+ # ``task add`` with no target means "here", so the Session comes from the
+ # caller environment rather than the argument -- and is just as much an
+ # effective target as one that was typed.
+ code, payload = run_cli(
+ ["task", "add", "--name", "t", "--cron", "0 9 * * *", "--message", "hello"],
+ kind=state.kind,
+ caller_session=state.sessions["standalone"],
+ )
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ assert state.counts() == before
+
+
+def test_permissions_028_a_callback_is_admitted_before_the_run_is_reserved(targets, run_cli):
+ """PERMISSIONS-028: the callback route is recorded on the row, so it is checked first."""
+
+ state = targets
+ before = state.counts()
+
+ code, payload = run_cli(
+ [
+ "agent",
+ "run",
+ "--agent",
+ state.agent.name,
+ "--message",
+ "hi",
+ "--async",
+ "--callback-session-id",
+ state.sessions["standalone"],
+ ],
+ kind=state.kind,
+ )
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ # Nothing reserved: the refusal landed before the new Session, not after it.
+ assert state.counts() == before
+
+
+def test_permissions_028_a_forbidden_project_target_is_refused(targets, run_cli):
+ """PERMISSIONS-028: Project chat access decides, with the Personal bypass intact."""
+
+ state = targets
+ before = state.counts()
+ code, payload = run_cli(
+ _message_task_argv("--session-id", state.sessions["closed"]),
+ kind=state.kind,
+ )
+
+ if state.kind == "organization":
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ assert state.counts() == before
+ else:
+ # A Personal instance has no Organization to restrict against; its
+ # Editor bypass is the intended answer here, not a gap.
+ assert code == 0
+ assert state.counts()["tasks"] == before["tasks"] + 1
+
+
+def test_permissions_028_an_unusable_agent_refuses_the_turn(targets, run_cli):
+ """PERMISSIONS-028: the Session's own Agent is the one the caller must be able to use."""
+
+ state = targets
+ state.unusable_agent()
+ before = state.counts()
+
+ code, payload = run_cli(
+ ["agent", "run", "--session-id", state.sessions["open"], "--message", "hi", "--async", "--no-callback"],
+ kind=state.kind,
+ )
+
+ if state.kind == "organization":
+ assert code == 1
+ assert payload["code"] == "agent_access_forbidden"
+ assert state.counts() == before
+ else:
+ assert code == 0
+
+
+def test_permissions_028_a_permitted_editor_still_queues_the_turn(targets, run_cli):
+ """PERMISSIONS-028: the gate refuses what a caller may not reach, nothing more."""
+
+ state = targets
+ before = state.counts()
+
+ code, payload = run_cli(
+ ["agent", "run", "--session-id", state.sessions["open"], "--message", "hi", "--async", "--no-callback"],
+ kind=state.kind,
+ )
+ assert code == 0, payload
+ assert state.counts()["runs"] == before["runs"] + 1
+
+ tasks_before = state.counts()
+ assert (
+ run_cli(_message_task_argv("--session-id", state.sessions["open"]), kind=state.kind)[0] == 0
+ )
+ assert state.counts()["tasks"] == tasks_before["tasks"] + 1
+
+
[email protected]("role", ["member", "owner", None])
+def test_permissions_028_runtime_management_and_local_callers_are_unchanged(targets, run_cli, role):
+ """PERMISSIONS-028: Member, Owner and local callers keep the reach they had."""
+
+ state = targets
+ before = state.counts()
+
+ code, payload = run_cli(
+ ["agent", "run", "--session-id", state.sessions["standalone"], "--message", "hi", "--async", "--no-callback"],
+ role=role,
+ kind=state.kind,
+ )
+ assert code == 0, payload
+ assert state.counts()["runs"] == before["runs"] + 1
+
+
+def test_permissions_028_an_update_reauthorizes_its_effective_target(targets, run_cli):
+ """PERMISSIONS-028: retargeting rewrites the definition under the invoker."""
+
+ state = targets
+ assert run_cli(_message_task_argv("--session-id", state.sessions["open"], name="keep"), kind=state.kind)[0] == 0
+ rows = state.task_rows()
+ task_id = next(iter(rows))
+ before = state.counts()
+
+ code, payload = run_cli(
+ ["task", "update", task_id, "--session-id", state.sessions["standalone"]],
+ kind=state.kind,
+ )
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ # The whole stored definition, not just its target: a refused edit writes nothing.
+ assert state.task_rows() == rows
+ assert state.counts() == before
+
+
+def test_permissions_028_an_inherited_update_target_is_checked_too(targets, run_cli):
+ """PERMISSIONS-028: an edit that never names the Session still speaks in it."""
+
+ state = targets
+ seeded, seeded_payload = run_cli(_watch_argv("--session-id", state.sessions["standalone"]), role=None)
+ assert seeded == 0, seeded_payload
+ rows = state.watch_rows()
+ watch_id = next(iter(rows))
+
+ code, payload = run_cli(["watch", "update", watch_id, "--name", "renamed"], kind=state.kind)
+ assert code == 1
+ assert payload["code"] == "session_not_found"
+ assert state.watch_rows() == rows
+
+
[email protected]("kind_of_work", ["task", "watch"])
[email protected]("placement", ["--create-session", "--create-session-per-run"])
+def test_permissions_028_a_permitted_destination_still_takes_the_work(
+ targets, run_cli, kind_of_work, placement
+):
+ """PERMISSIONS-028: the placement gate refuses a destination, not the shape of one."""
+
+ state = targets
+ code, payload = run_cli(
+ _placed_argv(kind_of_work, placement, state.open_project["scope_id"]),
+ kind=state.kind,
+ # A real Session for the caller env: ``watch add`` reads it for delivery,
+ # and an invented id fails there long before the gate under test.
+ caller_session=state.sessions["open"],
+ )
+ assert code == 0, payload
+ rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()
+ assert len(rows) == 1
+ assert next(iter(rows.values()))["session_policy"] == (
+ "create_once" if placement == "--create-session" else "create_per_run"
+ )
+
+
[email protected]("role", ["editor", "member", None])
+def test_permissions_028_per_run_work_with_no_scope_is_a_stream_of_standalone_sessions(
+ targets, run_cli, role
+):
+ """PERMISSIONS-028: creating unplaced Sessions repeatedly needs the reach to create one.
+
+ A ``create_per_run`` definition with no Scope reserves a standalone Session on
+ every fire, which is the reach an Editor is refused when they name one directly.
+ Deciding it at creation is the same answer, delivered where the caller is -- and
+ on both instance kinds, because an unplaced Session is runtime-management work
+ that no Personal Project bypass applies to.
+ """
+
+ state = targets
+ before = state.counts()
+ code, payload = run_cli(
+ ["task", "add", "--name", "p", "--cron", "0 9 * * *", "--message", "hello", "--create-session-per-run"],
+ role=role,
+ kind=state.kind,
+ )
+
+ if role == "editor":
+ assert code == 1
+ assert payload["code"] == "project_access_denied"
+ assert state.counts() == before
+ else:
+ assert code == 0, payload
+ assert state.counts()["tasks"] == before["tasks"] + 1
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_a_replacement_target_is_the_one_that_is_admitted(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: an edit that replaces the Session is judged on where it lands.
+
+ The definition will never speak in the old row again, so holding the caller to
+ it would refuse an Editor for a Session their own edit is removing. What has to
+ be admitted is the destination they chose -- and it is, by the reservation
+ writer, before the replacement Session exists.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["standalone"], name="move")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["standalone"], name="move")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()
+ definition_id = next(iter(rows))
+
+ code, payload = run_cli(
+ [
+ kind_of_work,
+ "update",
+ definition_id,
+ "--create-session",
+ "--scope-id",
+ state.open_project["scope_id"],
+ ],
+ kind=state.kind,
+ )
+ assert code == 0, payload
+
+ after = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+ assert after["session_policy"] == "create_once"
+ assert after["session_id"] not in (None, "", state.sessions["standalone"])
+
+
[email protected]("kind_of_work", ["task", "watch"])
[email protected]("placement", ["--create-session", "--create-session-per-run"])
+def test_permissions_028_a_replacement_cannot_land_where_the_caller_cannot_chat(
+ targets, run_cli, kind_of_work, placement
+):
+ """PERMISSIONS-028: replacing the target does not buy a Project the caller lacks.
+
+ Both placements are covered because they refuse in different places: one
+ reusable Session is reserved during the edit, while one Session per run is only
+ described by it -- and a description that nothing admits would hand every future
+ fire a Project this caller may not chat in.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["open"], name="move")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["open"], name="move")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()
+ definition_id = next(iter(rows))
+ before = state.counts()
+
+ code, payload = run_cli(
+ [
+ kind_of_work,
+ "update",
+ definition_id,
+ placement,
+ "--scope-id",
+ state.closed_project["scope_id"],
+ ],
+ kind=state.kind,
+ )
+
+ if state.kind == "organization":
+ assert code == 1
+ assert payload["code"] == "project_access_denied"
+ # Neither the replacement Session nor the edited definition was written.
+ assert state.counts() == before
+ assert (state.task_rows() if kind_of_work == "task" else state.watch_rows()) == rows
+ else:
+ # Same Personal-instance bypass as every other Project negative here.
+ assert code == 0, payload
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_per_run_work_admits_the_agent_every_fire_will_use(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: a definition that follows no Session picks its own Agent.
+
+ ``--clear-agent`` records that the bound Session owns the Agent choice, and the
+ edit that reads that marker deliberately resolves nothing -- re-resolving would
+ pin today's default over the Session (HFR-245). Converting the same definition
+ to one Session per run leaves no Session to own anything, so the marker survived
+ describing a row that no longer exists: the placement below was handed no Agent,
+ admitted the Scope alone, and every future fire then created its Session on the
+ Scope's default Agent, which nobody had been asked about.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["open"], name="follow")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["open"], name="follow")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ definition_id = next(iter(state.task_rows() if kind_of_work == "task" else state.watch_rows()))
+ assert run_cli([kind_of_work, "update", definition_id, "--clear-agent"], kind=state.kind)[0] == 0
+
+ # The Agent those fires would pick is now one this caller may not use. Nothing
+ # about the definition changed: it is the destination that did.
+ state.unusable_agent()
+ rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()
+ assert rows[definition_id]["metadata"][BINDING_FOLLOWS_SESSION_METADATA_KEY] is True
+ before = state.counts()
+
+ code, payload = run_cli(
+ [
+ kind_of_work,
+ "update",
+ definition_id,
+ "--create-session-per-run",
+ "--scope-id",
+ state.open_project["scope_id"],
+ ],
+ kind=state.kind,
+ )
+
+ if state.kind == "organization":
+ assert code == 1
+ assert payload["code"] == "agent_access_forbidden"
+ # Including the marker: a refused edit leaves the definition as it was.
+ assert (state.task_rows() if kind_of_work == "task" else state.watch_rows()) == rows
+ assert state.counts() == before
+ else:
+ assert code == 0, payload
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_an_admitted_per_run_target_keeps_the_agent_it_resolved(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: the same conversion, admitted, records what it admitted.
+
+ The Agent is resolved before the placement question so the answer is about the
+ Agent the fires will run as -- and the definition is then saved carrying it,
+ rather than an obsolete "ask my Session" that no longer names one.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["open"], name="follow")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["open"], name="follow")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ definition_id = next(iter(state.task_rows() if kind_of_work == "task" else state.watch_rows()))
+ assert run_cli([kind_of_work, "update", definition_id, "--clear-agent"], kind=state.kind)[0] == 0
+
+ code, payload = run_cli(
+ [
+ kind_of_work,
+ "update",
+ definition_id,
+ "--create-session-per-run",
+ "--scope-id",
+ state.open_project["scope_id"],
+ ],
+ kind=state.kind,
+ )
+ assert code == 0, payload
+
+ after = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+ assert after["session_policy"] == "create_per_run"
+ assert BINDING_FOLLOWS_SESSION_METADATA_KEY not in after["metadata"]
+ assert after["agent_name"] == state.agent.name
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_a_bound_session_still_keeps_the_agents_authority(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: the marker is dropped where it is obsolete, and nowhere else.
+
+ HFR-245/256: a definition bound to a Session must come back from an unrelated
+ edit still following it, or the next ``--name`` silently moves every fire onto
+ today's default Agent. That is the state the case above ends, so it is asserted
+ here in the shape that keeps it.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["open"], name="follow")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["open"], name="follow")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ definition_id = next(iter(state.task_rows() if kind_of_work == "task" else state.watch_rows()))
+
+ assert run_cli([kind_of_work, "update", definition_id, "--clear-agent"], kind=state.kind)[0] == 0
+ cleared = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+ assert cleared["agent_name"] is None
+ assert cleared["metadata"][BINDING_FOLLOWS_SESSION_METADATA_KEY] is True
+
+ assert run_cli([kind_of_work, "update", definition_id, "--name", "renamed"], kind=state.kind)[0] == 0
+ renamed = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+ assert renamed["agent_name"] is None
+ assert renamed["metadata"][BINDING_FOLLOWS_SESSION_METADATA_KEY] is True
+ assert renamed["session_id"] == cleared["session_id"]
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_a_reserved_replacement_still_follows_the_session_it_makes(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: one reusable Session is a row, so it can still own the Agent.
+
+ This is the boundary of the case above: ``--create-session`` reserves the
+ Session during the edit -- the same shape the reset rebind stamps the marker on
+ -- and the reservation writer resolves and admits the Agent it gives that
+ Session. Nothing here is unasked, so the definition keeps following the Session
+ it now has instead of being re-pinned.
+
+ That reservation had never actually run on this branch: the follow-the-Session
+ path left ``agent`` unbound and the writer read it, so the combination failed
+ with an internal error rather than either answer.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["open"], name="follow")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["open"], name="follow")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ definition_id = next(iter(state.task_rows() if kind_of_work == "task" else state.watch_rows()))
+ assert run_cli([kind_of_work, "update", definition_id, "--clear-agent"], kind=state.kind)[0] == 0
+ cleared = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+
+ code, payload = run_cli(
+ [
+ kind_of_work,
+ "update",
+ definition_id,
+ "--create-session",
+ "--scope-id",
+ state.open_project["scope_id"],
+ ],
+ kind=state.kind,
+ )
+ assert code == 0, payload
+
+ after = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+ assert after["session_policy"] == "create_once"
+ assert after["session_id"] not in (None, "", cleared["session_id"])
+ assert after["agent_name"] is None
+ assert after["metadata"][BINDING_FOLLOWS_SESSION_METADATA_KEY] is True
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_clearing_the_agent_on_per_run_work_resolves_one(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: the same question, reached from the other side.
+
+ A definition that already creates one Session per run has no Session to hand
+ Agent authority back to, so ``--clear-agent`` on it is the request the marker
+ cannot serve. It resolves the Agent the fires will use and is admitted for it,
+ instead of saving a definition with no Agent and no Session to ask.
+
+ The rename rides along because clearing alone changes nothing once the Agent is
+ resolved back -- the edit is refused as empty, which is true but says nothing
+ about the gate under test.
+ """
+
+ state = targets
+ seeded, seeded_payload = run_cli(
+ _placed_argv(
+ kind_of_work,
+ "--create-session-per-run",
+ state.open_project["scope_id"],
+ name="perrun",
+ ),
+ kind=state.kind,
+ caller_session=state.sessions["open"],
+ )
+ assert seeded == 0, seeded_payload
+ definition_id = next(iter(state.task_rows() if kind_of_work == "task" else state.watch_rows()))
+
+ state.unusable_agent()
+ rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()
+ assert rows[definition_id]["session_policy"] == "create_per_run"
+ before = state.counts()
+
+ code, payload = run_cli(
+ [kind_of_work, "update", definition_id, "--clear-agent", "--name", "renamed"],
+ kind=state.kind,
+ )
+
+ if state.kind == "organization":
+ assert code == 1
+ assert payload["code"] == "agent_access_forbidden"
+ assert (state.task_rows() if kind_of_work == "task" else state.watch_rows()) == rows
+ assert state.counts() == before
+ else:
+ assert code == 0, payload
+ after = (state.task_rows() if kind_of_work == "task" else state.watch_rows())[definition_id]
+ assert BINDING_FOLLOWS_SESSION_METADATA_KEY not in after["metadata"]
+ assert after["agent_name"] == state.agent.name
+
+
[email protected]("role", ["member", "owner", None])
+def test_permissions_028_the_callers_that_could_still_retarget_per_run_work(
+ targets, run_cli, role
+):
+ """PERMISSIONS-028: Member, Owner and a local caller keep converting definitions."""
+
+ state = targets
+ assert run_cli(_message_task_argv("--session-id", state.sessions["open"], name="follow"), role=None)[0] == 0
+ task_id = next(iter(state.task_rows()))
+ assert run_cli(["task", "update", task_id, "--clear-agent"], role=role, kind=state.kind)[0] == 0
+
+ code, payload = run_cli(
+ [
+ "task",
+ "update",
+ task_id,
+ "--create-session-per-run",
+ "--scope-id",
+ state.open_project["scope_id"],
+ ],
+ role=role,
+ kind=state.kind,
+ )
+ assert code == 0, payload
+ after = state.task_rows()[task_id]
+ assert after["agent_name"] == state.agent.name
+ assert BINDING_FOLLOWS_SESSION_METADATA_KEY not in after["metadata"]
+
+
[email protected]("command", ["hook_send", "task_add", "watch_add"])
+def test_permissions_028_a_fresh_legacy_target_is_a_placement_not_a_blank(
+ targets, run_cli, command
+):
+ """PERMISSIONS-028: a key whose thread nobody has opened yet is still a target.
+
+ There is no Session to admit the caller TO, but the work being written says
+ where one will be created on the first dispatch -- the reservation writer's
+ question, asked one step earlier. Read as "no target, no question", the same
+ Editor who is refused the IM thread that exists was handed the one that does
+ not, and every future fire with it.
+ """
+
+ state = targets
+ key = f"{FRESH_SCOPE_KEY}_{command}"
+ before = state.counts()
+
+ argv = {
+ "hook_send": ["hook", "send", "--session-key", key, "--message", "hi"],
+ "task_add": _message_task_argv("--session-key", key),
+ "watch_add": _watch_argv("--session-key", key),
+ }[command]
+ code, payload = run_cli(argv, kind=state.kind)
+
+ # An IM scope is not a Project, so no Personal Project bypass reaches this --
+ # the same answer the identical key gets once its Session exists.
+ assert code == 1
+ assert payload["code"] == "project_access_denied"
+ # Scopes included: resolving the key to ask the question must not leave the
+ # row the question was about.
+ assert state.counts() == before
+
+
[email protected]("role", ["member", "owner", None])
+def test_permissions_028_fresh_legacy_work_still_opens_for_the_callers_that_could(
+ targets, run_cli, role
+):
+ """PERMISSIONS-028: Member, Owner and a local caller keep opening new IM work."""
+
+ state = targets
+ before = state.counts()
+
+ code, payload = run_cli(
+ ["hook", "send", "--session-key", f"{FRESH_SCOPE_KEY}_{role}", "--message", "hi"],
+ role=role,
+ kind=state.kind,
+ )
+ assert code == 0, payload
+ assert state.counts()["runs"] == before["runs"] + 1
+
+
[email protected]("kind_of_work", ["task", "watch"])
+def test_permissions_028_an_update_onto_a_fresh_legacy_target_is_admitted_too(
+ targets, run_cli, kind_of_work
+):
+ """PERMISSIONS-028: an edit may not repoint saved work at a Scope it cannot reach.
+
+ The definition keeps speaking in the target this edit names, so the target is
+ reauthorized -- and a Session that does not exist yet is reauthorized as the
+ placement it is, not skipped for having no row.
+ """
+
+ state = targets
+ seeded = (
+ _message_task_argv("--session-id", state.sessions["standalone"], name="repoint")
+ if kind_of_work == "task"
+ else _watch_argv("--session-id", state.sessions["standalone"], name="repoint")
+ )
+ assert run_cli(seeded, role=None)[0] == 0
+ rows = state.task_rows() if kind_of_work == "task" else state.watch_rows()
+ definition_id = next(iter(rows))
+ before = state.counts()
+
+ code, payload = run_cli(
+ [
+ kind_of_work,
+ "update",
+ definition_id,
+ "--session-key",
+ f"{FRESH_SCOPE_KEY}_update_{kind_of_work}",
+ ],
+ kind=state.kind,
+ )
+ assert code == 1
+ assert payload["code"] == "project_access_denied"
+ assert (state.task_rows() if kind_of_work == "task" else state.watch_rows()) == rows
+ assert state.counts() == before
+
+
+def test_permissions_028_saved_control_keeps_the_definitions_own_authority(targets, run_cli):
+ """PERMISSIONS-028: pausing saved work is admission, not a reauthorization."""
+
+ state = targets
+ assert run_cli(_message_task_argv("--session-id", state.sessions["standalone"]), role=None)[0] == 0
+ rows = state.task_rows()
+ task_id = next(iter(rows))
+
+ # An Editor may steer a definition they could not have created: the target was
+ # admitted when it was written, and control must not restamp it to the invoker.
+ assert run_cli(["task", "pause", task_id], kind=state.kind)[0] == 0
+ paused = state.task_rows()[task_id]
+ assert paused["session_id"] == rows[task_id]["session_id"]
+ assert paused["metadata"] == rows[task_id]["metadata"]
+
+ assert run_cli(["task", "resume", task_id], kind=state.kind)[0] == 0
+ assert state.task_rows()[task_id]["metadata"] == rows[task_id]["metadata"]
diff --git a/tests/scenarios/permissions/test_member_instance_operations.py b/tests/scenarios/permissions/test_member_instance_operations.py
index 13bd27f90..c89e03d0b 100644
--- a/tests/scenarios/permissions/test_member_instance_operations.py
+++ b/tests/scenarios/permissions/test_member_instance_operations.py
@@ -25,7 +25,7 @@ from storage.models import agent_sessions, messages, resource_access_policies, r
from storage.workbench_sessions_service import create_session
from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_peer, remote_session_cookie
from vibe import internal_client, remote_access, ui_server
-from vibe.authorization import AuthorizationContext
+from vibe.authorization import INSTANCE_SCOPED_REFETCH_EVENTS, AuthorizationContext
from vibe.sse_broker import broker
from vibe.ui_compat import g
@@ -285,9 +285,18 @@ def test_permissions_016_real_sse_management_and_session_delivery(operations, ro
"""PERMISSIONS-016: publisher payloads traverse both stream gates."""
state = operations
events = [
- ("vaults.updated", vaults_updated_payload(scope="requests", request_id="request-α")),
+ (
+ "vaults.updated",
+ vaults_updated_payload(scope="requests", request_id="request-α", secret_name="SECRET_α"),
+ ),
("definitions.updated", {"definition_type": "scheduled"}),
("runs.updated", run_updated_payload(run_id="run-α", status="running")),
+ # The same instance-wide invalidation with the optional session id a
+ # publisher may attach: admission must not start depending on it.
+ (
+ "runs.updated",
+ run_updated_payload(run_id="run-β", status="running", session_id=state.sessions[0]["id"]),
+ ),
("remote_access.quality.changed", {"state": "healthy", "sampled_at": "2026-09-17T14:00:00Z"}),
("message.updated", {"session_id": state.sessions[1]["id"], "id": "message-α"}),
("session.status", {"session_id": state.sessions[0]["id"], "status": "running"}),
@@ -323,8 +332,18 @@ def test_permissions_016_real_sse_management_and_session_delivery(operations, ro
if role in {"member", "owner"}:
assert [(frame["type"], frame["data"]) for frame in delivered[: len(events)]] == events
assert len(delivered) == len(events) + (role == "owner")
- elif role == "editor" and state.kind == "personal":
- assert [(frame["type"], frame["data"]) for frame in delivered] == [events[-1]]
+ elif role == "editor":
+ # An Editor uses Harness, Vault and Runs, so the instance-wide
+ # invalidations reach them as bare signals they refetch under their own
+ # authority. Empty data is the assertion that no publisher identifier —
+ # secret name or session id — rides along. Everything else is unchanged:
+ # link quality stays management, the unknown event stays Owner-only, and
+ # session frames still follow the Project ACL.
+ invalidations = [
+ (event_type, {}) for event_type, _ in events if event_type in INSTANCE_SCOPED_REFETCH_EVENTS
+ ]
+ reachable_sessions = [events[-1]] if state.kind == "personal" else []
+ assert [(frame["type"], frame["data"]) for frame in delivered] == [*invalidations, *reachable_sessions]
else:
assert delivered == []
diff --git a/tests/test_cli_agent_models.py b/tests/test_cli_agent_models.py
index ff52216a5..e93192887 100644
--- a/tests/test_cli_agent_models.py
+++ b/tests/test_cli_agent_models.py
@@ -158,7 +158,15 @@ def test_cmd_agent_models_by_name_echoes_current(monkeypatch):
agent = SimpleNamespace(
name="my-audit", backend="claude", model="claude-opus-4-8", reasoning_effort="high"
)
- monkeypatch.setattr(cli, "_agent_store", lambda: SimpleNamespace(require=lambda name: agent))
+ # Naming an Agent reads that Agent, so the command asks the store for one
+ # the caller may USE. ``require`` stays on the stub because the two answer
+ # the same row here -- the access check is exercised in the permissions
+ # scenarios, not by weakening it into this catalog test.
+ monkeypatch.setattr(
+ cli,
+ "_agent_store",
+ lambda: SimpleNamespace(require=lambda name: agent, require_accessible=lambda name: agent),
+ )
monkeypatch.setattr(
cli.api,
"agent_model_options",
@@ -188,7 +196,15 @@ def test_cmd_agent_models_current_flags_invalid_effort(monkeypatch):
agent = SimpleNamespace(
name="drifted", backend="claude", model="claude-opus-4-8", reasoning_effort="bogus"
)
- monkeypatch.setattr(cli, "_agent_store", lambda: SimpleNamespace(require=lambda name: agent))
+ # Naming an Agent reads that Agent, so the command asks the store for one
+ # the caller may USE. ``require`` stays on the stub because the two answer
+ # the same row here -- the access check is exercised in the permissions
+ # scenarios, not by weakening it into this catalog test.
+ monkeypatch.setattr(
+ cli,
+ "_agent_store",
+ lambda: SimpleNamespace(require=lambda name: agent, require_accessible=lambda name: agent),
+ )
monkeypatch.setattr(
cli.api,
"agent_model_options",
@@ -213,7 +229,15 @@ def test_cmd_agent_models_model_filter_keeps_current_honest(monkeypatch):
agent = SimpleNamespace(
name="my-audit", backend="claude", model="claude-opus-4-8", reasoning_effort="high"
)
- monkeypatch.setattr(cli, "_agent_store", lambda: SimpleNamespace(require=lambda name: agent))
+ # Naming an Agent reads that Agent, so the command asks the store for one
+ # the caller may USE. ``require`` stays on the stub because the two answer
+ # the same row here -- the access check is exercised in the permissions
+ # scenarios, not by weakening it into this catalog test.
+ monkeypatch.setattr(
+ cli,
+ "_agent_store",
+ lambda: SimpleNamespace(require=lambda name: agent, require_accessible=lambda name: agent),
+ )
monkeypatch.setattr(
cli.api,
"agent_model_options",
diff --git a/tests/test_cli_definition_read_projection.py b/tests/test_cli_definition_read_projection.py
index 2df40ba04..f7cfb019a 100644
--- a/tests/test_cli_definition_read_projection.py
+++ b/tests/test_cli_definition_read_projection.py
@@ -408,14 +408,14 @@ def test_public_definition_routes_hide_owner_without_changing_runtime_metadata()
response = client.get(f"/api/harness/{plural}{query}")
assert response.status_code == 200
row = next(item for item in response.get_json()[plural] if item["id"] == identifier)
- assert "delegated_memory_owner" not in row["metadata"]
+ assert not private.keys() & row["metadata"].keys()
for enabled in (False, True):
response = client.patch(
f"/api/harness/{plural}/{identifier}", json={"enabled": enabled},
headers=csrf_headers(client),
)
assert response.status_code == 200
- assert "delegated_memory_owner" not in response.get_json()[field]["metadata"]
+ assert not private.keys() & response.get_json()[field]["metadata"].keys()
assert all(read(identifier)["metadata"][key] == value for key, value in private.items())
finally:
store.close()
@@ -454,7 +454,7 @@ def test_definition_to_run_public_projection_keeps_raw_execution_owner(capsys):
for output in (shown, listed, cli_run):
public = output["metadata"]
assert "delegated_memory_owner" not in public
- assert public["resource_user_context"] == metadata["resource_user_context"]
+ assert "resource_user_context" not in public
assert public["scheduled_provenance"]["platform_specific"]["message_metadata"] == {"visible": "retained"}
reloaded = TaskExecutionStore().get_run(run.id)
assert reloaded["metadata"]["delegated_memory_owner"] == owner
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 1a5ba0104..ee0272c95 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -15,6 +15,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from storage.importer import ensure_sqlite_state
from vibe import cli
@@ -869,10 +870,11 @@ def test_remote_editor_task_add_persists_authorization_context(
assert result == 0
payload = json.loads(capsys.readouterr().out)
- assert payload["definition"]["metadata"]["resource_user_context"][
- "vibe_instance_role"
- ] == "editor"
- assert len(cli.ScheduledTaskStore(store_path).list_tasks()) == 1
+ # Persisted for the deferred run, hidden from the projection it prints.
+ assert "resource_user_context" not in payload["definition"]["metadata"]
+ stored = cli.ScheduledTaskStore(store_path).list_tasks()
+ assert len(stored) == 1
+ assert stored[0].metadata["resource_user_context"]["vibe_instance_role"] == "editor"
def test_task_add_create_per_run_scope_id_records_session_scope_metadata(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:
@@ -3361,6 +3363,11 @@ def test_agent_run_rejects_cross_backend_agent_for_existing_session(tmp_path: Pa
def test_agent_run_existing_session_allows_matching_agent_hint(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:
db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")
+ # The raw schema template carries no import marker, so the first CLI call to
+ # ``_ensure_cli_sqlite_state`` would run the JSON importer over this database
+ # and drop the rows seeded below. Establish the state first, as the rest of
+ # this module does, then seed what the command is meant to find.
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
agent_store = cli.VibeAgentStore(db_path)
agent_store.create(name="codex-worker", backend="codex")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
@@ -3434,6 +3441,11 @@ def test_agent_run_rejects_different_same_backend_agent_for_existing_session(tmp
def test_agent_run_rejects_post_to_thread_for_threadless_session_before_enqueue(tmp_path: Path, sqlite_schema_db_factory) -> None:
db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")
+ # The raw schema template carries no import marker, so the first CLI call to
+ # ``_ensure_cli_sqlite_state`` would run the JSON importer over this database
+ # and drop the rows seeded below. Establish the state first, as the rest of
+ # this module does, then seed what the command is meant to find.
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
agent_store = cli.VibeAgentStore(db_path)
agent_store.create(name="worker", backend="codex")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
@@ -3466,6 +3478,11 @@ def test_agent_run_rejects_post_to_thread_for_threadless_session_before_enqueue(
def test_agent_run_rejects_cross_platform_deliver_key_before_enqueue(tmp_path: Path, sqlite_schema_db_factory) -> None:
db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")
+ # The raw schema template carries no import marker, so the first CLI call to
+ # ``_ensure_cli_sqlite_state`` would run the JSON importer over this database
+ # and drop the rows seeded below. Establish the state first, as the rest of
+ # this module does, then seed what the command is meant to find.
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
agent_store = cli.VibeAgentStore(db_path)
agent_store.create(name="worker", backend="codex")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
@@ -3521,6 +3538,11 @@ def test_agent_run_rejects_delivery_options_without_session_policy() -> None:
def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_path: Path, capsys, sqlite_schema_db_factory) -> None:
db_path = sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")
+ # The raw schema template carries no import marker, so the first CLI call to
+ # ``_ensure_cli_sqlite_state`` would run the JSON importer over this database
+ # and drop the rows seeded below. Establish the state first, as the rest of
+ # this module does, then seed what the command is meant to find.
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
agent_store = cli.VibeAgentStore(db_path)
agent_store.create(name="worker", backend="codex")
request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 6a4766d84..9641a4402 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -507,10 +507,11 @@ def test_remote_editor_watch_add_starts_and_persists_authorization_context(
assert result == 0
payload = json.loads(capsys.readouterr().out)
- assert payload["definition"]["metadata"]["resource_user_context"][
- "vibe_instance_role"
- ] == "editor"
- assert len(ManagedWatchStore(store_path).list_watches()) == 1
+ # Persisted for the deferred run, hidden from the projection it prints.
+ assert "resource_user_context" not in payload["definition"]["metadata"]
+ stored = ManagedWatchStore(store_path).list_watches()
+ assert len(stored) == 1
+ assert stored[0].metadata["resource_user_context"]["vibe_instance_role"] == "editor"
assert len(startup_calls) == 1
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 44c4e5444..75b28b72e 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -77,13 +77,22 @@ def test_public_surface_is_stable():
"is_session_archived",
"list_sessions",
"list_sessions_page",
+ # Chat-authority guard the queue commands share with the HTTP routes:
+ "require_session_chat_access",
+ # Chat authority plus the session's Agent: what a producer of deferred
+ # work must clear before the reservation it will be rebuilt from exists.
+ "require_session_turn_authority",
+ # The same question for a target whose Session does not exist yet: the
+ # Scope the future Session will be created in, plus the Agent the future
+ # dispatch will select.
+ "require_session_placement_authority",
"set_agent_status",
"touch_session",
"touch_session_agent_activity",
"update_session",
# Legacy IM-style reservation helpers added in C2 for the CLI:
"reserve_agent_session",
- "reserve_standalone_agent_session",
+ "reserve_standalone_agent_session",
# Backend-pin guard raised by update_session on a cross-backend switch:
"SessionBackendLockedError",
# Terminal-archive guard raised by update_session on an archived row:
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index ff2aaa50c..d90320089 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -568,7 +568,14 @@ def test_workbench_events_follow_role_boundaries() -> None:
assert can_receive_workbench_event(context, "message.updated")
assert not can_receive_workbench_event(viewer, "queue.updated")
assert can_receive_workbench_event(editor, "queue.updated")
- assert not can_receive_workbench_event(editor, "runs.updated")
+ # An Editor uses Runs, Harness definitions and Vault, so these instance-wide
+ # invalidations are admitted for them as bare refetch signals. What an Editor
+ # then sees is decided by the refetch under their own authority, and the
+ # payload filter strips any publisher identifier riding along.
+ assert can_receive_workbench_event(editor, "runs.updated")
+ assert can_receive_workbench_event(editor, "definitions.updated")
+ assert can_receive_workbench_event(editor, "vaults.updated")
+ assert not can_receive_workbench_event(viewer, "runs.updated")
assert can_receive_workbench_event(member, "runs.updated")
assert can_receive_workbench_event(member, "definitions.updated")
assert can_receive_workbench_event(member, "vaults.updated")
diff --git a/tests/test_memory_delegated_reads.py b/tests/test_memory_delegated_reads.py
index 5d562a8d8..6d3fc5e09 100644
--- a/tests/test_memory_delegated_reads.py
+++ b/tests/test_memory_delegated_reads.py
@@ -530,7 +530,7 @@ def test_public_definition_projection_preserves_sqlite_runtime_owner(managers, m
restored = ManagedWatchStore().get_watch(definition.id)
for item in [shown, *listed, fallback]:
assert "delegated_memory_owner" not in item["metadata"]
- assert item["metadata"]["resource_user_context"] == resource
+ assert "resource_user_context" not in item["metadata"]
assert restored.metadata["delegated_memory_owner"] == owner
assert restored.metadata["resource_user_context"] == resource
finally:
diff --git a/tests/test_memory_ui_access.py b/tests/test_memory_ui_access.py
index 3f704a9fe..eadfe5f83 100644
--- a/tests/test_memory_ui_access.py
+++ b/tests/test_memory_ui_access.py
@@ -48,7 +48,7 @@ def test_ui_read_secret_is_consumed_from_stdin_without_entering_child_environmen
assert ui_access.initialize_process_ui_read_secret() == secret
assert ui_access.MEMORY_UI_SECRET_STDIN_ENV not in ui_access.os.environ
- child_env = runtime._memory_ui_child_env(
+ child_env = runtime.independent_process_env(
{"PATH": "/bin"},
memory_ui_secret=secret,
)
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index e47a6a878..230abbddf 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -85,6 +85,24 @@ def _use_default_model_hub_release_environment(monkeypatch):
monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
[email protected](autouse=True)
+def _seed_default_state_database(request, tmp_path, sqlite_db_factory):
+ """Give this module's default state database the pre-migrated head.
+
+ The shared seeder decides from a module's own source whether it reaches
+ default SQLite state, and skips one that never names it. Nothing here does:
+ the database is reached through ``config.save()`` and the routes under test,
+ so the skip was a false negative and every case in this file replayed the
+ whole migration chain to arrive at the same empty head. Seeded through the
+ same factory the shared fixture uses, at the isolated home it creates, so
+ the template and the per-test copy keep their single owner.
+ """
+
+ if request.node.get_closest_marker("no_sqlite_template"):
+ return
+ sqlite_db_factory(tmp_path / "home" / ".avibe" / "state" / "vibe.sqlite")
+
+
def _schema(name: str) -> dict:
return json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 1c9147524..4634287a0 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -1936,6 +1936,59 @@ def test_pre_member_resource_user_context_snapshot_keeps_editor_role() -> None:
assert not restored.can_manage_instance
+def test_deferred_snapshot_carries_the_signed_email_and_ignores_supplied_metadata() -> None:
+ """PERMISSIONS-025: Project email ACLs need the principal the request had.
+
+ The normalized form is the one ``_matching_binding_role`` compares, and the
+ key is written from the signed context after any caller-supplied value is
+ dropped, so untrusted metadata can neither mint nor override it.
+ """
+
+ context = resource_access_service.ResourceUserContext(
+ subject="editor-1",
+ email="[email protected] ",
+ organization_id="org-1",
+ organization_member_id="organization-member-1",
+ organization_role="member",
+ instance_role="editor",
+ instance_access_source="email",
+ claims_issued_at=1_700_000_000,
+ is_remote=True,
+ )
+ spoofed = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "someone-else",
+ "email": "[email protected]",
+ "vibe_instance_role": "owner",
+ }
+ }
+ metadata = resource_access_service.metadata_with_resource_user_context(spoofed, context)
+ assert metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]["email"] == "[email protected]"
+ restored = resource_access_service.resource_user_context_from_metadata(metadata)
+ assert restored is not None
+ assert restored.email == "[email protected]"
+ assert restored.subject == "editor-1"
+ assert restored.instance_role == "editor"
+
+
+def test_historical_snapshot_without_an_email_is_not_given_one() -> None:
+ """PERMISSIONS-025: an unstamped principal stays absent rather than inferred."""
+
+ legacy = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "editor-1",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_role": "member",
+ }
+ }
+ restored = resource_access_service.resource_user_context_from_metadata(legacy)
+ assert restored is not None
+ assert restored.email is None
+ assert restored.has_role("editor")
+
+
def test_instance_member_operates_resources_without_rewriting_acl(tmp_path, sqlite_schema_db_factory) -> None:
db = tmp_path / "vibe.sqlite"
sqlite_schema_db_factory(db)
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 6dc87b9a1..8305db6fd 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -3954,6 +3954,9 @@ def test_show_event_cli_dispatch_flag_updates_annotation_payload(monkeypatch, tm
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ # A dispatching event reserves its turn under the caller's own
+ # authority before anything is posted, so the session has to exist.
+ _seed_show_cli_session()
monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
captured = {}
@@ -4014,6 +4017,9 @@ def test_show_event_cli_dispatch_preserves_top_level_payload(monkeypatch, tmp_pa
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ # A dispatching event reserves its turn under the caller's own
+ # authority before anything is posted, so the session has to exist.
+ _seed_show_cli_session()
monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
captured = {}
@@ -4129,6 +4135,9 @@ def test_show_event_cli_embedded_dispatch_fallback_uses_synchronous_bridge(monke
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ # A dispatching event reserves its turn under the caller's own
+ # authority before anything is posted, so the session has to exist.
+ _seed_show_cli_session()
monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": None})
captured = {}
@@ -4171,6 +4180,9 @@ def test_show_event_cli_failed_delivery_reports_generated_event_id(
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ # A dispatching event reserves its turn under the caller's own
+ # authority before anything is posted, so the session has to exist.
+ _seed_show_cli_session()
monkeypatch.setattr(cli, "_post_show_event_to_live_ui", lambda *_args: None)
attempted = {}
@@ -4220,6 +4232,9 @@ def test_show_event_cli_timeout_replaces_blank_id_before_local_retry(
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ # A dispatching event reserves its turn under the caller's own
+ # authority before anything is posted, so the session has to exist.
+ _seed_show_cli_session()
monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
posted = {}
@@ -4412,6 +4427,9 @@ def test_show_event_cli_http_502_replays_same_event_identity_locally(monkeypatch
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
_save_config()
+ # A dispatching event reserves its turn under the caller's own
+ # authority before anything is posted, so the session has to exist.
+ _seed_show_cli_session()
monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
posted = {}
diff --git a/tests/test_skill_observability.py b/tests/test_skill_observability.py
index 475918cd2..7ddd87b1f 100644
--- a/tests/test_skill_observability.py
+++ b/tests/test_skill_observability.py
@@ -610,7 +610,7 @@ def test_skill_usage_help_follows_cli_language(monkeypatch, capsys, language):
output = capsys.readouterr().out
for key in ("helpCommand", "helpClear", "helpYes"):
assert t(f"data.skillUsage.{key}", language) in output
- assert ("Member or Owner" if language == "en" else "成员或所有者") in output
+ assert ("Member or Owner" if language == "en" else "管理者或所有者") in output
assert ("Owner only" if language == "en" else "仅限实例所有者") not in output
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 5ae7eff31..8a2ea0826 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -7796,6 +7796,141 @@ def test_public_show_page_events_preserve_dispatch_for_authorized_user(monkeypat
assert dispatches[0]["session_id"] == "ses123"
+def test_public_show_page_dispatch_records_the_visitor_that_admitted_it(monkeypatch, tmp_path):
+ """PERMISSIONS-027: the share route resolves its visitor once and stores that visitor.
+
+ Admission and provenance have to read one object. A share visitor is not
+ whoever this process would otherwise resolve to, and pairing, claims and
+ access can all change between two awaits — so resolving a second time could
+ admit one person and record the deferred turn under another. The resolver
+ below answers differently after its first call, which makes any second
+ resolution visible in the identity that ends up persisted.
+ """
+
+ from dataclasses import replace as replace_context
+
+ from core.show_session_events import ShowSessionEventStore
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path, paired=True)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+
+ resolved = []
+ resolve_public_editor = ui_server._show_public_editor_context
+
+ def changing_editor_context():
+ context = resolve_public_editor()
+ resolved.append(context)
+ if len(resolved) == 1:
+ return context
+ return replace_context(context, email="[email protected]", subject="user-9")
+
+ monkeypatch.setattr("vibe.ui_server._show_public_editor_context", changing_editor_context)
+
+ appended = []
+ append_event = ShowSessionEventStore.append
+
+ def recording_append(self, session_id, payload, **kwargs):
+ appended.append(kwargs.get("authorization_context"))
+ return append_event(self, session_id, payload, **kwargs)
+
+ monkeypatch.setattr(ShowSessionEventStore, "append", recording_append)
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _active_org_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ reserved = []
+
+ async def fake_dispatch_async(payload, **kwargs):
+ # Read the reservation where the controller picks it up. Acceptance
+ # materializes the snapshot out of the delivery row afterwards, so this
+ # is the moment the recorded authority has to be there.
+ with create_sqlite_engine().connect() as conn:
+ row = message_deliveries.get_delivery(conn, payload["user_message_id"])
+ reserved.append(message_deliveries.delivery_payload(row)["metadata"])
+ _accept_dispatch(payload)
+ return {"status_code": 202, "body": {"ok": True}}
+
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Please take this on.", "dispatch": True},
+ },
+ )
+
+ assert response.status_code == 201
+ # One resolution answered the admission decision, the display author and the
+ # authority the reservation is written under.
+ assert len(resolved) == 1
+ assert appended == [resolved[0]]
+ # The stored event is authored by that same visitor. The public projection
+ # drops the email on the way out, which is why the identity is checked here
+ # and in the reservation rather than in the response body.
+ assert published[0]["payload"]["author"]["email"] == "[email protected]"
+ assert "email" not in response.get_json()["event"]["payload"]["author"]
+
+ snapshot = reserved[0][resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert snapshot["email"] == "[email protected]"
+ assert snapshot["sub"] == "user-2"
+
+
+def test_public_show_page_dispatch_fails_closed_without_a_resolved_visitor(monkeypatch, tmp_path):
+ """PERMISSIONS-027: no resolved visitor, no write — never a fall through to local authority.
+
+ ``ShowSessionEventStore.append`` treats a missing context as "the running
+ invocation answers", which on this process is the local Owner. The share
+ route must therefore refuse before it gets there rather than hand down a
+ ``None`` the store would resolve for it.
+ """
+
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path, paired=True)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ monkeypatch.setattr("vibe.ui_server._show_public_editor_context", lambda: None)
+ monkeypatch.setattr(
+ ShowSessionEventStore,
+ "append",
+ lambda *args, **kwargs: pytest.fail("a write ran without a resolved visitor"),
+ )
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _active_org_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Please take this on.", "dispatch": True},
+ },
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "public_show_events_login_required"
+
+
@pytest.mark.parametrize("event_type", ["assistant.mark.created", "system.annotation.control"])
def test_public_show_page_events_reject_non_human_types(monkeypatch, tmp_path, event_type):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index eb51d2522..8e6331149 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -410,6 +410,7 @@ export const AppWindow: React.FC<{
compact
sessionId={showpageSid}
canManageInstance={capabilities.can_manage_instance}
+ canPinToDock={capabilities.can_chat}
onOpenChange={handleShareOpenChange}
ownerWindowId={win.id}
/>
diff --git a/ui/src/components/apps/ShowPageRoute.tsx b/ui/src/components/apps/ShowPageRoute.tsx
index 9daff6010..33b3f3cec 100644
--- a/ui/src/components/apps/ShowPageRoute.tsx
+++ b/ui/src/components/apps/ShowPageRoute.tsx
@@ -144,6 +144,7 @@ const MobileShowPage: React.FC<{ sessionId: string }> = ({ sessionId }) => {
<ShowPageShareControl
sessionId={sessionId}
canManageInstance={capabilities.can_manage_instance}
+ canPinToDock={capabilities.can_chat}
onOpenChange={setShareOpen}
/>
</div>
diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsx
index b841266f5..b7829fdfe 100644
--- a/ui/src/components/workbench/AgentsPage.test.tsx
+++ b/ui/src/components/workbench/AgentsPage.test.tsx
@@ -1,13 +1,14 @@
/* @vitest-environment jsdom */
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
-import type { VibeAgentBrief, WorkbenchEventHandlers } from '../../context/ApiContext';
+import type { VibeAgentBrief, WorkbenchEventHandlers, WorkbenchProject } from '../../context/ApiContext';
import type { InstanceCapabilities, InstanceRole } from '../../lib/sessionInfo';
import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';
+import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';
import { AgentsPage } from './AgentsPage';
type FakeApi = {
@@ -18,6 +19,8 @@ type FakeApi = {
updateVibeAgent: ReturnType<typeof vi.fn>;
removeVibeAgent: ReturnType<typeof vi.fn>;
getRunningAgents: ReturnType<typeof vi.fn>;
+ listProjects: ReturnType<typeof vi.fn>;
+ createSession: ReturnType<typeof vi.fn>;
connectWorkbenchEvents: ReturnType<typeof vi.fn>;
};
@@ -119,6 +122,8 @@ function makeApi(
updateVibeAgent,
removeVibeAgent,
getRunningAgents: vi.fn().mockResolvedValue({ ok: true, counts: { total: 2 } }),
+ listProjects: vi.fn().mockResolvedValue({ projects: [] }),
+ createSession: vi.fn().mockResolvedValue({ id: 'ses_created' }),
connectWorkbenchEvents: vi.fn((next: WorkbenchEventHandlers) => {
handlers = next;
return vi.fn();
@@ -126,12 +131,18 @@ function makeApi(
};
}
-const MEMBER_CAPABILITIES: InstanceCapabilities = {
- ...OWNER_INSTANCE_CAPABILITIES,
- is_instance_owner: false,
- can_manage_instance: false,
- can_manage_access_members: false,
-};
+const MEMBER_CAPABILITIES = capabilitiesFor('member');
+
+const project = (id: string, canChat: boolean): WorkbenchProject => ({
+ id,
+ scope_id: `proj_${id}`,
+ display_name: `project ${id}`,
+ folder_path: `/tmp/${id}`,
+ created_at: '2026-08-21T00:00:00Z',
+ last_active_at: null,
+ archived: false,
+ capabilities: { can_chat: canChat, has_folder: true },
+});
function renderPage(
api: FakeApi,
@@ -2454,3 +2465,120 @@ describe('AgentsPage reconnect reconciliation', () => {
expect(getVibeAgent.mock.calls.slice(3).some(([name]) => name === 'agent-a')).toBe(false);
});
});
+
+// PERMISSIONS-020. Running an Agent is a use operation; editing its definition
+// is management. These render the capabilities the server projects for each
+// role and follow the click through to the API call it should reach.
+describe('PERMISSIONS-020 AgentsPage Run authority is independent of definition management', () => {
+ const roleTree = (role: InstanceRole) => (
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: true,
+ instanceKind: 'organization',
+ instanceRole: role,
+ capabilities: capabilitiesFor(role),
+ }}
+ >
+ <MemoryRouter initialEntries={['/agents']}>
+ <AgentsPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>
+ );
+
+ const renderAsRole = (api: FakeApi, role: InstanceRole) => {
+ apiRef.current = api;
+ return render(roleTree(role));
+ };
+
+ const agentApi = (agent = brief('agent-a', 'A')) =>
+ makeApi(vi.fn().mockResolvedValue(listResult(agent)), vi.fn().mockResolvedValue(fullAgent(agent, 'prompt')));
+
+ it('lets an editor launch a session from an Agent whose definition stays locked', async () => {
+ const agent = brief('agent-a', 'A');
+ const api = agentApi(agent);
+ api.listProjects.mockResolvedValue({
+ projects: [project('chat-ok', true), project('read-only', false)],
+ });
+ renderAsRole(api, 'editor');
+
+ await waitFor(() => expect(screen.getByText('agents.detail.run')).toBeTruthy());
+ // Management stays denied on the same render that offers Run.
+ expect(screen.queryByText('agents.newAgent')).toBeNull();
+ expect(screen.queryByText('common.delete')).toBeNull();
+ expect(screen.getByText('agents.remoteReadOnly')).toBeTruthy();
+
+ fireEvent.click(screen.getByText('agents.detail.run').closest('button')!);
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByRole('combobox')).toBeTruthy());
+
+ // Only Projects whose own capabilities admit a chat are offered.
+ const select = within(dialog).getByRole('combobox') as HTMLSelectElement;
+ expect([...select.options].map((option) => option.value)).toEqual(['chat-ok']);
+
+ fireEvent.click(within(dialog).getByText('agents.runDialog.open').closest('button')!);
+ await waitFor(() =>
+ expect(api.createSession).toHaveBeenCalledWith({
+ project_id: 'chat-ok',
+ agent_backend: 'codex',
+ agent_name: 'agent-a',
+ agent_id: 'id-agent-a',
+ model: 'gpt-5',
+ reasoning_effort: 'medium',
+ }),
+ );
+ expect(api.updateVibeAgent).not.toHaveBeenCalled();
+ expect(api.removeVibeAgent).not.toHaveBeenCalled();
+ });
+
+ it.each(['member', 'owner'] as const)('keeps Run reachable for %s', async (role) => {
+ const api = agentApi();
+ api.listProjects.mockResolvedValue({ projects: [project('chat-ok', true)] });
+ renderAsRole(api, role);
+
+ await waitFor(() => expect(screen.getByText('agents.detail.run')).toBeTruthy());
+ // The management surface a role above editor keeps.
+ expect(screen.getByText('agents.newAgent')).toBeTruthy();
+ expect(screen.getByText('common.delete')).toBeTruthy();
+ });
+
+ it('offers no Run to a viewer, who may neither chat nor use Agents', async () => {
+ const api = agentApi();
+ renderAsRole(api, 'viewer');
+
+ await waitFor(() => expect(api.getVibeAgent).toHaveBeenCalled());
+ expect(screen.queryByText('agents.detail.run')).toBeNull();
+ expect(screen.queryByText('agents.newAgent')).toBeNull();
+ expect(api.listProjects).not.toHaveBeenCalled();
+ });
+
+ it('closes an open launcher when the Run authority is revoked mid-session', async () => {
+ const api = agentApi();
+ api.listProjects.mockResolvedValue({ projects: [project('chat-ok', true)] });
+ apiRef.current = api;
+ const view = render(roleTree('editor'));
+
+ await waitFor(() => expect(screen.getByText('agents.detail.run')).toBeTruthy());
+ fireEvent.click(screen.getByText('agents.detail.run').closest('button')!);
+ expect(await screen.findByRole('dialog')).toBeTruthy();
+
+ view.rerender(roleTree('viewer'));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(api.createSession).not.toHaveBeenCalled();
+ });
+
+ it('cannot launch when no Project admits this editor', async () => {
+ const api = agentApi();
+ api.listProjects.mockResolvedValue({ projects: [project('read-only', false)] });
+ renderAsRole(api, 'editor');
+
+ await waitFor(() => expect(screen.getByText('agents.detail.run')).toBeTruthy());
+ fireEvent.click(screen.getByText('agents.detail.run').closest('button')!);
+ const dialog = await screen.findByRole('dialog');
+ await waitFor(() => expect(within(dialog).getByText('agents.runDialog.noProject')).toBeTruthy());
+
+ const open = within(dialog).getByText('agents.runDialog.open').closest('button') as HTMLButtonElement;
+ expect(open.disabled).toBe(true);
+ fireEvent.click(open);
+ expect(api.createSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 78df3f650..0ace936b1 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -331,6 +331,10 @@ export const AgentsPage: React.FC = () => {
const visibleTabs = capabilities.can_use_agents ? AGENTS_TAB_ORDER : (['definitions'] as const);
const activeTab = capabilities.can_use_agents ? agentsTab : 'definitions';
const canEditAgents = capabilities.can_manage_agents;
+ // Running an Agent is a use operation, editing its definition is management:
+ // `POST /api/sessions` admits an editor, so Run follows chat + Agent use while
+ // every definition field stays read-only.
+ const canRunAgents = capabilities.can_chat && capabilities.can_use_agents;
// Bulk Agent onboarding is a one-way instance-wide migration and stays Owner
// on the HTTP policy, so it follows owner identity rather than the Agent-CRUD
// capability a member also has: keying the fetch off `can_manage_agents` sent
@@ -1607,6 +1611,7 @@ export const AgentsPage: React.FC = () => {
agent={selected}
isDefault={defaultName === selected.name}
canEdit={canEditAgents}
+ canRun={canRunAgents}
onChange={updateField}
onSetDefault={onSetDefault}
onRename={onRename}
@@ -1882,8 +1887,11 @@ const ImportMenu: React.FC<ImportMenuProps> = ({ onImport, importing }) => {
interface DetailProps {
agent: VibeAgentFull;
isDefault: boolean;
- /** False on remote instances, where every mutating control is unavailable. */
+ /** Definition-management authority: rename, model, prompt, default, delete. */
canEdit: boolean;
+ /** Use authority: start a Project session with this Agent. Independent of
+ * `canEdit` — an editor runs an Agent whose definition they cannot touch. */
+ canRun: boolean;
onChange: (patch: VibeAgentUpdatePayload) => Promise<void>;
onSetDefault: () => Promise<void>;
onRename: (newName: string) => Promise<void>;
@@ -1895,9 +1903,10 @@ interface DetailProps {
// Name → Backend (read-only) → Model (Combobox) → Reasoning effort →
// System Prompt (collapsible) → footer Run / Delete. Name is editable
// for user agents. The backend renames the row and its references atomically;
-// system agents keep their locked identity. On a remote instance `canEdit` is
-// false and the panel degrades to a read-only view of the same fields.
-const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, onChange, onSetDefault, onRename, onDelete, onClose }) => {
+// system agents keep their locked identity. Without `canEdit` the panel degrades
+// to a read-only view of the same fields; Run follows `canRun` instead, so a
+// read-only definition can still be launched by whoever may use it.
+const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, canRun, onChange, onSetDefault, onRename, onDelete, onClose }) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -2486,39 +2495,41 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, on
button was redundant with the top Enable toggle and was
removed. */}
<div className="flex items-center gap-2 pt-2">
+ {canRun && (
+ <Button
+ type="button"
+ variant="outline"
+ size="xs"
+ onClick={() => setRunning(true)}
+ className="border-mint/40 bg-mint-soft text-mint-ink hover:brightness-110"
+ >
+ <Play className="size-3" />
+ {t('agents.detail.run')}
+ </Button>
+ )}
+ <div className="flex-1" />
{canEdit ? (
- <>
+ !system ? (
<Button
type="button"
- variant="outline"
+ variant="destructive-soft"
size="xs"
- onClick={() => setRunning(true)}
- className="border-mint/40 bg-mint-soft text-mint-ink hover:brightness-110"
+ onClick={onDelete}
>
- <Play className="size-3" />
- {t('agents.detail.run')}
+ <Trash2 className="size-3" />
+ {t('common.delete')}
</Button>
- <div className="flex-1" />
- {!system ? (
- <Button
- type="button"
- variant="destructive-soft"
- size="xs"
- onClick={onDelete}
- >
- <Trash2 className="size-3" />
- {t('common.delete')}
- </Button>
- ) : (
- <span className="text-[10px] text-muted">{t('agents.detail.systemLocked')}</span>
- )}
- </>
+ ) : (
+ <span className="text-[10px] text-muted">{t('agents.detail.systemLocked')}</span>
+ )
) : (
<span className="text-[10px] text-muted">{t('agents.remoteReadOnlyHint')}</span>
)}
</div>
- {canEdit && running && <RunAgentDialog agent={agent} onClose={() => setRunning(false)} />}
+ {/* Derived, not latched: losing `canRun` mid-dialog unmounts it in the same
+ render, so a revoked capability cannot leave an open launcher behind. */}
+ {canRun && running && <RunAgentDialog agent={agent} onClose={() => setRunning(false)} />}
{/* Full-screen system-prompt editor — large input + Markdown preview.
Opening from collapsed or expanded both jump straight here. */}
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index f2853fa25..3f9f32aab 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -2824,6 +2824,7 @@ export const ChatPage: React.FC = () => {
canOpenShowPage={canOpenShowPage}
canManageShowPage={canManageShowPage}
canManageInstance={capabilities.can_manage_instance}
+ canPinToDock={capabilities.can_chat}
sessionActions={sessionActions}
titleFieldRef={titleFieldRef}
/>
@@ -3418,6 +3419,7 @@ interface ChatHeaderBarProps {
canOpenShowPage?: boolean;
canManageShowPage?: boolean;
canManageInstance?: boolean;
+ canPinToDock?: boolean;
// Shared session actions, rendered behind the mobile-only ⋯ at the far right.
// Empty (or absent) withdraws the trigger — which is what a read-only session
// yields, since every one of those writes is refused.
@@ -3430,7 +3432,7 @@ interface ChatHeaderBarProps {
// which renders the header alone rather than mounting the whole page. Note the
// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the
// read-only rendering is reachable without an ApiProvider.
-export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, patchSaving, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, showPageAccess = null, canOpenShowPage = true, canManageShowPage = true, canManageInstance = false, sessionActions, titleFieldRef }) => {
+export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, patchSaving, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, writable = readOnlyReason === null, showPageAccess = null, canOpenShowPage = true, canManageShowPage = true, canManageInstance = false, canPinToDock = false, sessionActions, titleFieldRef }) => {
const { t } = useTranslation();
const readOnly = !writable;
const sessionReadOnly = readOnlyReason !== null;
@@ -3584,6 +3586,7 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
sessionId={session.id}
initialAccess={showPageAccess}
canManageInstance={canManageInstance}
+ canPinToDock={canPinToDock}
onPayloadChange={onShowPageVisibilityChange}
onOpenChange={onShareOpenChange}
/>
diff --git a/ui/src/components/workbench/HarnessPage.banner.test.tsx b/ui/src/components/workbench/HarnessPage.banner.test.tsx
new file mode 100644
index 000000000..1315ff29c
--- /dev/null
+++ b/ui/src/components/workbench/HarnessPage.banner.test.tsx
@@ -0,0 +1,151 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
+import type { InstanceRole } from '../../lib/sessionInfo';
+import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';
+import { HarnessPage } from './HarnessPage';
+
+// PERMISSIONS-022 — the global background-work banner is one shared instance
+// preference behind the member-tier `PUT /api/workbench/prefs`, while the
+// Harness page itself is an editor surface. The switch has to read as read-only
+// below member instead of optimistically flipping and silently reverting.
+
+type FakeApi = {
+ getWorkbenchPrefs: ReturnType<typeof vi.fn>;
+ setBackgroundWorkBannerEnabled: ReturnType<typeof vi.fn>;
+ getHarnessBootstrap: ReturnType<typeof vi.fn>;
+ listVibeAgents: ReturnType<typeof vi.fn>;
+ connectWorkbenchEvents: ReturnType<typeof vi.fn>;
+};
+
+const apiRef = vi.hoisted(() => ({ current: null as FakeApi | null }));
+
+vi.mock('../../context/ApiContext', async () => {
+ const actual = await vi.importActual<typeof import('../../context/ApiContext')>('../../context/ApiContext');
+ return { ...actual, useApi: () => apiRef.current };
+});
+vi.mock('./CapabilityTabs', () => ({ CapabilityTabs: () => null }));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const emptyCounts = { tasks: {}, watches: {}, runs: {} };
+
+const makeApi = (bannerEnabled = true): FakeApi => ({
+ getWorkbenchPrefs: vi.fn().mockResolvedValue({ background_work_banner_enabled: bannerEnabled }),
+ setBackgroundWorkBannerEnabled: vi
+ .fn()
+ .mockImplementation(async (next: boolean) => ({ background_work_banner_enabled: next })),
+ getHarnessBootstrap: vi.fn().mockResolvedValue({
+ counts: emptyCounts,
+ page: { tasks: [], counts: {}, has_more: false },
+ }),
+ listVibeAgents: vi.fn().mockResolvedValue({ ok: true, agents: [], default_agent_name: null }),
+ connectWorkbenchEvents: vi.fn().mockReturnValue(() => {}),
+});
+
+const renderAsRole = (role: InstanceRole, api: FakeApi) => {
+ apiRef.current = api;
+ return render(
+ <I18nextProvider i18n={i18n}>
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: true,
+ instanceKind: 'organization',
+ instanceRole: role,
+ capabilities: capabilitiesFor(role),
+ }}
+ >
+ <MemoryRouter initialEntries={['/harness']}>
+ <HarnessPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>
+ </I18nextProvider>,
+ );
+};
+
+const bannerSwitch = () =>
+ screen.getByRole('switch', { name: en.harness.bannerToggle.title }) as HTMLButtonElement;
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ apiRef.current = null;
+});
+
+describe('PERMISSIONS-022 HarnessPage background-work banner follows instance-preference authority', () => {
+ it('leaves the switch read-only for an editor and attempts no write', async () => {
+ const api = makeApi();
+ renderAsRole('editor', api);
+
+ // The page itself still loads: Harness is an editor surface.
+ await waitFor(() => expect(api.getHarnessBootstrap).toHaveBeenCalled());
+ await waitFor(() => expect(api.getWorkbenchPrefs).toHaveBeenCalled());
+
+ const control = bannerSwitch();
+ expect(control.disabled).toBe(true);
+ expect(screen.getByText(en.harness.bannerToggle.readOnlyHint)).toBeTruthy();
+ expect(screen.queryByText(en.harness.bannerToggle.description)).toBeNull();
+
+ fireEvent.click(control);
+ expect(api.setBackgroundWorkBannerEnabled).not.toHaveBeenCalled();
+ // No optimistic flip either — the rendered state still mirrors the server.
+ expect(control.getAttribute('aria-checked')).toBe('true');
+ });
+
+ it.each<InstanceRole>(['member', 'owner'])('lets a %s persist the shared preference', async (role) => {
+ const api = makeApi();
+ renderAsRole(role, api);
+
+ await waitFor(() => expect(api.getWorkbenchPrefs).toHaveBeenCalled());
+ const control = bannerSwitch();
+ await waitFor(() => expect(control.getAttribute('aria-checked')).toBe('true'));
+ expect(control.disabled).toBe(false);
+ expect(screen.getByText(en.harness.bannerToggle.description)).toBeTruthy();
+
+ fireEvent.click(control);
+ await waitFor(() => expect(api.setBackgroundWorkBannerEnabled).toHaveBeenCalledWith(false));
+ await waitFor(() => expect(control.getAttribute('aria-checked')).toBe('false'));
+ });
+
+ it('refuses the write in the same render a member is downgraded to editor', async () => {
+ const api = makeApi();
+ const view = renderAsRole('member', api);
+ await waitFor(() => expect(api.getWorkbenchPrefs).toHaveBeenCalled());
+ expect(bannerSwitch().disabled).toBe(false);
+
+ view.rerender(
+ <I18nextProvider i18n={i18n}>
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: true,
+ instanceKind: 'organization',
+ instanceRole: 'editor',
+ capabilities: capabilitiesFor('editor'),
+ }}
+ >
+ <MemoryRouter initialEntries={['/harness']}>
+ <HarnessPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>
+ </I18nextProvider>,
+ );
+
+ const control = bannerSwitch();
+ expect(control.disabled).toBe(true);
+ fireEvent.click(control);
+ expect(api.setBackgroundWorkBannerEnabled).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/workbench/HarnessPage.definitionsStream.test.tsx b/ui/src/components/workbench/HarnessPage.definitionsStream.test.tsx
new file mode 100644
index 000000000..8f9211727
--- /dev/null
+++ b/ui/src/components/workbench/HarnessPage.definitionsStream.test.tsx
@@ -0,0 +1,187 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// PERMISSIONS-016 — the Harness page below runtime management. `runs.updated`
+// already woke it; `definitions.updated` is admitted at the same Editor tier and
+// reduced to the same bare frame, but nothing listened for it by name, so a
+// definition created, paused or retired anywhere else left this page stale until
+// an unrelated run happened to fire. This drives the REAL stream: a named
+// EventSource frame carrying `data: {}`, through the provider's own listener and
+// read cache, into the page's refetch -- with no runs event and no reconnect.
+
+const apiFetch = vi.hoisted(() => vi.fn());
+
+vi.mock('../../lib/apiFetch', () => ({
+ apiFetch,
+ isApiFetchDeadlineAbort: () => false,
+ ensureCsrfToken: async () => 'csrf-not-real',
+ withApiDeadline: async <T,>(run: (signal: AbortSignal) => Promise<T>) =>
+ run(new AbortController().signal),
+ recoverRemoteAuthFromSessionProbe: async () => {},
+}));
+vi.mock('./CapabilityTabs', () => ({ CapabilityTabs: () => null }));
+
+import en from '../../i18n/en.json';
+import { ApiProvider } from '../../context/ApiContext';
+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
+import { ToastContext } from '../../context/ToastContext';
+import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';
+import { HarnessPage } from './HarnessPage';
+
+/** Enough of EventSource to be fed named frames; jsdom ships none. */
+class FakeEventSource {
+ static readonly OPEN = 1;
+ static instances: FakeEventSource[] = [];
+
+ readyState = FakeEventSource.OPEN;
+ closed = false;
+ onerror: ((event: Event) => void) | null = null;
+ private readonly listeners = new Map<string, Set<(event: MessageEvent) => void>>();
+
+ constructor(readonly url: string) {
+ FakeEventSource.instances.push(this);
+ }
+
+ addEventListener(type: string, listener: (event: MessageEvent) => void): void {
+ const bucket = this.listeners.get(type) ?? new Set();
+ bucket.add(listener);
+ this.listeners.set(type, bucket);
+ }
+
+ removeEventListener(type: string, listener: (event: MessageEvent) => void): void {
+ this.listeners.get(type)?.delete(listener);
+ }
+
+ close(): void {
+ this.closed = true;
+ this.readyState = 2;
+ }
+
+ emit(type: string, data: unknown): void {
+ const event = { data: JSON.stringify(data) } as MessageEvent;
+ for (const listener of [...(this.listeners.get(type) ?? [])]) listener(event);
+ }
+
+ static latest(): FakeEventSource {
+ const source = FakeEventSource.instances.at(-1);
+ if (!source) throw new Error('no EventSource was opened');
+ return source;
+ }
+}
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const HARNESS_BOOTSTRAP = '/api/harness/bootstrap';
+
+const jsonFor = (path: string) => {
+ if (path.startsWith(HARNESS_BOOTSTRAP)) {
+ return {
+ counts: { tasks: {}, watches: {}, runs: {} },
+ page: { tasks: [], counts: {}, has_more: false },
+ };
+ }
+ if (path.startsWith('/api/workbench/prefs')) return { background_work_banner_enabled: false };
+ return { ok: true, agents: [], default_agent_name: null };
+};
+
+const harnessReads = () =>
+ apiFetch.mock.calls.filter(([path]) => String(path).startsWith(HARNESS_BOOTSTRAP)).length;
+
+/** What the server sends below runtime management: the type, and nothing else. */
+const emitBareFrame = (type: string) => FakeEventSource.latest().emit(type, { type, data: {} });
+
+const mountAsEditor = () =>
+ render(
+ <ToastContext.Provider value={{ showToast: () => {} }}>
+ <ApiProvider>
+ <I18nextProvider i18n={i18n}>
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: true,
+ instanceKind: 'organization',
+ instanceRole: 'editor',
+ capabilities: capabilitiesFor('editor'),
+ }}
+ >
+ <MemoryRouter initialEntries={['/harness']}>
+ <HarnessPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>
+ </I18nextProvider>
+ </ApiProvider>
+ </ToastContext.Provider>,
+ );
+
+/** Mount, then complete the handshake a real connect would, with a healthy leg. */
+const mountConnected = async () => {
+ const view = mountAsEditor();
+ await waitFor(() => expect(FakeEventSource.instances.length).toBe(1));
+ await act(async () => {
+ FakeEventSource.latest().emit('connected', { sub_id: 1, interval_ms: 25_000 });
+ FakeEventSource.latest().emit('workbench.events.bridge.status', {
+ type: 'workbench.events.bridge.status',
+ data: { connected: true },
+ });
+ });
+ await waitFor(() => expect(harnessReads()).toBeGreaterThan(0));
+ return view;
+};
+
+beforeEach(() => {
+ apiFetch.mockReset();
+ apiFetch.mockImplementation(async (path: string) => ({
+ ok: true,
+ status: 200,
+ json: async () => jsonFor(String(path)),
+ }));
+ FakeEventSource.instances = [];
+ vi.stubGlobal('EventSource', FakeEventSource);
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('PERMISSIONS-016 HarnessPage wakes on the bare definitions.updated frame', () => {
+ it('refetches the Harness view from the named signal alone', async () => {
+ await mountConnected();
+ const before = harnessReads();
+
+ await act(async () => emitBareFrame('definitions.updated'));
+
+ // A second network read, not the 1.5s read cache answering itself: the
+ // listener has to invalidate `/api/harness` for this to be reachable.
+ await waitFor(() => expect(harnessReads()).toBeGreaterThan(before));
+ // No runs event, and the same socket throughout -- the refetch came from
+ // this frame rather than from an adjacent signal or a reconnect.
+ expect(FakeEventSource.instances.length).toBe(1);
+ });
+
+ it('keeps waking on runs.updated and stops when the page unmounts', async () => {
+ const view = await mountConnected();
+ const before = harnessReads();
+
+ await act(async () => emitBareFrame('runs.updated'));
+ await waitFor(() => expect(harnessReads()).toBeGreaterThan(before));
+
+ const afterRuns = harnessReads();
+ view.unmount();
+ await act(async () => {
+ if (!FakeEventSource.latest().closed) emitBareFrame('definitions.updated');
+ });
+ expect(harnessReads()).toBe(afterRuns);
+ });
+});
diff --git a/ui/src/components/workbench/HarnessPage.events.test.tsx b/ui/src/components/workbench/HarnessPage.events.test.tsx
new file mode 100644
index 000000000..c8a5f7a4b
--- /dev/null
+++ b/ui/src/components/workbench/HarnessPage.events.test.tsx
@@ -0,0 +1,107 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
+import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';
+import { HarnessPage } from './HarnessPage';
+
+// PERMISSIONS-016 — `runs.updated` is admitted at the Editor tier that owns
+// `/api/harness/*`, and below runtime management the controller reduces the
+// frame to its type alone. The Harness page has no polling fallback, so the
+// stream is the only thing that wakes it: this drives the real page from a bare
+// frame rather than asserting on a stream stub that never emits.
+
+type WorkbenchEventHandlers = { onRunsUpdated?: (data: unknown) => void };
+
+const eventHandlers: WorkbenchEventHandlers[] = [];
+
+type FakeApi = {
+ getWorkbenchPrefs: ReturnType<typeof vi.fn>;
+ getHarnessBootstrap: ReturnType<typeof vi.fn>;
+ listVibeAgents: ReturnType<typeof vi.fn>;
+ connectWorkbenchEvents: ReturnType<typeof vi.fn>;
+};
+
+const apiRef = vi.hoisted(() => ({ current: null as FakeApi | null }));
+
+vi.mock('../../context/ApiContext', async () => {
+ const actual = await vi.importActual<typeof import('../../context/ApiContext')>('../../context/ApiContext');
+ return { ...actual, useApi: () => apiRef.current };
+});
+vi.mock('./CapabilityTabs', () => ({ CapabilityTabs: () => null }));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const makeApi = (): FakeApi => ({
+ getWorkbenchPrefs: vi.fn().mockResolvedValue({ background_work_banner_enabled: false }),
+ getHarnessBootstrap: vi.fn().mockResolvedValue({
+ counts: { tasks: {}, watches: {}, runs: {} },
+ page: { tasks: [], counts: {}, has_more: false },
+ }),
+ listVibeAgents: vi.fn().mockResolvedValue({ ok: true, agents: [], default_agent_name: null }),
+ connectWorkbenchEvents: vi.fn((handlers: WorkbenchEventHandlers) => {
+ eventHandlers.push(handlers);
+ return () => {
+ const at = eventHandlers.indexOf(handlers);
+ if (at >= 0) eventHandlers.splice(at, 1);
+ };
+ }),
+});
+
+const renderAsEditor = (api: FakeApi) => {
+ apiRef.current = api;
+ return render(
+ <I18nextProvider i18n={i18n}>
+ <InstanceAuthorizationContext.Provider
+ value={{
+ remote: true,
+ instanceKind: 'organization',
+ instanceRole: 'editor',
+ capabilities: capabilitiesFor('editor'),
+ }}
+ >
+ <MemoryRouter initialEntries={['/harness']}>
+ <HarnessPage />
+ </MemoryRouter>
+ </InstanceAuthorizationContext.Provider>
+ </I18nextProvider>,
+ );
+};
+
+afterEach(() => {
+ cleanup();
+ eventHandlers.length = 0;
+ vi.restoreAllMocks();
+ apiRef.current = null;
+});
+
+describe('PERMISSIONS-016 HarnessPage wakes an Editor on the bare runs.updated frame', () => {
+ it('reloads the Harness view from the signal alone', async () => {
+ const api = makeApi();
+ renderAsEditor(api);
+
+ await waitFor(() => expect(api.getHarnessBootstrap).toHaveBeenCalled());
+ const before = api.getHarnessBootstrap.mock.calls.length;
+ const agentsBefore = api.listVibeAgents.mock.calls.length;
+
+ await act(async () => {
+ for (const handler of [...eventHandlers]) handler.onRunsUpdated?.({});
+ });
+
+ await waitFor(() => expect(api.getHarnessBootstrap.mock.calls.length).toBeGreaterThan(before));
+ // The Agent catalog the rows are labelled from refreshes on the same signal.
+ await waitFor(() => expect(api.listVibeAgents.mock.calls.length).toBeGreaterThan(agentsBefore));
+ });
+});
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 684d67e03..79f1d1060 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -32,6 +32,7 @@ import clsx from 'clsx';
import { Link, useSearchParams } from 'react-router-dom';
import { useApi } from '../../context/ApiContext';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { DEFAULT_TAB, harnessEmptyStateKey, harnessTabFromParam, TAB_ORDER, type TabKey } from './harnessTabs';
import type {
HarnessDefinitionCounts,
@@ -171,6 +172,11 @@ type Selection =
export const HarnessPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
+ // Harness is an editor surface, but this banner is one shared instance
+ // preference: `PUT /api/workbench/prefs` is member-tier, so below that the
+ // switch must read as read-only instead of silently reverting.
+ const { capabilities } = useInstanceAuthorization();
+ const canManageBanner = capabilities.can_manage_instance;
const now = useVisibleNow();
const [tab, setTab] = useState<TabKey>(DEFAULT_TAB);
const [tasks, setTasks] = useState<HarnessTask[]>([]);
@@ -307,6 +313,9 @@ export const HarnessPage: React.FC = () => {
const onToggleBanner = useCallback(
async (next: boolean) => {
+ // Derived from the live capability, so a mid-session revocation refuses the
+ // write in the same render the switch goes disabled.
+ if (!canManageBanner) return;
setBannerEnabled(next); // optimistic
setBannerPending(true);
try {
@@ -318,7 +327,7 @@ export const HarnessPage: React.FC = () => {
setBannerPending(false);
}
},
- [api],
+ [api, canManageBanner],
);
const clearSessionFilter = useCallback(() => {
@@ -416,6 +425,12 @@ export const HarnessPage: React.FC = () => {
useEffect(() => {
return api.connectWorkbenchEvents({
+ // A definition row changed somewhere else -- another surface, the CLI, or
+ // the scheduler retiring a schedule. The list this page shows IS that row,
+ // so it refetches; the Agent catalog is unaffected by a definition edit.
+ onDefinitionsUpdated: () => {
+ void refresh();
+ },
onRunsUpdated: () => {
void refresh();
void refreshAgents();
@@ -638,12 +653,14 @@ export const HarnessPage: React.FC = () => {
<div className="flex items-center justify-between gap-4 rounded-xl border border-border-strong bg-surface px-4 py-3">
<div className="min-w-0">
<div className="text-sm font-semibold text-foreground">{t('harness.bannerToggle.title')}</div>
- <div className="text-[12px] text-muted">{t('harness.bannerToggle.description')}</div>
+ <div className="text-[12px] text-muted">
+ {canManageBanner ? t('harness.bannerToggle.description') : t('harness.bannerToggle.readOnlyHint')}
+ </div>
</div>
<Switch
checked={bannerEnabled}
onCheckedChange={onToggleBanner}
- disabled={bannerPending}
+ disabled={bannerPending || !canManageBanner}
label={t('harness.bannerToggle.title')}
/>
</div>
diff --git a/ui/src/components/workbench/ShowPageShareControl.test.tsx b/ui/src/components/workbench/ShowPageShareControl.test.tsx
index 855b2b1ee..20d592188 100644
--- a/ui/src/components/workbench/ShowPageShareControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.test.tsx
@@ -6,6 +6,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import en from '../../i18n/en.json';
+import { showDockId } from '../../context/dockDoc';
import type { ShowPageAccess } from '../../lib/showPageAccess';
import { ShowPageShareControl } from './ShowPageShareControl';
@@ -45,16 +46,16 @@ vi.mock('@/context/ApiContext', () => ({
useApi: () => api,
}));
-vi.mock('../../context/DockContext', () => ({
- useDock: () => ({
- isDocked: vi.fn(() => false),
- isPinned: vi.fn(() => false),
- dock: vi.fn(),
- pin: vi.fn(),
- undock: vi.fn(),
- }),
+const dock = vi.hoisted(() => ({
+ isDocked: vi.fn(() => false),
+ isPinned: vi.fn(() => false),
+ dock: vi.fn(),
+ pin: vi.fn(),
+ undock: vi.fn(),
}));
+vi.mock('../../context/DockContext', () => ({ useDock: () => dock }));
+
vi.mock('../useShowPages', () => ({
useShowPageInventory: () => ({
pages: [],
@@ -68,6 +69,8 @@ beforeEach(() => {
permissionsApi.getPermissions.mockReset();
permissionsApi.getResourceAccess.mockReset();
permissionsApi.updateResourceAccess.mockReset();
+ dock.isDocked.mockReturnValue(false);
+ dock.isPinned.mockReturnValue(false);
});
afterEach(() => {
@@ -710,3 +713,74 @@ describe('ShowPageShareControl request surface', () => {
expect(mutatingCallsSoFar()).toEqual([]);
});
});
+
+// PERMISSIONS-021. `/api/dock/pins` is an editor-tier route, so the Dock row
+// follows page use, not instance management. PM verified both verbs over signed
+// HTTP: an Editor pins and unpins with a persisted readback, a Viewer is denied.
+describe('PERMISSIONS-021 ShowPageShareControl Dock pin authority', () => {
+ const page = {
+ session_id: 'ses-1',
+ visibility: 'private',
+ active_url: '/show/ses-1/',
+ share_id: null,
+ url_available: true,
+ offline: false,
+ title: 'Release notes',
+ };
+
+ const renderShare = (props: { canPinToDock?: boolean; canUse?: boolean } = {}) => {
+ const access = showPageAccess({ can_use: props.canUse !== false, can_manage: false });
+ api.getShowPageAccess.mockResolvedValue(access);
+ api.getShowPage.mockResolvedValue(page);
+ render(
+ <I18nextProvider i18n={i18n}>
+ <ShowPageShareControl
+ sessionId="ses-1"
+ initialAccess={access}
+ canPinToDock={props.canPinToDock ?? true}
+ />
+ </I18nextProvider>,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));
+ };
+
+ it('pins a page for a user who may use it but may not manage the instance', async () => {
+ renderShare();
+
+ const toggle = await screen.findByRole('switch', { name: 'Pin to Dock' });
+ fireEvent.click(toggle);
+
+ expect(dock.pin).toHaveBeenCalledWith('ses-1');
+ expect(dock.undock).not.toHaveBeenCalled();
+ });
+
+ it('unpins the same page and reports it as docked', async () => {
+ dock.isDocked.mockReturnValue(true);
+ dock.isPinned.mockReturnValue(true);
+ renderShare();
+
+ expect(await screen.findByText(/Pinned — “Release notes” is in your Dock/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('switch', { name: 'Pin to Dock' }));
+
+ expect(dock.undock).toHaveBeenCalledWith(showDockId('ses-1'));
+ expect(dock.pin).not.toHaveBeenCalled();
+ });
+
+ it('offers no Dock control to a role that cannot reach the pins route', async () => {
+ renderShare({ canPinToDock: false });
+
+ // The share link still loads, so this is the Dock row being withheld, not an
+ // unreadable page.
+ await waitFor(() => expect(screen.getByDisplayValue(/\/show\/ses-1\//)).toBeTruthy());
+ expect(screen.queryByRole('switch', { name: 'Pin to Dock' })).toBeNull();
+ expect(dock.pin).not.toHaveBeenCalled();
+ });
+
+ it('withholds the Dock control when page use itself is revoked', async () => {
+ renderShare({ canUse: false });
+
+ await waitFor(() => expect(api.getShowPageAccess).toHaveBeenCalled());
+ expect(screen.queryByRole('switch', { name: 'Pin to Dock' })).toBeNull();
+ expect(api.getShowPage).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index dbbbabd8b..8d4a525e3 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -20,6 +20,9 @@ export const ShowPageShareControl: React.FC<{
sessionId: string;
initialAccess?: ShowPageAccess | null;
canManageInstance?: boolean;
+ /** Dock pin/undock authority. `/api/dock/pins` is an editor-tier route, so
+ * this is deliberately NOT `canManageInstance`. */
+ canPinToDock?: boolean;
onPayloadChange?: (payload: ShowPageLinkInfo) => void;
onOpenChange?: (open: boolean) => void;
compact?: boolean;
@@ -28,6 +31,7 @@ export const ShowPageShareControl: React.FC<{
sessionId,
initialAccess = null,
canManageInstance = false,
+ canPinToDock = false,
onPayloadChange,
onOpenChange,
compact = false,
@@ -320,7 +324,7 @@ export const ShowPageShareControl: React.FC<{
</div>
) : null}
- {payload && canManageInstance ? (
+ {payload && canPinToDock ? (
<div className="border-t border-border pt-3">
<div className="flex items-center gap-3">
<span className="grid size-9 shrink-0 place-items-center rounded-md border border-border bg-foreground/[0.03] text-cyan-ink">
diff --git a/ui/src/components/workbench/VaultsPage.test.tsx b/ui/src/components/workbench/VaultsPage.test.tsx
index 5adf1c4a4..8d0da8920 100644
--- a/ui/src/components/workbench/VaultsPage.test.tsx
+++ b/ui/src/components/workbench/VaultsPage.test.tsx
@@ -2,7 +2,7 @@
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
@@ -10,10 +10,14 @@ import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizatio
import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';
import { VaultsPage } from './VaultsPage';
+type WorkbenchEventHandlers = { onVaultsUpdated?: (data: unknown) => void };
+
+const eventHandlers = vi.hoisted(() => [] as WorkbenchEventHandlers[]);
const api = vi.hoisted(() => ({
connectWorkbenchEvents: vi.fn(() => () => undefined),
getVaultAudit: vi.fn(),
getVaultGrants: vi.fn(),
+ getVaultRequests: vi.fn(),
listVaultSecrets: vi.fn(),
}));
const showToast = vi.hoisted(() => vi.fn());
@@ -80,6 +84,15 @@ function renderPage(context = remoteOwner) {
}
beforeEach(() => {
+ eventHandlers.length = 0;
+ api.connectWorkbenchEvents.mockImplementation((handlers: WorkbenchEventHandlers) => {
+ eventHandlers.push(handlers);
+ return () => {
+ const at = eventHandlers.indexOf(handlers);
+ if (at >= 0) eventHandlers.splice(at, 1);
+ };
+ });
+ api.getVaultRequests.mockResolvedValue({ requests: [] });
api.listVaultSecrets.mockResolvedValue({ secrets: [] });
api.getVaultGrants.mockResolvedValue({ grants: [] });
api.getVaultAudit.mockResolvedValue({
@@ -116,3 +129,26 @@ describe('VaultsPage remote audit history', () => {
expect(screen.queryByText('vaults.remoteReadOnly')).toBeNull();
});
});
+
+// PERMISSIONS-016 — `vaults.updated` is admitted at the Editor tier that owns
+// the endpoint it announces, and below runtime management the controller reduces
+// the frame to its type alone. The pending-requests list is the consumer that
+// has to wake on it, so it is driven here through the real page rather than
+// asserted on the stream stub.
+describe('PERMISSIONS-016 VaultsPage wakes an Editor on the bare vaults.updated frame', () => {
+ it('refetches pending requests from the signal alone', async () => {
+ renderPage(activeOrgMember);
+ await waitFor(() => expect(api.getVaultRequests).toHaveBeenCalled());
+ const before = api.getVaultRequests.mock.calls.length;
+
+ await act(async () => {
+ for (const handler of [...eventHandlers]) handler.onVaultsUpdated?.({});
+ });
+
+ await waitFor(() => expect(api.getVaultRequests.mock.calls.length).toBeGreaterThan(before));
+ // The frame carried no secret name; the refetch still asks for this Editor's
+ // own pending scope.
+ const [query] = api.getVaultRequests.mock.calls.at(-1) ?? [];
+ expect(query).toMatchObject({ status: 'pending' });
+ });
+});
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index fc8712d2d..d9d2159da 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1261,6 +1261,11 @@ export type WorkbenchEventHandlers = {
onSessionStatus?: (data: { session_id: string; agent_status: 'idle' | 'running' | 'failed' }) => void;
// The send-while-busy queue for a session changed (enqueue / flush / remove).
onQueueUpdated?: (data: { session_id: string }) => void;
+ // A Task / Watch definition was created, edited, enabled, paused or removed.
+ // Instance-scoped like the two below, and `definition_type` is a hint, not a
+ // filter: below runtime management the server reduces the frame to `{}`, so a
+ // consumer that reads the field must still refetch when it is absent.
+ onDefinitionsUpdated?: (data: { definition_type?: string }) => void;
onRunsUpdated?: (data: {
run_id: string;
status: HarnessRunStatus;
@@ -3244,6 +3249,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
handlers.onQueueUpdated?.(envelope.data);
});
});
+ source.addEventListener('definitions.updated', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{ definition_type?: string }>(e.data);
+ if (!envelope) return;
+ clearReadCacheMatching((path) => path.startsWith('/api/harness'));
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onDefinitionsUpdated?.(envelope.data);
+ });
+ });
source.addEventListener('runs.updated', (e: MessageEvent) => {
const envelope = parseWorkbenchEnvelope<{
run_id: string;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fcd306603..358b695a5 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3886,7 +3886,8 @@
"filtered": "{{shown}}/{{total}}",
"bannerToggle": {
"title": "Background task banner",
- "description": "Show in-progress background tasks at the bottom of chats."
+ "description": "Show in-progress background tasks at the bottom of chats.",
+ "readOnlyHint": "This banner is a shared instance setting; your role cannot change it."
},
"sessionFilter": {
"chip": "Only: this session {{id}}",
diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.ts
index 90c046f43..23258ccb9 100644
--- a/ui/src/i18n/keyCoverage.test.ts
+++ b/ui/src/i18n/keyCoverage.test.ts
@@ -849,6 +849,7 @@ const NON_KEY_LITERALS = [
// Event-channel names. `ApiContext.tsx` publishes and subscribes by these.
'authorization.changed',
+ 'definitions.updated',
'inbox.session.updated',
'inbox.unread.changed',
'message.new',
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 9a53c3599..816a1295b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3886,7 +3886,8 @@
"filtered": "{{shown}}/{{total}}",
"bannerToggle": {
"title": "后台任务横幅",
- "description": "在会话底部显示进行中的后台任务。"
+ "description": "在会话底部显示进行中的后台任务。",
+ "readOnlyHint": "该横幅是实例共享设置,当前角色无法修改。"
},
"sessionFilter": {
"chip": "仅看:本会话 {{id}}",
@@ -5133,7 +5134,7 @@
},
"roles": {
"owner": "所有者",
- "member": "成员",
+ "member": "管理者",
"editor": "编辑者",
"viewer": "查看者"
},
diff --git a/ui/src/lib/testing/instanceRoleCapabilities.ts b/ui/src/lib/testing/instanceRoleCapabilities.ts
new file mode 100644
index 000000000..4ff6d0469
--- /dev/null
+++ b/ui/src/lib/testing/instanceRoleCapabilities.ts
@@ -0,0 +1,56 @@
+/**
+ * Test-only mirror of the server capability projection
+ * (`AuthorizationContext.capability_projection` in `vibe/authorization.py`).
+ *
+ * The Web UI never derives capabilities from a role — the server projects them
+ * and `normalizeSessionInfo` only copies the bits through — so a component test
+ * that renders "an Editor" has to state the same bits the server would have
+ * sent. Stating them once keeps every permission test arguing against one
+ * description of the roles instead of four hand-written ones.
+ *
+ * `tests/test_instance_authorization.py` is the anchor: it freezes the viewer
+ * and editor rows bitwise and defines member as owner minus member management.
+ * A capability added there must be added here.
+ */
+import {
+ DENIED_INSTANCE_CAPABILITIES,
+ OWNER_INSTANCE_CAPABILITIES,
+ type InstanceCapabilities,
+ type InstanceRole,
+} from '../sessionInfo';
+
+/** Read the instance and open Show Pages; no chat and no resource use. */
+const VIEWER_CAPABILITIES: InstanceCapabilities = {
+ ...DENIED_INSTANCE_CAPABILITIES,
+ can_read_instance: true,
+ can_use_show_pages: true,
+};
+
+/** Viewer plus the use authorities: chat, Agents, Skills, Vault, files, terminal.
+ * Every `can_manage_*` bit stays false — using a resource is not managing it. */
+const EDITOR_CAPABILITIES: InstanceCapabilities = {
+ ...VIEWER_CAPABILITIES,
+ can_chat: true,
+ can_use_agents: true,
+ can_use_skills: true,
+ can_use_vault_secrets: true,
+ can_use_terminal_files: true,
+ can_use_terminal: true,
+ can_use_files: true,
+};
+
+/** Owner minus member management and the owner flag itself. */
+const MEMBER_CAPABILITIES: InstanceCapabilities = {
+ ...OWNER_INSTANCE_CAPABILITIES,
+ is_instance_owner: false,
+ can_manage_access_members: false,
+};
+
+export const ROLE_CAPABILITIES: Record<InstanceRole, InstanceCapabilities> = {
+ viewer: VIEWER_CAPABILITIES,
+ editor: EDITOR_CAPABILITIES,
+ member: MEMBER_CAPABILITIES,
+ owner: OWNER_INSTANCE_CAPABILITIES,
+};
+
+export const capabilitiesFor = (role: InstanceRole): InstanceCapabilities => ROLE_CAPABILITIES[role];
diff --git a/ui/src/lib/useVaultRequestRefresh.test.ts b/ui/src/lib/useVaultRequestRefresh.test.ts
index 600b06183..a6c71e8e1 100644
--- a/ui/src/lib/useVaultRequestRefresh.test.ts
+++ b/ui/src/lib/useVaultRequestRefresh.test.ts
@@ -1,6 +1,67 @@
-import { describe, expect, it } from 'vitest';
+/* @vitest-environment jsdom */
-import { shouldPollVaultRequests } from './useVaultRequestRefresh';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { shouldPollVaultRequests, useVaultRequestRefresh } from './useVaultRequestRefresh';
+
+type Handlers = {
+ onConnected?: () => void;
+ onEventBridgeStatus?: (data: { connected: boolean }) => void;
+ onError?: () => void;
+ onVaultsUpdated?: (data: unknown) => void;
+};
+
+const handlers: Handlers[] = [];
+
+const connectWorkbenchEvents = vi.fn((next: Handlers) => {
+ handlers.push(next);
+ return () => {
+ const at = handlers.indexOf(next);
+ if (at >= 0) handlers.splice(at, 1);
+ };
+});
+
+vi.mock('@/context/ApiContext', () => ({
+ useApi: () => ({ connectWorkbenchEvents }),
+}));
+
+const POLL_INTERVAL_MS = 5000;
+
+const settle = async () => {
+ await act(async () => {
+ await Promise.resolve();
+ });
+};
+
+const advance = async (ms: number) => {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms);
+ });
+};
+
+const bridgeReports = async (connected: boolean) => {
+ await act(async () => {
+ for (const handler of [...handlers]) handler.onEventBridgeStatus?.({ connected });
+ });
+};
+
+/** The frame an editor actually receives: the event type, and nothing else. */
+const bareVaultsUpdated = async () => {
+ await act(async () => {
+ for (const handler of [...handlers]) handler.onVaultsUpdated?.({});
+ });
+};
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ handlers.length = 0;
+ connectWorkbenchEvents.mockClear();
+});
describe('Vault request refresh mode', () => {
it('polls only while the controller event bridge is unavailable', () => {
@@ -8,3 +69,56 @@ describe('Vault request refresh mode', () => {
expect(shouldPollVaultRequests(true)).toBe(false);
});
});
+
+// PERMISSIONS-016 — `vaults.updated` is admitted at the Editor tier that owns
+// the endpoint it announces, and the frame an Editor receives carries no secret
+// name or session id. So the refresh the page depends on has to survive on the
+// signal alone. The hook is driven here, not its predicate: a stream that never
+// emits would satisfy the assertion above and still leave the page asleep.
+describe('PERMISSIONS-016 Vault request refresh consumes the bare event', () => {
+ it('stops polling once the bridge is healthy and refetches on the event alone', async () => {
+ const refresh = vi.fn().mockResolvedValue(undefined);
+ renderHook(() => useVaultRequestRefresh(refresh));
+
+ // The immediate fallback tick is the initial snapshot.
+ await settle();
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ await bridgeReports(true);
+ await advance(POLL_INTERVAL_MS * 3);
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ await bareVaultsUpdated();
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('resumes the degraded poll when the bridge reports itself down', async () => {
+ const refresh = vi.fn().mockResolvedValue(undefined);
+ renderHook(() => useVaultRequestRefresh(refresh));
+
+ await settle();
+ await bridgeReports(true);
+ await advance(POLL_INTERVAL_MS * 2);
+ const quiet = refresh.mock.calls.length;
+
+ await bridgeReports(false);
+ await settle();
+ expect(refresh.mock.calls.length).toBe(quiet + 1);
+
+ await advance(POLL_INTERVAL_MS);
+ expect(refresh.mock.calls.length).toBe(quiet + 2);
+ });
+
+ it('catches up on reconnect for whatever the stream could not deliver', async () => {
+ const refresh = vi.fn().mockResolvedValue(undefined);
+ renderHook(() => useVaultRequestRefresh(refresh));
+
+ await settle();
+ const before = refresh.mock.calls.length;
+
+ await act(async () => {
+ for (const handler of [...handlers]) handler.onConnected?.();
+ });
+ expect(refresh.mock.calls.length).toBe(before + 1);
+ });
+});
diff --git a/vibe/authorization.py b/vibe/authorization.py
index e0e4ba181..643100651 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -2,9 +2,11 @@
from __future__ import annotations
+from contextlib import contextmanager
+from contextvars import ContextVar
from dataclasses import dataclass
import re
-from typing import Any, Mapping
+from typing import Any, Iterator, Mapping
from core.inbox_events import (
DEFINITIONS_UPDATED_EVENT,
@@ -76,15 +78,30 @@ _VIEWER_WORKBENCH_EVENTS = frozenset(
"workbench.events.bridge.status",
}
)
-_EDITOR_WORKBENCH_EVENTS = frozenset({"queue.updated"})
-_PRIVILEGED_RUNTIME_WORKBENCH_EVENTS = frozenset(
+#: Change notifications whose consumers refetch an instance-scoped endpoint
+#: rather than read the frame. Harness and Vault are editor HTTP namespaces —
+#: ``/api/harness/*`` applies no resource ACL and ``vault_service.list_requests``
+#: / ``list_grants`` give an editor the full runtime read — so a notification
+#: admitted at a higher role than the endpoint it announces leaves an editor's
+#: Harness and Vault pages on a stream that never wakes them.
+#:
+#: One set, two owners: this is both the role tier below and the projection rule
+#: in ``ui_server._workbench_event_payload_for_context``, which reduces the frame
+#: to its bare signal for a recipient without runtime management. Admission is the
+#: role; what a frame may CARRY is decided there, because publishers attach
+#: identifiers — a run's session, a Vault secret name — that are not uniformly
+#: inside a lower role's read scope, and no consumer reads them.
+INSTANCE_SCOPED_REFETCH_EVENTS = frozenset(
{
DEFINITIONS_UPDATED_EVENT,
RUNS_UPDATED_EVENT,
VAULTS_UPDATED_EVENT,
- "remote_access.quality.changed",
}
)
+_EDITOR_WORKBENCH_EVENTS = frozenset({"queue.updated"}) | INSTANCE_SCOPED_REFETCH_EVENTS
+#: Remote-access link quality describes the instance's own connection, which is
+#: instance management, and stays member-only.
+_PRIVILEGED_RUNTIME_WORKBENCH_EVENTS = frozenset({"remote_access.quality.changed"})
@dataclass(frozen=True)
class HttpAuthorizationPolicy:
@@ -302,6 +319,46 @@ def instance_owner_context() -> AuthorizationContext:
return AuthorizationContext(instance_role="owner")
+_INVOCATION_AUTHORITY: ContextVar["AuthorizationContext | None"] = ContextVar(
+ "avibe_invocation_authority", default=None
+)
+
+
+@contextmanager
+def invocation_authority(context: "AuthorizationContext | None") -> Iterator[None]:
+ """Activate the authority an invocation runs under, for its lifetime only.
+
+ Set explicitly by an entry point that knows who invoked it — today the CLI
+ dispatch boundary. It is the default the two role resolvers fall back to when
+ a service call passes no context, which is why it is invocation-scoped and
+ never global: the token is reset in ``finally``, so ``SystemExit``, an
+ exception, and nested or sequential invocations all restore the previous
+ authority. Activating ``None`` is meaningful — an explicit local invocation
+ nested under a remote one masks it and restores it on exit.
+
+ What bounds the scope is ownership, not the carrier. A ``ContextVar`` is
+ copied into whatever this invocation itself starts — ``asyncio.to_thread``
+ and a task created inside the block both copy the current context — which is
+ what a command that awaits its own work needs, and is not a leak. The scope
+ ends where the invocation does: one entry point sets it, around one dispatch,
+ and resets it on the way out. A separate process, and a thread started
+ outside this block, each begin from their own context, so an independently
+ started controller, daemon or supervisor is never running inside a caller's.
+ """
+
+ token = _INVOCATION_AUTHORITY.set(context)
+ try:
+ yield
+ finally:
+ _INVOCATION_AUTHORITY.reset(token)
+
+
+def current_invocation_authority() -> "AuthorizationContext | None":
+ """Return the active invocation authority, or None outside one."""
+
+ return _INVOCATION_AUTHORITY.get()
+
+
class InstanceAuthorizationError(PermissionError):
def __init__(self, minimum_role: str):
super().__init__(f"Instance role '{minimum_role}' is required")
@@ -309,14 +366,43 @@ class InstanceAuthorizationError(PermissionError):
self.minimum_role = minimum_role
+def _in_http_request() -> bool:
+ try:
+ from vibe.ui_compat import has_request_context
+
+ return bool(has_request_context())
+ except Exception:
+ return False
+
+
+def default_authorization_context() -> AuthorizationContext:
+ """The authority a service call that passes no context runs under.
+
+ Inside an HTTP request this is the local Owner, exactly as it has always
+ been, and the invocation carrier is not consulted: a signed HTTP caller
+ authorizes itself by passing its context explicitly, so a call that passes
+ none is not silently re-attributed to whoever the request belongs to. That
+ boundary is retained deliberately, not repaired here.
+
+ Outside a request, an active invocation authority is the caller; with no
+ invocation either, this is a standalone local entry point and keeps Owner
+ administration.
+ """
+
+ if _in_http_request():
+ return instance_owner_context()
+ invocation = _INVOCATION_AUTHORITY.get()
+ return invocation if invocation is not None else instance_owner_context()
+
+
def require_instance_role(
context: AuthorizationContext | Mapping[str, Any] | None,
minimum_role: str,
) -> AuthorizationContext:
- """Authorize a service call; omitted context denotes local Owner administration."""
+ """Authorize a service call; omitted context resolves to the invocation authority."""
resolved = (
- instance_owner_context()
+ default_authorization_context()
if context is None
else context
if isinstance(context, AuthorizationContext)
diff --git a/vibe/cli.py b/vibe/cli.py
index 24d89b301..9a695eced 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -48,10 +48,14 @@ from core.scheduled_tasks import (
resolve_session_id_target,
session_anchor_for_target,
)
-from core.caller_context import caller_context_from_env, caller_resource_user_context
+from core.caller_context import (
+ caller_context_from_env,
+ caller_resource_user_context,
+ env_declares_remote_caller,
+)
from core.command_runner import command_line_preview
from core.install_integrity import verify_python_environment, verify_site_packages
-from core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
+from core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentAccessError, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
NO_EVENT_EXIT_CODE,
@@ -376,6 +380,54 @@ def _reserved_session_cli_error(exc: "UnresolvableSessionTarget") -> TaskCliErro
)
+def _retyped_placement_refusal(
+ exc: Exception, *, help_command: str | None
+) -> Exception:
+ """Give a refused Session placement the same first-class code the preflight gives it.
+
+ A command that names an EXISTING target is admitted by
+ ``_require_cli_turn_authority``, which already reports each refusal under its
+ own code. A command that CREATES its target is admitted by the reservation
+ writer instead, one layer below the CLI, and its refusals arrived here as bare
+ ``PermissionError``s -- so the same user, refused for the same reason, got
+ ``task_command_failed`` and a prose string with nothing to branch on. Re-typed
+ at the printer for the same reason the reserved-target case above is: every
+ creating command inherits it, including ones added later.
+ """
+
+ from core.vibe_agents import VibeAgentAccessError
+ from storage.workbench_sessions_service import ProjectAccessDeniedError
+ from vibe.authorization import InstanceAuthorizationError
+
+ if isinstance(exc, TaskCliError):
+ return exc
+ if isinstance(exc, InstanceAuthorizationError):
+ return TaskCliError(
+ str(exc),
+ code=exc.code,
+ help_command=help_command,
+ details={"minimum_role": exc.minimum_role},
+ )
+ if isinstance(exc, ProjectAccessDeniedError):
+ # Covers both shapes the placement check refuses: a Project the caller
+ # cannot chat in, and a destination that is no Project at all -- work with
+ # no Scope creates unplaced Sessions, which is runtime management.
+ return TaskCliError(
+ "You cannot place new work here",
+ code=exc.code,
+ hint="Pass --scope-id for a Project you can chat in, or ask for access to this one.",
+ help_command=help_command,
+ )
+ if isinstance(exc, VibeAgentAccessError):
+ return TaskCliError(
+ str(exc),
+ code="agent_access_forbidden",
+ hint="The Agent this work would run on is not one you can use.",
+ help_command=help_command,
+ )
+ return exc
+
+
def _print_task_error(exc: Exception, *, help_command: str | None = None) -> None:
# Re-typed BEFORE the ``TaskCliError`` branch, and here rather than in each command's
# own ``except``, because this is the one printer every CLI admission door funnels its
@@ -392,6 +444,7 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non
ResourceAccessError,
)
+ exc = _retyped_placement_refusal(exc, help_command=help_command)
if (
isinstance(exc, ResourceAccessError)
and exc.code == HARNESS_ACCESS_FORBIDDEN_CODE
@@ -2569,9 +2622,9 @@ def _task_payload(task, *, brief: bool = False):
"enabled": task.enabled,
}
payload = task.to_dict()
- from storage.message_deliveries import metadata_without_delegated_owner
+ from storage.message_deliveries import public_message_metadata
- payload["metadata"] = metadata_without_delegated_owner(payload.get("metadata"))
+ payload["metadata"] = public_message_metadata(payload.get("metadata") or {})
payload.update(derived)
return payload
@@ -2922,6 +2975,196 @@ def _resolve_session_target_args(
return session_id or None, session_key
+class _CommandTarget(NamedTuple):
+ """Where the work a command is about to write will actually speak.
+
+ At most one field is set. ``session_id`` is a Session that exists now, so the
+ caller is admitted to it directly. ``placement_scope_key`` is a target that
+ names a Scope whose Session does not exist yet — the deprecated IM key for a
+ thread nobody has opened — so the work describes a Session that will be
+ created later, and the question is the reservation writer's: may this caller
+ put work in that Scope, with that Agent. Neither set means the target names
+ nothing to admit anyone to.
+ """
+
+ session_id: Optional[str] = None
+ placement_scope_key: Optional[str] = None
+
+
+def _resolve_command_target(session_id: Optional[str], session_key: str) -> _CommandTarget:
+ """Read a command's named target, without creating anything it describes.
+
+ A target is named one of two ways: an Agent Session ID — typed, or defaulted
+ from the caller environment — or the legacy scope key the IM surfaces still
+ accept. Both are resolved read-only, through the primitives their own dispatch
+ uses, so asking who may drive a Session never creates the row the question is
+ about.
+
+ An empty target is not an authorization answer. A blank argument, an ID that
+ does not parse and a malformed key are shape and lifecycle questions owned by
+ the validator, the creation policy or the repair path that already reports
+ them; a binding whose row is gone stays editable by the person who has to fix
+ it. What must NOT be empty is a well-formed key whose Session has simply not
+ been opened yet: that target is where future work lands, so it is returned as
+ a placement rather than silently admitted.
+ """
+
+ if session_id:
+ try:
+ resolve_session_id_target(session_id)
+ except ValueError:
+ return _CommandTarget()
+ return _CommandTarget(session_id=session_id)
+ if not (session_key or "").strip():
+ return _CommandTarget()
+ try:
+ target = parse_session_key(session_key)
+ except ValueError:
+ # Shape is the caller's own validator's question, reported in its
+ # vocabulary. Nothing exists to admit anyone to.
+ return _CommandTarget()
+
+ from storage.sessions_service import SQLiteSessionsService
+
+ _ensure_cli_sqlite_state()
+ service = SQLiteSessionsService(paths.get_sqlite_state_path())
+ try:
+ row = service.find_session_for_anchor(
+ scope_key=target.session_scope,
+ session_anchor=session_anchor_for_target(target),
+ )
+ finally:
+ service.close()
+ existing = str((row or {}).get("id") or "") or None
+ if existing:
+ return _CommandTarget(session_id=existing)
+ return _CommandTarget(placement_scope_key=target.session_scope)
+
+
+def _require_cli_turn_authority(
+ session_id: Optional[str],
+ *,
+ session_key: str = "",
+ help_command: str,
+) -> _CommandTarget:
+ """Admit this invocation to the Session the work it is about to write runs in.
+
+ A Run row, a callback route and a stored Task/Watch definition are all
+ rebuilt later under the authority recorded when the row was written, so the
+ question has to be answered before the row exists. Deciding only at dispatch
+ lets a caller who may not chat in that Project — or may not use the Agent
+ that Session selected — occupy the target anyway, and leaves the refusal
+ somewhere nobody is waiting for it.
+
+ It asks ``core.services.sessions`` the same pair a Workbench turn already
+ answers, under this invocation's own authority: a local invocation keeps
+ standalone Owner semantics, and a remote one is the caller the host signed.
+ Saved automation CONTROL is deliberately not here — running, pausing or
+ removing a stored definition stays Editor admission over the authority the
+ definition already carries, and must not restamp itself to whoever asked.
+
+ Returns the target it read, because half the question can only be asked later:
+ a target whose Session does not exist yet is admitted by Scope and Agent, and
+ which Agent was selected is not known until the caller resolves it. Callers
+ that can name such a target finish with ``_require_cli_target_placement``.
+ """
+
+ target = _resolve_command_target(session_id, session_key)
+ target_session_id = target.session_id
+ if not target_session_id:
+ return target
+
+ from core.services import sessions as sessions_service
+ from core.vibe_agents import VibeAgentAccessError
+ from vibe.authorization import InstanceAuthorizationError
+
+ _ensure_cli_sqlite_state()
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.connect() as conn:
+ sessions_service.require_session_turn_authority(conn, target_session_id)
+ except LookupError as exc:
+ # Same meaning ``vibe session get`` gives it: a Session the caller may
+ # not reach is not a Session they get to learn about.
+ raise TaskCliError(
+ str(exc),
+ code="session_not_found",
+ hint="Target a Session you can continue, or create a new one for this work.",
+ help_command=help_command,
+ details={"session_id": target_session_id},
+ ) from exc
+ except InstanceAuthorizationError as exc:
+ raise TaskCliError(
+ str(exc),
+ code=exc.code,
+ help_command=help_command,
+ details={"session_id": target_session_id, "minimum_role": exc.minimum_role},
+ ) from exc
+ except VibeAgentAccessError as exc:
+ raise TaskCliError(
+ str(exc),
+ code="agent_access_forbidden",
+ hint="The Agent this Session runs on is not one you can use.",
+ help_command=help_command,
+ details={"session_id": target_session_id},
+ ) from exc
+ finally:
+ engine.dispose()
+ return target
+
+
+def _require_cli_placement_authority(
+ scope_key: str,
+ *,
+ agent: Optional[VibeAgent],
+ agent_name: Optional[str],
+) -> None:
+ """Admit a definition that will create its Sessions later, where it will create them.
+
+ ``_require_cli_turn_authority`` answers this for a definition bound to a Session
+ that exists, and the reservation writer answers it for one that reserves during
+ the edit. A ``create_per_run`` definition does neither: it records a destination
+ and creates a Session there on every fire, so without this the placement was
+ admitted for the first time at dispatch — long after the caller who chose it
+ could be told no.
+
+ Refusals travel as they are: ``_print_task_error`` gives each one the code its
+ preflight sibling already reports.
+ """
+
+ from core.services import sessions as sessions_service
+
+ _ensure_cli_sqlite_state()
+ sessions_service.require_session_placement_authority(
+ scope_key=scope_key,
+ agent_id=agent.id if agent else None,
+ agent_name=agent.name if agent else (agent_name or None),
+ )
+
+
+def _require_cli_target_placement(
+ target: _CommandTarget,
+ *,
+ agent: Optional[VibeAgent],
+ agent_name: Optional[str] = None,
+) -> None:
+ """Finish ``_require_cli_turn_authority`` for a target that has no Session yet.
+
+ A legacy key naming a thread nobody has opened is a real, supported target:
+ the work is stored now and its Session is created on the first dispatch. So
+ it is admitted like the placement it is, once the Agent that dispatch will
+ select is known — not left unasked because there was no row to ask about.
+ """
+
+ if not target.placement_scope_key:
+ return
+ _require_cli_placement_authority(
+ target.placement_scope_key,
+ agent=agent,
+ agent_name=agent_name,
+ )
+
+
def _default_session_id_from_caller(caller_context) -> Optional[str]:
if caller_context is None:
return None
@@ -3212,6 +3455,12 @@ def _validate_callback_session_id(session_id: str, *, help_command: str) -> None
help_command=help_command,
details={"session_id": session_id},
) from exc
+ # A callback is a turn in the Session it names, posted by this run. Both
+ # spellings reach here -- an explicit ``--callback-session-id`` and the
+ # caller's own Session when Avibe defaults it -- and the answer is needed
+ # before the run is reserved or enqueued, because the callback route is
+ # recorded on the row and replayed under the authority stored with it.
+ _require_cli_turn_authority(session_id, help_command=help_command)
def _resolve_runs_list_session_filter(args) -> Optional[str]:
@@ -3658,9 +3907,9 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:
"last_error": watch.last_error,
}
payload = watch.to_dict()
- from storage.message_deliveries import metadata_without_delegated_owner
+ from storage.message_deliveries import public_message_metadata
- payload["metadata"] = metadata_without_delegated_owner(payload.get("metadata"))
+ payload["metadata"] = public_message_metadata(payload.get("metadata") or {})
payload.update(derived)
return payload
@@ -3764,7 +4013,7 @@ def _agent_payload(agent, *, brief: bool = False) -> dict:
def _run_payload(run: dict, *, brief: bool = False) -> dict:
- from storage.message_deliveries import metadata_without_delegated_owner
+ from storage.message_deliveries import public_message_metadata
normalized = dict(run)
normalized["status"] = normalize_run_status(normalized.get("status"))
@@ -3793,7 +4042,7 @@ def _run_payload(run: dict, *, brief: bool = False) -> dict:
"callback_status": normalized.get("callback_status"),
"callback_run_id": normalized.get("callback_run_id"),
}
- normalized["metadata"] = metadata_without_delegated_owner(normalized.get("metadata"))
+ normalized["metadata"] = public_message_metadata(normalized.get("metadata") or {})
return normalized
@@ -4210,6 +4459,15 @@ def cmd_task_add(args):
required=session_policy == "existing",
help_command="vibe task add --help",
)
+ # Before the reservation and before the definition row: a stored
+ # schedule fires under the authority written with it, so the Session
+ # it will speak in is admitted while the caller is still here to be
+ # told no.
+ command_target = _require_cli_turn_authority(
+ session_id,
+ session_key=session_key,
+ help_command="vibe task add --help",
+ )
cwd = _resolve_definition_session_cwd(
explicit_cwd=getattr(args, "cwd", None),
existing_cwd=None,
@@ -4237,7 +4495,18 @@ def cmd_task_add(args):
expected_enabled_agent_id, expected_reference_agent_id = _agent_write_guard_ids(
agent_resolution
)
- if session_policy == "create_once":
+ # Where every future fire lands, admitted before the definition row.
+ # A named target whose Session is still future, a per-run definition
+ # that reserves one on each fire, and a reserved reusable Session all
+ # ask the reservation writer's question; the first two ask it here.
+ _require_cli_target_placement(command_target, agent=agent, agent_name=agent_name)
+ if session_policy == "create_per_run":
+ _require_cli_placement_authority(
+ scope_key or "",
+ agent=agent,
+ agent_name=agent_name,
+ )
+ elif session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
agent_id=agent.id if agent else None,
@@ -4857,7 +5126,6 @@ def cmd_task_update(args):
metadata.pop(BINDING_FOLLOWS_SESSION_METADATA_KEY, None)
elif getattr(args, "clear_agent", False):
metadata[BINDING_FOLLOWS_SESSION_METADATA_KEY] = True
- follows_session_agent = bool(metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY))
message_changed = any(
getattr(args, name, None) is not None
@@ -4886,6 +5154,29 @@ def cmd_task_update(args):
next_schedule_type=schedule_type,
help_command="vibe task update --help",
)
+ # Which Session this definition will actually speak in, decided by the
+ # policy above rather than by what is stored today.
+ retains_existing_session = _update_retains_existing_session(
+ session_policy,
+ stored_session_id=task.session_id,
+ create_session=bool(getattr(args, "create_session", False)),
+ )
+ # ...and therefore whether a Session can still own the Agent choice.
+ follows_session_agent = _follows_session_agent_after_update(
+ metadata,
+ session_policy=session_policy,
+ )
+ command_target = _CommandTarget()
+ if retains_existing_session:
+ # An update rewrites the definition under the invoker, so the target it
+ # keeps -- named here or inherited by leaving the binding alone -- is
+ # reauthorized, unlike run/pause/resume, which only steer a definition
+ # that already carries its own authority.
+ command_target = _require_cli_turn_authority(
+ session_id,
+ session_key=session_key,
+ help_command="vibe task update --help",
+ )
explicit_cwd = getattr(args, "cwd", None)
_reject_inert_create_once_cwd_update(
explicit_cwd=explicit_cwd,
@@ -4905,14 +5196,7 @@ def cmd_task_update(args):
# into ``session_workdir``, and for a command task that answer is the command's
# directory: an unrelated ``--name`` edit on a reserved definition wrote the
# subprocess directory into ``metadata["session_workdir"]``.
- command_only_cwd = task.has_command and (
- session_policy == "existing"
- or (
- session_policy == "create_once"
- and bool(task.session_id)
- and not getattr(args, "create_session", False)
- )
- )
+ command_only_cwd = task.has_command and retains_existing_session
if command_only_cwd:
session_workdir = _stored_session_workdir(task, metadata)
cwd = _resolve_command_only_cwd(
@@ -4974,12 +5258,17 @@ def cmd_task_update(args):
help_command="vibe task update --help",
)
agent_resolution = _AgentTargetResolution(None, False)
+ # Every branch below either rebinds this or leaves the definition's Agent to
+ # someone else; the reservation writer reads it either way, and without a
+ # value the follow-the-Session branch raised UnboundLocalError there.
+ agent = None
if follows_session_agent and not explicit_agent_requested:
# Deliberately resolves NOTHING. Re-resolving here would write today's
# scope/default Agent back onto a definition whose Agent authority now
# belongs to its bound Session, and the pin wins over the Session row at
# dispatch -- so an unrelated ``--name`` edit would silently move every
- # future fire onto a different Agent.
+ # future fire onto a different Agent. The reservation below still resolves
+ # and admits the Agent it gives the Session it creates.
pass
elif agent_name is None and session_policy != "existing":
agent_resolution = _resolve_agent_target(
@@ -5003,7 +5292,20 @@ def cmd_task_update(args):
expected_enabled_agent_id, expected_reference_agent_id = _agent_write_guard_ids(
agent_resolution
)
- if session_policy == "create_once" and (
+ # See ``vibe task add``: the effective target's placement, once the Agent
+ # this edit selects is known.
+ _require_cli_target_placement(
+ command_target,
+ agent=agent_resolution.agent,
+ agent_name=agent_name,
+ )
+ if session_policy == "create_per_run":
+ _require_cli_placement_authority(
+ scope_key,
+ agent=agent_resolution.agent,
+ agent_name=agent_name,
+ )
+ elif session_policy == "create_once" and (
getattr(args, "create_session", False) or not session_id
):
session_id = _reserve_definition_session(
@@ -5207,6 +5509,14 @@ def cmd_hook_send(args):
deliver_key=getattr(args, "deliver_key", None),
help_command="vibe hook send --help",
)
+ # Deprecated, but it still queues a real Agent turn, so it is admitted
+ # like one -- including through the legacy key, which names the same
+ # Session by its scope and thread.
+ command_target = _require_cli_turn_authority(
+ session_id,
+ session_key=session_key,
+ help_command="vibe hook send --help",
+ )
message = _resolve_prompt_input(
args,
help_command="vibe hook send --help",
@@ -5219,6 +5529,16 @@ def cmd_hook_send(args):
help_command="vibe hook send --help",
)
agent = agent_resolution.agent
+ # The other half of the gate above, now that the Agent this hook will run
+ # on is known: a key whose thread has not been opened yet reserves its
+ # Session at dispatch, in the Scope named here.
+ _require_cli_target_placement(command_target, agent=agent)
+ from storage.resource_access_service import metadata_with_resource_user_context
+
+ # Deprecated, but it still enqueues an Agent turn, so it travels with the
+ # same initiating snapshot ``vibe agent run`` records. Empty for a local
+ # caller, exactly as before.
+ provenance_metadata = metadata_with_resource_user_context(None) or None
request = _task_request_store().enqueue_hook_send(
session_key=session_key,
session_id=session_id,
@@ -5229,6 +5549,7 @@ def cmd_hook_send(args):
agent_id=agent.id if agent else None,
run_type="agent_run",
source_kind="cli",
+ metadata=provenance_metadata,
expected_enabled_agent_id=(
agent.id
if agent is not None and agent_resolution.requires_enabled_write_guard
@@ -5332,8 +5653,20 @@ def cmd_agent_list(args):
def cmd_agent_show(args):
+ # Reading one Agent is selection-shaped — the row names its backend, model and
+ # instructions — so it answers under use access to that exact resource, the
+ # same ACL ``vibe agent list`` already filters by.
+ try:
+ agent = _agent_store().require_accessible(args.name)
+ except VibeAgentAccessError as exc:
+ _print_task_error(
+ TaskCliError(str(exc), code="agent_access_forbidden", details={"agent": args.name})
+ )
+ return 1
+ except Exception as exc:
+ _print_task_error(TaskCliError(str(exc), code="agent_not_found", details={"agent": args.name}))
+ return 1
try:
- agent = _agent_store().require(args.name)
_print_cli_payload("agent", agent=_agent_payload(agent))
return 0
except Exception as exc:
@@ -5402,8 +5735,15 @@ def cmd_agent_models(args):
)
agent = None
if name:
+ # Naming an Agent here reads that Agent's own model and effort, so it
+ # follows the same use access as selecting it. The catalog options
+ # below stay open: they describe a backend, not an Agent.
try:
- agent = _agent_store().require(name)
+ agent = _agent_store().require_accessible(name)
+ except VibeAgentAccessError as exc:
+ raise TaskCliError(
+ str(exc), code="agent_access_forbidden", details={"agent": name}
+ ) from exc
except Exception as exc:
raise TaskCliError(str(exc), code="agent_not_found", details={"agent": name}) from exc
backend = agent.backend
@@ -5966,6 +6306,60 @@ def _definition_session_policy_for_update(
return current_policy or "existing"
+def _update_retains_existing_session(
+ session_policy: str,
+ *,
+ stored_session_id: Optional[str],
+ create_session: bool,
+) -> bool:
+ """Whether the edited definition keeps speaking in a Session that already exists.
+
+ ``existing`` binds to one by definition, and a reusable ``create_once`` binding
+ that has already reserved keeps it unless this edit asks for a replacement. The
+ remaining shapes -- a first or replacement reservation, and one Session per run
+ -- place the work somewhere that does not exist yet, so the old row is not the
+ target and the destination Scope and Agent are what has to be admitted.
+ """
+
+ if session_policy == "existing":
+ return True
+ return (
+ session_policy == "create_once"
+ and bool(stored_session_id)
+ and not create_session
+ )
+
+
+def _follows_session_agent_after_update(
+ metadata: dict[str, Any],
+ *,
+ session_policy: str,
+) -> bool:
+ """Whether Agent authority still belongs to a Session, under this edit's policy.
+
+ "Follow the bound Session's Agent" is authority held by a Session the definition
+ has: ``--clear-agent`` hands it to the one it is bound to, and the reset rebind
+ stamps it on a ``create_once`` definition pointed at a Session it just made. The
+ marker then stops the edit from resolving an Agent, because there is nothing to
+ decide -- the row the definition speaks in already answers, and re-resolving
+ would pin today's default over it (HFR-245).
+
+ ``create_per_run`` has no such row: every fire makes a throwaway Session from the
+ definition itself, so the marker outlives what it described. Left standing it
+ kept the edit from resolving an Agent while each future fire still picked one --
+ the Scope's default, admitted for nobody, because the placement guard below was
+ handed no Agent to ask about. It is cleared here, before that Agent is resolved
+ and admitted, rather than after the row is saved.
+ """
+
+ if not metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY):
+ return False
+ if session_policy != "create_per_run":
+ return True
+ metadata.pop(BINDING_FOLLOWS_SESSION_METADATA_KEY, None)
+ return False
+
+
def _reject_inert_create_once_cwd_update(
*,
explicit_cwd: Optional[str],
@@ -6364,6 +6758,7 @@ def _reserve_cli_session(
metadata: Optional[dict] = None,
session_anchor_target=None,
visibility: str = "background",
+ authorization_context=None,
) -> str:
# Route through ``core.services.sessions`` so the CLI shares the same
# business API as the UI server and the future N3 internal endpoint;
@@ -6386,6 +6781,7 @@ def _reserve_cli_session(
visibility=visibility,
metadata={"scope_placement": "explicit", **dict(metadata or {})},
require_enabled_agent=True,
+ authorization_context=authorization_context,
)
else:
session_anchor = f"standalone_{uuid4().hex[:12]}"
@@ -6400,6 +6796,7 @@ def _reserve_cli_session(
visibility=visibility,
metadata=metadata,
require_enabled_agent=True,
+ authorization_context=authorization_context,
)
if not session_id:
raise TaskCliError(
@@ -6430,6 +6827,7 @@ def _reserve_forked_cli_session(
reasoning_effort: Optional[str],
scope_key: Optional[str],
visibility: str,
+ authorization_context=None,
):
from core.services.session_fork import (
SESSION_AGENT_UNAVAILABLE_CODE,
@@ -6447,6 +6845,7 @@ def _reserve_forked_cli_session(
scope_id=scope_key,
visibility=visibility,
db_path=paths.get_sqlite_state_path(),
+ authorization_context=authorization_context,
)
except SessionForkError as exc:
if exc.code == SESSION_AGENT_UNAVAILABLE_CODE:
@@ -6652,6 +7051,10 @@ def cmd_agent_run(args):
session_key=session_key,
help_command="vibe agent run --help",
)
+ # The Agent resolved above is the SESSION's -- an explicit --agent
+ # may only restate it -- so admitting the caller to the Session
+ # answers both halves of the turn it is about to queue.
+ _require_cli_turn_authority(session_id, help_command="vibe agent run --help")
if session_policy == "existing" and (args.post_to or args.deliver_key):
_validate_delivery_args(
session_id=session_id,
@@ -6666,6 +7069,9 @@ def cmd_agent_run(args):
legacy_deliver_key = args.deliver_key
if (getattr(args, "same_scope", False) or (getattr(args, "scope_id", None) or "").strip()) and legacy_deliver_key != scope_key:
legacy_deliver_key = None
+ # The caller's own authority, resolved once. A remote caller reserves
+ # under it; a local caller stays ``None`` and keeps Owner semantics.
+ caller_authorization = caller_resource_user_context(caller_context)
if session_policy == "create":
session_id = _reserve_cli_session(
agent=agent,
@@ -6674,6 +7080,7 @@ def cmd_agent_run(args):
metadata=session_metadata,
session_anchor_target=legacy_reservation_target,
visibility=visibility,
+ authorization_context=caller_authorization,
)
reserved_session_id = session_id
elif session_policy == "none":
@@ -6683,6 +7090,7 @@ def cmd_agent_run(args):
workdir=run_cwd,
metadata=session_metadata,
visibility=visibility,
+ authorization_context=caller_authorization,
)
reserved_session_id = session_id
elif session_policy == "fork":
@@ -6693,6 +7101,7 @@ def cmd_agent_run(args):
reasoning_effort=args.reasoning_effort,
scope_key=scope_key,
visibility=visibility,
+ authorization_context=caller_authorization,
)
session_id = fork_result.session_id
reserved_session_id = session_id
@@ -6721,6 +7130,15 @@ def cmd_agent_run(args):
**provenance_metadata,
"session_fork": fork_result.fork.to_metadata(),
}
+ from storage.resource_access_service import metadata_with_resource_user_context
+
+ # `caller_context` above is descriptive provenance. Deferred execution
+ # rechecks authority from the stored snapshot instead, so a remote
+ # caller's own identity has to travel with the Run; a local caller keeps
+ # no key and stays local.
+ provenance_metadata = metadata_with_resource_user_context(
+ provenance_metadata, caller_authorization
+ )
request_store = _task_request_store()
request = request_store.enqueue_agent_run(
agent_name=agent.name if agent else None,
@@ -7510,7 +7928,9 @@ def cmd_session_send_now(args):
try:
engine = _open_session_engine()
with engine.connect() as conn:
- sessions_service.get_active_session(conn, session_id)
+ # Promotion is chat work, so it is authorized before the controller
+ # is asked to act — the IPC hop carries no caller identity.
+ sessions_service.require_session_chat_access(conn, session_id)
controller_result = asyncio.run(internal_client.send_now(session_id))
except LookupError:
_print_task_error(
@@ -7611,7 +8031,7 @@ def cmd_session_queue_list(args):
)
engine = _open_session_engine()
with engine.connect() as conn:
- sessions_service.get_active_session(conn, session_id)
+ sessions_service.require_session_chat_access(conn, session_id)
target = resolve_session_id_target(session_id)
if target.session_key.platform != "avibe":
raise TaskCliError(
@@ -7672,7 +8092,9 @@ def cmd_session_queue_remove(args):
from storage.agent_session_rows import reserve_write_lock
reserve_write_lock(conn)
- sessions_service.get_active_session(conn, session_id)
+ # Inside the writer transaction, before the row is retired: the
+ # refusal and the delete decide on the same committed state.
+ sessions_service.require_session_chat_access(conn, session_id)
target = resolve_session_id_target(session_id)
if target.session_key.platform != "avibe":
raise TaskCliError(
@@ -9764,6 +10186,9 @@ def cmd_vault_request(args):
except vault_service.SecretNameCaseConflictError as exc:
_print_task_error(TaskCliError(str(exc), code="secret_name_case_conflict", help_command=help_command))
return 1
+ except vault_service.VaultSecretAccessError as exc:
+ _print_task_error(TaskCliError(str(exc), code="vault_access_forbidden", help_command=help_command))
+ return 1
except vault_service.VaultServiceError as exc:
_print_task_error(TaskCliError(str(exc), code="invalid_spec", help_command=help_command))
return 1
@@ -9841,6 +10266,9 @@ def cmd_vault_sign(args):
except vault_service.SecretNotFoundError:
_print_task_error(TaskCliError(f"secret '{name}' not found", code="secret_not_found", help_command=help_command))
return 1
+ except vault_service.VaultSecretAccessError as exc:
+ _print_task_error(TaskCliError(str(exc), code="vault_access_forbidden", help_command=help_command))
+ return 1
except api.VaultApiError as exc:
_print_task_error(TaskCliError(str(exc), code=exc.code, help_command=help_command))
return 1
@@ -10569,6 +10997,13 @@ def cmd_watch_add(args):
required=session_policy == "existing",
help_command="vibe watch add --help",
)
+ # Same gate as ``vibe task add``: the waiter's hook is a turn in this
+ # Session, replayed later under the authority stored with the Watch.
+ command_target = _require_cli_turn_authority(
+ session_id,
+ session_key=session_key,
+ help_command="vibe watch add --help",
+ )
agent_resolution = _resolve_agent_target(
agent_name=getattr(args, "agent", None),
session_id=session_id,
@@ -10592,7 +11027,15 @@ def cmd_watch_add(args):
if session_policy != "existing"
else None
)
- if session_policy == "create_once":
+ # See ``vibe task add``: where the stored Watch's hook will land.
+ _require_cli_target_placement(command_target, agent=agent, agent_name=agent_name)
+ if session_policy == "create_per_run":
+ _require_cli_placement_authority(
+ scope_key or "",
+ agent=agent,
+ agent_name=agent_name,
+ )
+ elif session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
agent_id=agent.id if agent else None,
@@ -10906,7 +11349,6 @@ def cmd_watch_update(args):
metadata.pop(BINDING_FOLLOWS_SESSION_METADATA_KEY, None)
elif getattr(args, "clear_agent", False):
metadata[BINDING_FOLLOWS_SESSION_METADATA_KEY] = True
- follows_session_agent = bool(metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY))
cwd = (
None
if getattr(args, "clear_cwd", False)
@@ -10944,9 +11386,24 @@ def cmd_watch_update(args):
next_schedule_type="watch",
help_command="vibe watch update --help",
)
- creates_future_session = session_policy == "create_per_run" or (
- session_policy == "create_once" and (bool(getattr(args, "create_session", False)) or not session_id)
+ creates_future_session = not _update_retains_existing_session(
+ session_policy,
+ stored_session_id=session_id,
+ create_session=bool(getattr(args, "create_session", False)),
+ )
+ # ...and therefore whether a Session can still own the Agent choice.
+ follows_session_agent = _follows_session_agent_after_update(
+ metadata,
+ session_policy=session_policy,
)
+ command_target = _CommandTarget()
+ if not creates_future_session:
+ # The effective target, named or inherited -- see ``vibe task update``.
+ command_target = _require_cli_turn_authority(
+ session_id,
+ session_key=session_key,
+ help_command="vibe watch update --help",
+ )
session_workdir = (
_resolve_definition_session_cwd(
explicit_cwd=getattr(args, "cwd", None),
@@ -10969,12 +11426,16 @@ def cmd_watch_update(args):
help_command="vibe watch update --help",
)
agent_resolution = _AgentTargetResolution(None, False)
+ # See ``vibe task update``: the reservation writer reads this on the
+ # follow-the-Session branch too, where nothing else binds it.
+ agent = None
if follows_session_agent and not explicit_agent_requested:
# Deliberately resolves NOTHING. Re-resolving here would write today's
# scope/default Agent back onto a definition whose Agent authority now
# belongs to its bound Session, and the pin wins over the Session row at
# dispatch -- so an unrelated ``--name`` edit would silently move every
- # future watch hook onto a different Agent.
+ # future watch hook onto a different Agent. The reservation below still
+ # resolves and admits the Agent it gives the Session it creates.
pass
elif agent_name is None and session_policy != "existing":
agent_resolution = _resolve_agent_target(
@@ -10998,7 +11459,20 @@ def cmd_watch_update(args):
expected_enabled_agent_id, expected_reference_agent_id = _agent_write_guard_ids(
agent_resolution
)
- if session_policy == "create_once" and (
+ # See ``vibe task add``: the effective target's placement, once the Agent
+ # this edit selects is known.
+ _require_cli_target_placement(
+ command_target,
+ agent=agent_resolution.agent,
+ agent_name=agent_name,
+ )
+ if session_policy == "create_per_run":
+ _require_cli_placement_authority(
+ scope_key,
+ agent=agent_resolution.agent,
+ agent_name=agent_name,
+ )
+ elif session_policy == "create_once" and (
getattr(args, "create_session", False) or not session_id
):
session_id = _reserve_definition_session(
@@ -13679,6 +14153,27 @@ def _run_remote_pair(args, *, guided: bool) -> int:
if current.get("paired"):
_print_remote_already_configured(current)
return 0
+
+ # The guided entry point (``vibe`` / ``vibe remote``) is admitted at the
+ # management floor so it can report what is already configured, but past this
+ # line it performs exactly what ``vibe remote pair`` does: it writes this
+ # machine's identity. Refusing here, before a pairing key is solicited or
+ # spent, keeps both entry points on the one Owner answer.
+ from vibe.authorization import InstanceAuthorizationError, require_instance_role
+
+ try:
+ require_instance_role(None, "owner")
+ except InstanceAuthorizationError as exc:
+ _print_task_error(
+ TaskCliError(
+ str(exc),
+ code=exc.code,
+ details={"command": "vibe remote pair", "minimum_role": exc.minimum_role},
+ )
+ )
+ return 1
+
+ if guided:
_print_remote_setup_intro()
if not _wait_for_pairing_key_ready():
print("Remote access setup cancelled.")
@@ -14259,6 +14754,42 @@ def _request_show_page_prewarm_best_effort(
return None
+def _reserve_dispatching_show_event(session_id: str, payload: dict) -> None:
+ """Write a dispatching Show event here, under this invocation's authority.
+
+ A dispatching event is deferred Agent work, and the controller rebuilds that
+ turn from the reservation rather than from whatever woke it. The live UI is a
+ separate process reached over a local token, so it would resolve a remote
+ caller as this machine's Owner and record the wrong authority. Reserving
+ first keeps the answer this invocation was admitted under; the POST that
+ follows replays the same event id, so the live path still owns publishing and
+ dispatch, and an unreachable UI still falls back exactly as before.
+
+ Non-dispatching events start no turn and have no deferred consumer, so they
+ stay on the single-write path.
+
+ This reservation is the only point where the caller's authority is still
+ known, so its failure is the command's failure. Falling through would hand
+ the same turn to the live UI or to the local fallback, and both would write
+ it again as this machine's Owner -- turning a refusal into an escalation and
+ a storage fault into an unstamped row. Either path may replay this
+ reservation once it exists; neither may create a second one after it did not.
+ """
+
+ from core.show_session_events import (
+ ShowSessionEventStore,
+ show_event_request_requests_dispatch,
+ )
+
+ if not show_event_request_requests_dispatch(payload):
+ return
+ store = ShowSessionEventStore()
+ try:
+ store.append(session_id, payload)
+ finally:
+ store.close()
+
+
def _post_show_event_to_live_ui(session_id: str, payload: dict) -> dict | None:
from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token
@@ -14794,6 +15325,7 @@ def cmd_show_event(args):
else f"show_evt_{uuid4().hex[:16]}"
)
event_id_for_retry = payload["id"]
+ _reserve_dispatching_show_event(session_id, payload)
event = _post_show_event_to_live_ui(session_id, payload)
if event is None:
# The local bridge handles both shapes: non-dispatch events are
@@ -17860,17 +18392,262 @@ def _dispatch_installer_activation(argv: list[str]) -> int:
return 0
+#: The role floor each public command namespace runs under, keyed by the parser
+#: leaf path the user actually typed (aliases are their own keys). It is a
+#: NAMESPACE floor, not a second policy engine: the resource answer — which
+#: Project, Agent, page or secret — stays with the existing policy functions the
+#: services call. ``None`` means the leaf deliberately carries no instance-role
+#: contract, and every one of those is classified in the audit rather than left
+#: out. A leaf missing from this table is admitted as Owner, so a command added
+#: later fails closed until it is classified; ``test_cli_command_admission``
+#: walks the parser so that classification cannot be forgotten silently.
+_CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {
+ # Public facts, unchanged: a version and an update check answer the same
+ # thing to anyone, and status is not gated merely because doctor is.
+ ("version",): None,
+ ("check-update",): None,
+ ("status",): None,
+ # Host scope, not instance scope: these act on this machine's screen and on
+ # authored files, and have no role contract to repair here.
+ ("screenshot",): None,
+ ("debug", "prompt", "export"): None,
+ # Memory owns its own verified identity and proof lifecycle.
+ ("memory", "status"): None,
+ ("memory", "profile"): None,
+ ("memory", "list"): None,
+ ("memory", "search"): None,
+ ("memory", "remember"): None,
+ # Runtime, configuration and retention are operational management.
+ (): "member",
+ ("start",): "member",
+ ("stop",): "member",
+ ("restart",): "member",
+ ("doctor",): "member",
+ ("upgrade",): "member",
+ ("runtime", "status"): "member",
+ ("runtime", "prepare"): "member",
+ ("runtime", "clean"): "member",
+ # Remote access: operating the tunnel is management, but pairing writes this
+ # machine's identity, so setup admits at the management floor and the command
+ # itself keeps the Owner check in front of any pairing effect.
+ ("remote",): "member",
+ ("remote", "status"): "member",
+ ("remote", "start"): "member",
+ ("remote", "stop"): "member",
+ ("remote", "pair"): "owner",
+ # Agents: discovery, selection and running are use; the definition lifecycle
+ # is management, admitted before any builtin synchronization or import.
+ ("agent", "list"): "editor",
+ ("agent", "show"): "editor",
+ ("agent", "models"): "editor",
+ ("agent", "run"): "editor",
+ ("agent", "create"): "member",
+ ("agent", "update"): "member",
+ ("agent", "enable"): "member",
+ ("agent", "disable"): "member",
+ ("agent", "remove"): "member",
+ ("agent", "import"): "member",
+ ("agent", "default"): "member",
+ # Harness: one instance-wide Editor floor for reads and ordinary control.
+ ("runs", "list"): "editor",
+ ("runs", "show"): "editor",
+ ("runs", "cancel"): "editor",
+ ("harness", "status"): "editor",
+ ("task", "add"): "editor",
+ ("task", "update"): "editor",
+ ("task", "list"): "editor",
+ ("task", "ls"): "editor",
+ ("task", "show"): "editor",
+ ("task", "pause"): "editor",
+ ("task", "resume"): "editor",
+ ("task", "run"): "editor",
+ ("task", "remove"): "editor",
+ ("task", "rm"): "editor",
+ ("watch", "add"): "editor",
+ ("watch", "update"): "editor",
+ ("watch", "list"): "editor",
+ ("watch", "ls"): "editor",
+ ("watch", "show"): "editor",
+ ("watch", "pause"): "editor",
+ ("watch", "resume"): "editor",
+ ("watch", "remove"): "editor",
+ ("watch", "rm"): "editor",
+ ("hook", "send"): "editor",
+ # Sessions and their queue, mirroring the HTTP surface: reading is Viewer
+ # work, editing and the queue are Editor work, and both sides are narrowed
+ # further by the effective Project role of each session the command touches.
+ ("session", "list"): "viewer",
+ ("session", "get"): "viewer",
+ ("session", "update"): "editor",
+ ("session", "send-now"): "editor",
+ ("session", "queue", "list"): "editor",
+ ("session", "queue", "remove"): "editor",
+ # Vault: the namespace is Editor work, as it is over HTTP. Metadata and
+ # deletion stay Member work, but that answer belongs to the secret's own
+ # policy (``_require_secret_resource_management``), which now sees the
+ # caller — the same split the browser goes through. Key material is this
+ # machine's identity and is the one Owner floor here.
+ ("vault", "list"): "editor",
+ ("vault", "find"): "editor",
+ ("vault", "tags"): "editor",
+ ("vault", "run"): "editor",
+ ("vault", "fetch"): "editor",
+ ("vault", "access"): "editor",
+ ("vault", "sign"): "editor",
+ ("vault", "await"): "editor",
+ ("vault", "request"): "editor",
+ ("vault", "inject"): "editor",
+ ("vault", "export"): "editor",
+ ("vault", "edit"): "editor",
+ ("vault", "rm"): "editor",
+ ("vault", "key", "export"): "owner",
+ ("vault", "key", "import"): "owner",
+ # Show: reading a page is Viewer work and writing to one is Editor work; the
+ # page's own ACL still decides which page, on both sides.
+ ("show", "list"): "viewer",
+ ("show", "path"): "viewer",
+ ("show", "status"): "viewer",
+ ("show", "marks"): "viewer",
+ ("show", "update"): "editor",
+ ("show", "mark"): "editor",
+ ("show", "unmark"): "editor",
+ ("show", "reply"): "editor",
+ ("show", "event"): "editor",
+ ("show", "annotate"): "editor",
+ # Skills are an Editor capability; these two already carry their own scope
+ # contract and keep it.
+ ("skill", "list"): "editor",
+ ("skill", "load"): "editor",
+ ("data", "query"): "editor",
+ ("data", "skill-usage"): "editor",
+ ("data", "retention"): "member",
+}
+
+#: Argv-level entry points the supervisor and the installer use. They are not
+#: parser leaves, and they are Owner work: an invocation that declares a remote
+#: caller must not reach them as an alternate entry.
+_INTERNAL_ACTIVATION_COMMANDS = ("__restart-supervisor", "__activate-upgrade", "__activate-install")
+
+
+def _cli_invocation_authority(env: Optional[Mapping[str, str]] = None):
+ """Resolve, once, the authority this CLI invocation runs under.
+
+ A genuinely local invocation resolves to ``None``, which keeps standalone
+ Owner administration. A remote Agent invocation runs as the remote user whose
+ snapshot Avibe injected — but only while that snapshot still describes this
+ installation. The environment is carried across process boundaries and
+ outlives the pairing it was minted under, so the claims alone are not
+ provenance: they are validated the same way every other deferred consumer
+ validates a stored snapshot, against the configured instance and its durable
+ ready binding.
+
+ A declared-remote invocation whose provenance is missing, malformed or no
+ longer valid here stays an anonymous remote context and fails closed. It does
+ not become local just because the claims it should have carried are absent or
+ stale — that would turn a rejected remote caller into the machine's owner.
+ """
+
+ from storage.resource_access_service import (
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ resource_user_context_from_metadata,
+ )
+ from vibe.authorization import AuthorizationContext
+
+ source = os.environ if env is None else env
+ snapshot = caller_resource_user_context(caller_context_from_env(source))
+ if snapshot is None and not env_declares_remote_caller(source):
+ return None
+ context = resource_user_context_from_metadata({RESOURCE_USER_CONTEXT_METADATA_KEY: snapshot})
+ return AuthorizationContext(is_remote=True) if context is None else context
+
+
+def _dispatch_path(parser: argparse.ArgumentParser, args) -> tuple[tuple[str, ...], bool]:
+ """Return the parser leaf the user reached, and whether it needs a subcommand."""
+
+ path: list[str] = []
+ current = parser
+ while True:
+ action = next(
+ (item for item in current._actions if isinstance(item, argparse._SubParsersAction)),
+ None,
+ )
+ if action is None:
+ return tuple(path), False
+ chosen = getattr(args, action.dest, None)
+ if not chosen or chosen not in action.choices:
+ return tuple(path), True
+ path.append(chosen)
+ current = action.choices[chosen]
+
+
+def _require_command_admission(parser: argparse.ArgumentParser, args) -> None:
+ """Admit the invocation to this command's namespace before it can act."""
+
+ from vibe.authorization import InstanceAuthorizationError, require_instance_role
+
+ path, subcommand_missing = _dispatch_path(parser, args)
+ if path not in _CLI_COMMAND_FLOORS and subcommand_missing:
+ # Not a command at all: argparse is about to print usage and exit, and no
+ # product effect can run in between.
+ return
+ floor = _CLI_COMMAND_FLOORS.get(path, "owner")
+ if floor is None:
+ return
+ try:
+ require_instance_role(None, floor)
+ except InstanceAuthorizationError as exc:
+ command = " ".join(("vibe", *path)).strip()
+ _print_task_error(
+ TaskCliError(
+ str(exc),
+ code=exc.code,
+ details={"command": command, "minimum_role": exc.minimum_role},
+ )
+ )
+ sys.exit(1)
+
+
+def _require_internal_activation_admission(command: str) -> None:
+ from vibe.authorization import InstanceAuthorizationError, require_instance_role
+
+ try:
+ require_instance_role(None, "owner")
+ except InstanceAuthorizationError as exc:
+ print(f"{command}: {exc}", file=sys.stderr)
+ sys.exit(1)
+
+
def main():
+ """Public CLI entry: resolve the invocation's authority once, then dispatch.
+
+ The whole dispatch runs inside the invocation, including argument parsing and
+ the internal activation entry points, so nothing this process does on the
+ caller's behalf can be mistaken for local administration. Entering it with
+ ``None`` for a local invocation is deliberate: skipping activation would leave
+ a surrounding authority in place for a nested local call.
+ """
+
+ from vibe.authorization import invocation_authority
+
cache_running_vibe_path()
argv = sys.argv[1:]
- if argv and argv[0] == "__restart-supervisor":
- sys.exit(_dispatch_restart_supervisor(argv[1:]))
- if argv and argv[0] == "__activate-upgrade":
- sys.exit(_dispatch_deferred_upgrade_activation(argv[1:]))
- if argv and argv[0] == "__activate-install":
- sys.exit(_dispatch_installer_activation(argv[1:]))
- parser = build_parser()
- args = parser.parse_args()
+ with invocation_authority(_cli_invocation_authority()):
+ if argv and argv[0] in _INTERNAL_ACTIVATION_COMMANDS:
+ _require_internal_activation_admission(argv[0])
+ if argv and argv[0] == "__restart-supervisor":
+ sys.exit(_dispatch_restart_supervisor(argv[1:]))
+ if argv and argv[0] == "__activate-upgrade":
+ sys.exit(_dispatch_deferred_upgrade_activation(argv[1:]))
+ if argv and argv[0] == "__activate-install":
+ sys.exit(_dispatch_installer_activation(argv[1:]))
+ parser = build_parser()
+ args = parser.parse_args()
+ _require_command_admission(parser, args)
+ _dispatch_parsed_command(parser, args)
+
+
+def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
+ """Run the admitted command. Every branch exits; nothing returns to ``main``."""
if args.command == "stop":
sys.exit(cmd_stop())
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 5b52b0053..a34193765 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1486,10 +1486,10 @@
"helpCommand": "\u67e5\u770b Avibe \u6570\u636e,\u6216\u6267\u884c\u663e\u5f0f\u7684 trace \u4fdd\u7559\u7ef4\u62a4",
"helpDescription": "\u901a\u8fc7\u53d7\u4fdd\u62a4\u7684\u53ea\u8bfb SQL \u67e5\u770b\u672c\u5730 Avibe SQLite \u72b6\u6001,\u6216\u6267\u884c\u663e\u5f0f\u7ef4\u62a4:`query` \u4e3a\u53ea\u8bfb;`retention --run` \u4f1a\u5220\u9664\u65e7\u7684\u5185\u90e8 trace \u4e8b\u4ef6\u5e76\u53ef\u80fd\u538b\u5b9e\u6570\u636e\u5e93\u3002",
"skillUsage": {
- "ownerRequired": "需要实例成员或所有者权限。",
+ "ownerRequired": "需要实例管理者或所有者权限。",
"confirmationRequired": "清除 Skill 统计需要使用 --yes 确认。",
"clearRequired": "--yes 必须与 --clear 一起使用。",
- "helpCommand": "查看或清除本地 Skill 统计(实例成员或所有者)",
+ "helpCommand": "查看或清除本地 Skill 统计(实例管理者或所有者)",
"helpClear": "清除 Skill 事件及每日统计。",
"helpYes": "确认清除 Skill 统计。"
},
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 3fac33f3f..53f298ec3 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -584,7 +584,7 @@ def _schedule_restart_locked(
start_new_session=True,
close_fds=True,
cwd=get_safe_cwd(),
- env=runtime._memory_ui_child_env(
+ env=runtime.independent_process_env(
env,
memory_ui_secret=memory_ui_secret,
),
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 27e2d4a74..a2cf87a84 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -1028,16 +1028,28 @@ def _spawn_stdin(
process.stdin.close()
-def _memory_ui_child_env(
+def independent_process_env(
env: dict[str, str] | None,
*,
- memory_ui_secret: str | None,
-) -> dict[str, str] | None:
+ memory_ui_secret: str | None = None,
+) -> dict[str, str]:
+ """Build the environment for a process Avibe owns, not one it runs for a caller.
+
+ The service, the UI server, the connector and the restart supervisor all
+ outlive the call that started them and act as the installation. The caller
+ provenance the current process may be carrying belongs to that call, so it
+ stops here — the child's own entry point is Owner work and would refuse it
+ anyway. ``None`` is materialized rather than passed through to ``Popen``,
+ because an implicit inherit would carry the caller across too.
+ """
+
+ from core.caller_context import environment_without_caller_context
+
+ child_env = environment_without_caller_context(env)
if memory_ui_secret is None:
- return env
+ return child_env
from vibe.memory_ui_access import MEMORY_UI_SECRET_STDIN_ENV
- child_env = dict(os.environ if env is None else env)
child_env[MEMORY_UI_SECRET_STDIN_ENV] = "1"
return child_env
@@ -1065,7 +1077,7 @@ def spawn_background(
start_new_session=True,
cwd=str(get_working_dir()),
close_fds=True,
- env=_memory_ui_child_env(env, memory_ui_secret=memory_ui_secret),
+ env=independent_process_env(env, memory_ui_secret=memory_ui_secret),
)
_spawn_stdin(process, memory_ui_secret=memory_ui_secret)
finally:
@@ -1099,7 +1111,7 @@ def spawn_service_background_process(
start_new_session=True,
cwd=str(get_working_dir()),
close_fds=True,
- env=_memory_ui_child_env(env, memory_ui_secret=memory_ui_secret),
+ env=independent_process_env(env, memory_ui_secret=memory_ui_secret),
)
_spawn_stdin(process, memory_ui_secret=memory_ui_secret)
finally:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 879c93c6c..e3366263f 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -11934,6 +11934,14 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)
return True
if event_type in {"authorization.changed", "workbench.events.bridge.status"}:
return True
+ from vibe.authorization import INSTANCE_SCOPED_REFETCH_EVENTS
+
+ if event_type in INSTANCE_SCOPED_REFETCH_EVENTS:
+ # Instance-wide invalidations: the recipient refetches an endpoint that
+ # re-applies its own authority, so they bypass the session/scope filter
+ # below even when a publisher attaches an optional session id. What the
+ # frame may CARRY is decided by ``_workbench_event_payload_for_context``.
+ return True
data = _workbench_event_data(payload)
if event_type == "projects.changed":
# This global invalidation is safe only while it carries no project data.
@@ -11967,6 +11975,15 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)
Returns ``None`` when the event cannot be projected safely for this
recipient, in which case the caller drops the frame.
"""
+ from vibe.authorization import INSTANCE_SCOPED_REFETCH_EVENTS
+
+ if event_type in INSTANCE_SCOPED_REFETCH_EVENTS and not _has_runtime_management_access(context):
+ # Below runtime management the frame is a bare signal: consumers refetch
+ # and ignore the body, while publishers attach identifiers (session ids,
+ # ``vaults.updated``'s secret name) that this recipient's own read
+ # endpoints may filter out. Reducing the class, not one field, keeps a
+ # future publisher field from disclosing by default.
+ return json.dumps({"type": event_type, "data": {}}, separators=(",", ":"))
if (
event_type == "show.event"
and context is not None
@@ -13596,7 +13613,15 @@ def _show_page_runtime_failure_response(
def _show_session_event_error_response(exc: Exception):
code = getattr(exc, "code", "show_session_event_failed")
- status = 404 if code == "session_not_found" else 409 if code == "event_id_conflict" else 400
+ status = (
+ 404
+ if code == "session_not_found"
+ else 409
+ if code == "event_id_conflict"
+ else 403
+ if code == "session_access_forbidden"
+ else 400
+ )
return jsonify({"ok": False, "code": code, "error": str(exc)}), status
@@ -13757,8 +13782,13 @@ def _show_limited_viewer_is_allowed(
return allowlisted
-async def _show_public_request_author() -> dict[str, str] | None:
- context = await asyncio.to_thread(_show_public_editor_context)
+def _show_public_author_from_context(context: Any) -> dict[str, str] | None:
+ """Project one validated public Editor context into its display author.
+
+ The author is a rendering of the authority, not a second source of it, so
+ the write path resolves the context once and derives both from that object.
+ """
+
if context is None:
return None
if context.is_remote:
@@ -13766,6 +13796,14 @@ async def _show_public_request_author() -> dict[str, str] | None:
return {"kind": "local"}
+async def _show_public_request_author() -> dict[str, str] | None:
+ """Resolve and project in one step, for the read-only public surfaces."""
+
+ return _show_public_author_from_context(
+ await asyncio.to_thread(_show_public_editor_context)
+ )
+
+
def _show_request_author() -> dict[str, str] | None:
from vibe.authorization import context_from_session_payload
@@ -13819,6 +13857,7 @@ async def _show_event_response_from_payload(
public: bool = False,
public_share_id: str | None = None,
allow_dispatch: bool = True,
+ authorization_context: Any = None,
):
context = getattr(g, "authorization_context", None)
is_remote_caller = context is not None and context.is_remote
@@ -13848,6 +13887,14 @@ async def _show_event_response_from_payload(
),
400,
)
+ # The share route has no validated request context of its own — its visitor
+ # is whoever the link admitted, not whoever this process would otherwise
+ # resolve to — so it resolves that visitor once at its own boundary and hands
+ # the object down. Resolving again here would let the identity that admitted
+ # the write differ from the identity the deferred turn is stored under.
+ event_context = context if context is not None else authorization_context
+ if public and event_context is None:
+ return jsonify({"ok": False, "code": "public_show_events_login_required"}), 403
store = _show_session_event_store()
try:
event_payload = store.append(
@@ -13855,6 +13902,7 @@ async def _show_event_response_from_payload(
payload,
author=author,
reserve_dispatch=allow_dispatch,
+ authorization_context=event_context,
)
except Exception as exc:
return _show_session_event_error_response(exc)
@@ -16110,7 +16158,11 @@ async def serve_public_show_page(share_id, asset_path):
)
if request.method != "POST":
return jsonify({"ok": False, "code": "method_not_allowed"}), 405
- author = await _show_public_request_author()
+ # One resolution for the whole write: the admission decision below,
+ # the display author, and the authority the event is stored under all
+ # come from this object, so they cannot describe different people.
+ write_context = await asyncio.to_thread(_show_public_editor_context)
+ author = _show_public_author_from_context(write_context)
if author is None:
return jsonify({"ok": False, "code": "public_show_events_login_required"}), 403
can_annotate = _show_annotation_capability(
@@ -16135,6 +16187,7 @@ async def serve_public_show_page(share_id, asset_path):
public=True,
public_share_id=share_id,
allow_dispatch=can_annotate,
+ authorization_context=write_context,
)
if request.method in {"GET", "HEAD"}:
if shim_response := _show_runtime_public_client_shim_response(asset_path):
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index a48831e52..f1ccc6cc3 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -38,6 +38,7 @@ from vibe.package_shape import (
)
from config import paths as config_paths
+from core.caller_context import environment_without_caller_context
from core.install_integrity import (
IntegrityResult,
isolated_probe_environment,
@@ -382,7 +383,11 @@ def defer_upgrade_activation(
start_new_session=True,
close_fds=True,
cwd=get_safe_cwd(),
- env=isolated_probe_environment(),
+ # Activation is Avibe's own work: it runs after this process exits,
+ # under the installation's authority, not the caller's. Keep the
+ # interpreter isolation this spawn already needs and drop the caller
+ # hop on top of it, rather than changing what probes inherit.
+ env=environment_without_caller_context(isolated_probe_environment()),
)