Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(auth): align member Agent management (#1621)
Max457ed2b470c6
diff --git a/core/vibe_agents.py b/core/vibe_agents.pyindex 2146fc64d..049a5a24a 100644--- a/core/vibe_agents.py+++ b/core/vibe_agents.py@@ -256,10 +256,10 @@ def ensure_agent_selection_access(if row is None:if missing_is_error:raise LookupError("Agent not found")- # Owners keep the pre-catalog fallback for historical backend names.- # Everyone else must resolve a real Agent row; a missing selector is- # not an authorization grant.- if context.is_instance_owner:+ # Members keep the pre-catalog fallback for historical backend names:+ # selecting a backend is part of Agent entitlement, not Owner identity.+ # Editors and Viewers must still resolve a real Agent row.+ if context.has_role("member"):return Noneraise VibeAgentAccessError("Agent access is not permitted.")@@ -289,9 +289,9 @@ def ensure_agent_name_access(try:store.require_accessible(str(agent_name), user_context=context)except ValueError:- # Legacy local/Owner task definitions may refer to a backend name- # that predates the Vibe Agent catalog. Keep those internal flows- # intact; an Editor or Viewer must still resolve a real ACL row.+ # Existing local/Owner definitions may predate the Agent catalog.+ # A Member binding is new data and must resolve a real Agent row,+ # matching the execution-time catalog requirement.if context.is_instance_owner:returnraise@@ -637,7 +637,9 @@ def ensure_session_agent_access()if not session.get("agent_backend"):return ensure_default_agent_access(connection, user_context=context)- if not context.is_instance_owner:+ # A backend-only row predates the Agent catalog. Dispatch entitlement+ # follows Agent management rank; it is not an Owner identity operation.+ if not context.has_role("member"):raise VibeAgentAccessError("Agent access is not permitted.")return None@@ -1747,7 +1749,7 @@ class VibeAgentStore:) -> None:normalized = normalize_agent_name(name)context = resolve_resource_access_context(user_context)- if not context.can_manage_access_members:+ if not context.can_manage_agents:raise VibeAgentAccessError("Agent access is not permitted.")now = _utc_now_iso()with self.engine.begin() as conn:@@ -1772,8 +1774,8 @@ class VibeAgentStore:reason="disabled",)# No audience validation here: the default is advisory and the ACL- # is enforced per-principal at use time. The Owner-only gate on this- # setter is what bounds who may point instance-wide routing.+ # is enforced per-principal at use time. Agent managers may point+ # instance-wide routing without widening the target Agent's ACL.self._write_default_agent_name(conn, agent.name, now=now)def get_default_agent(self, *, enabled_only: bool = True) -> Optional[VibeAgent]:diff --git a/docs/plans/instance-access-role-member.md b/docs/plans/instance-access-role-member.mdnew file mode 100644index 000000000..4030eea95--- /dev/null+++ b/docs/plans/instance-access-role-member.md@@ -0,0 +1,228 @@+# Instance access role `member` (owner minus member management)++Issue: https://github.com/avibe-bot/avibe/issues/1596+Related: https://github.com/avibe-bot/avibe/pull/1562 (Personal editor resource-ACL semantics — the capability model this role plugs into)++This file is the **cross-lane contract**. Field names, role identifiers, and capability names are exact. Deviations require orchestrator sign-off.++## 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`.+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.++## Role axis (instance access)++```+viewer < editor < member < owner+```++Stored / token / session payload value: `vibe_instance_role` ∈ `{owner, member, editor, viewer}`.++Allowlist entry role (cannot be `owner`; owner is implicit via `instance.ownerUserId`):++```+InstanceAccessEntryRole = "member" | "editor" | "viewer"+```++Project access bindings stay `{editor, viewer}` — **do not** add `member` to project ACL rows. A `member` instance role on a restricted Organization project is narrowed by the existing `min(instance_role, binding_role)` rule (so a `member` bound as `viewer` becomes `viewer`).++Organization roles stay `{owner, admin, member}` and are a **separate axis**. Never conflate them.++## Capability contract++Exact capability names. Source of truth: `AuthorizationContext` in `vibe/authorization.py`.++| Capability | viewer | editor | **member** | owner |+|---|---|---|---|---|+| `can_read_instance` | yes | yes | yes | yes |+| `can_chat` | no | yes | yes | yes |+| `can_use_cloud_asr` | no | yes | yes | yes |+| `can_use_resource("agent"\|"skill"\|"vault_secret")` | no | yes | yes | yes |+| `can_use_resource("show_page")` | yes | yes | yes | yes |+| `can_use_terminal` / `can_use_files` / `can_use_terminal_files` | no | yes | yes | yes |+| `can_manage_projects` | no | no | **yes** | yes |+| `can_manage_agents` | no | no | **yes** | yes |+| `can_manage_instance` | no | no | **yes** | yes |+| `can_use_system` | no | no | **yes** | yes |+| **`can_manage_access_members`** (NEW) | no | no | **no** | yes |+| `is_instance_owner` | no | no | **no** | yes |++`is_instance_owner` remains `instance_role == "owner"` (identity, not rank). Canonical-owner control-plane actions (pairing keys, hostname writes, ownership transfer, allowlist mutate) stay `canonicalOwnerRequired`.++`capability_projection()` MUST include the new key:++```+"can_manage_access_members": <bool>+```++Existing keys keep their names and types. Frontend `InstanceCapabilities` adds the same key.++## Rank++```+_ROLE_RANK = {"viewer": 1, "editor": 2, "member": 3, "owner": 4}+INSTANCE_ROLES = frozenset({"owner", "member", "editor", "viewer"})+```++`has_role("owner")` is true only for owner. `has_role("member")` is true for member and owner. `has_role("editor")` is true for editor, member, and owner.++Therefore:++- `can_manage_projects` / `can_manage_agents` / `can_manage_instance` / `can_use_system` change from `has_role("owner")` to `has_role("member")`.+- `can_manage_access_members` is `has_role("owner")` (equivalently `is_instance_owner`).++## Member-management surface (owner-only)++These MUST require `can_manage_access_members` (not the broader `can_manage_instance`):++**App (`avibe`):**++- `PUT /api/permissions/authorized-users` (`vibe/ui_server.py` current-instance authorized-users PUT)+- Any other handler that adds / removes allowlist entries or changes an access role+- Ownership-transfer UI / API, if any local surface exists (keep owner-only)++**Backend (`avibe-backend`):**++- `instance.authorized_users.mutate` (allowlist add/remove/replace) — remains `canonicalOwnerRequired`+- Instance ownership transfer — remains `canonicalOwnerRequired`+- Pairing-key issue/rotate, custom hostname writes — unchanged, still canonical owner++`member` MUST be a valid **value** of an allowlist entry (so an owner can grant `member`), but a principal whose own role is `member` cannot mutate the allowlist.++## Token / session payload contract (cross-repo)++Produced by avibe-backend (`lib/security.ts` cloud token `vibe_instance_role`; `lib/oidc/authorization-context.ts`; `app/api/v1/instances/[instanceId]/user-token`).++Consumed by avibe (`vibe/authorization.py` `context_from_session_payload`, `vibe/remote_access.py` `_validated_authorization_payload`).++| Field | Type | Semantics |+|---|---|---|+| `vibe_instance_role` | `"owner" \| "member" \| "editor" \| "viewer"` | Instance access role. Unknown values fail closed (empty context). |+| `vibe_instance_access_source` | existing enum, unchanged | |+| `vibe_instance_kind` | `"personal" \| "organization"` | server-owned; unchanged |+| `vibe_instance_id` | string | pairing identity; unchanged |++Allowlist schema:++- `remote_access_allowlist_entries.role`: enum `["viewer", "editor", "member"]`, default `"viewer"`+- CHECK constraint updated to match+- `oauth_authorization_codes.instance_access_role`: enum `["owner", "editor", "viewer", "member"]` (nullable snapshot)+- `InstanceAccessRole` type includes `"member"`+- `InstanceAccessEntryRole = Exclude<InstanceAccessRole, "owner">` therefore becomes `"member" \| "editor" \| "viewer"` automatically++Project ACL (`access_role` `editor|viewer`) is **out of scope**.++## Persisted-shape rule++- Older releases never write `member`. Loaders MUST keep accepting `{owner, editor, viewer}` snapshots with no `member` field.+- An unknown role value fails closed (empty / unauthorized context), never crashes startup.+- Backend migration: add `member` to the allowlist CHECK; existing `viewer`/`editor` rows unchanged. Provide a load fixture covering a pre-`member` allowlist row.+- App: `context_from_session_payload` accepts `member`; payloads without it behave as today.+- Deferred `resource_user_context` snapshots: a `vibe_instance_role: "member"` written by this release must round-trip; a snapshot without the field keeps its previous role.++## HTTP / SSE policy (app)++- Default `/api/` minimum stays fail-closed.+- Member-reachable management routes are explicitly declared in `_MEMBER_HTTP_RULES`; unknown APIs remain Owner-only. Member-management, credential, host-lifecycle, ACL-write, and bulk-onboarding routes stay outside that allowlist.+- `POST /api/agents/default` requires the member tier and its setter requires `can_manage_agents`. The default remains advisory: assigning a private or scope-policy Agent does not widen its ACL, and callers who cannot use it degrade to another usable Agent at resolution time.+- Privileged SSE events (definitions/runs/vaults updated) currently require owner. **Member receives them** (they are instance-management events, not member-management). Implement by treating them as `has_role("member")`.+- Editor SSE (`queue.updated`) and viewer SSE unchanged.++## Frontend++- `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.+- 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)++Seed one principal of every existing role **plus** `member`, run the change, assert:++1. `member` can do every owner instance operation except member management and ownership transfer.+2. `member` cannot add/remove allowlist entries or change roles (HTTP 403 / capability false).+3. `owner` still can.+4. `editor` / `viewer` capabilities unchanged vs current master.+5. Unknown role still fails closed.+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.++## Lane split++### Lane B — avibe-backend (`codex`)++Repo: `avibe-backend`, branch from latest `origin/main`.+Scope (no-touch for lane A):++- `lib/types.ts` (`InstanceAccessRole`, `InstanceAccessEntryRole`)+- `lib/oidc/authorization-context.ts`+- `lib/db/schema.ts` allowlist + oauth snapshot enums + CHECKs+- new drizzle migration (allocate next revision against `origin/main` HEAD at rebase)+- `lib/instances.ts` `resolveInstanceAccess` (member is a valid allowlist role; editor-vs-viewer aggregation becomes editor-or-member-or-viewer with member > editor > viewer if any aggregation exists)+- `lib/security.ts` token mint `vibe_instance_role`+- `app/api/instances/[instanceId]/authorized-users` and v1 equivalent (accept `member` as an entry role; mutate still canonical-owner)+- store drizzle/memory allowlist writers+- tests covering schema, resolution, token projection, persisted pre-`member` fixtures+- i18n / console labels if the org console exposes the allowlist role picker++Do **not** touch avibe-app files.++### Lane A — avibe (`claude`)++Repo: `avibe`, branch from latest `origin/master`.+Scope (no-touch for lane B):++- `vibe/authorization.py` (roles, rank, capabilities, HTTP/SSE policy, projection)+- `core/vibe_agents.py` (Agent management/default gates and pre-catalog entitlement fallbacks)+- `vibe/ui_server.py` (authorized-users PUT and any sibling member-mutation gate → `can_manage_access_members`)+- `vibe/permissions.py` if it validates allowlist roles+- `vibe/remote_access.py` only if it independently validates the role set+- `storage/project_access_service.py` / `storage/resource_access_service.py` only if they hardcode `{owner,editor,viewer}` instead of using `has_role` / `INSTANCE_ROLES`+- `ui/src/lib/sessionInfo.ts`, `ui/src/features/permissions/*`, i18n en/zh+- focused tests: instance authorization, HTTP policy, permissions page / capability projection, persisted snapshot fixtures+- `ui/` build if UI files change++Do **not** touch avibe-backend files. Consume the token field `vibe_instance_role: "member"` as documented; if backend is unmerged, tests stub that payload.++## Merge / deploy order++Backend first (token + allowlist can already emit `member`; old app treats unknown-or-absent as fail-closed / ignore). App second (understands `member`, exposes the capability). Independent PRs, no stacked PR. App PR body declares "expects backend #NNNN merged first" once the backend PR exists.++## Out of scope++- Changing organization roles+- Adding `member` to project ACL bindings+- Billing / plan gates+- Renaming the organization role `member`++## Addendum: Agent management alignment (2026-08-21)++### Divergence found++The initial implementation left three authorization layers inconsistent. The capability projection granted `can_manage_agents` to `member`, and the HTTP allowlist admitted Agent CRUD, but `storage/resource_access_service.py::_policy_allows_management` still required every non-owner to match the resource policy's `owner_user_id`. Built-in SYSTEM Agents such as `claude` and `codex` normally have no policy row, so the missing-policy fail-closed path denied every member mutation even though the capability and router both admitted it.++### Owner decisions++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.++### Pre-catalog fallback audit++| Site | Decision | Rationale |+|---|---|---|+| `ensure_agent_selection_access` missing-row fallback | Include `member` via `has_role("member")` | A historical backend-name selector is Agent entitlement compatibility, not Owner identity. |+| `ensure_agent_name_access` legacy task/watch binding fallback | Keep `is_instance_owner` | The fallback preserves executable pre-catalog definitions; a member-created binding is new data and must reference a real catalog Agent because execution deliberately requires that row. |+| `ensure_session_agent_access` backend-only session fallback | Include `member` via `has_role("member")` | Dispatching a persisted pre-catalog session is compatibility for Agent use/management, not ownership or migration control. |+| `_require_agent_onboarding_access` | Keep `is_instance_owner` | Onboarding inventories and claims every policy-less Agent in one one-way migration; its instance-wide migration authority is distinct from per-Agent management. |++The remote-Owner task/watch write fallback can still admit a missing legacy name while `ScheduledTaskService._require_execution_agent_access` requires a catalog row at execution. That divergence predates this change and is a known latent issue outside this alignment's scope; it does not justify admitting new member-created bindings. New routing must reference a real Vibe Agent catalog row.++### Current-master default semantics++The original follow-up brief referenced the pre-PR-#1606 audience-wide assignment predicate. PR #1606 had already replaced that model on `master`: an instance default is advisory, and ACL enforcement occurs per principal when the default is resolved. This alignment deliberately preserves #1606. A member may assign a private or scope-policy Agent as the default; a principal who cannot use it degrades to another usable Agent without changing the configured default or widening the target ACL.diff --git a/storage/resource_access_service.py b/storage/resource_access_service.pyindex 7aae19f56..f998250cb 100644--- a/storage/resource_access_service.py+++ b/storage/resource_access_service.py@@ -1368,6 +1368,8 @@ def _policy_allows(def _policy_allows_management(context: ResourceUserContext, policy: Mapping[str, Any] | None) -> bool:if context.is_instance_owner:return True+ if context.has_role("member"):+ return Trueif policy is None:return False# Skills and Vault ACL rows are retained for compatibility, but MVP runtimediff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.pyindex c3f194553..5dcbb1179 100644--- a/tests/test_instance_authorization.py+++ b/tests/test_instance_authorization.py@@ -257,7 +257,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> Nroute must inherit the same Instance role as the rest of that capability.The member surface is the opposite shape: an explicit allow-list, so anunknown API fails closed to Owner along with allowlist mutation,- pairing-identity writes, and instance-wide default-agent routing.+ pairing-identity writes, and bulk Agent onboarding."""assert _EDITOR_HTTP_NAMESPACES == (@@ -333,6 +333,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> Nmember_examples = (("POST", "/api/agents"),("POST", "/api/agents/import"),+ ("POST", "/api/agents/default"),("PATCH", "/api/agents/demo"),("DELETE", "/api/agents/demo"),("PUT", "/api/models/agents/codex/chain"),@@ -370,8 +371,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N# Host reach.("POST", "/api/browse"),("POST", "/api/browse/mkdir"),- # Instance-wide Agent routing and bulk migration.- ("POST", "/api/agents/default"),+ # Bulk migration.("GET", "/api/agent-onboarding"),("POST", "/api/agent-onboarding"),)@@ -1114,15 +1114,13 @@ def test_pair_is_forbidden_for_member_and_succeeds_for_owner(monkeypatch, tmp_paassert paired == [("key", "https://avibe.bot", "avibe")]-def test_member_cannot_set_instance_default_agent(monkeypatch, tmp_path) -> None:- """Instance-wide default routing is Owner-only, and that is the whole gate.+def test_member_can_set_instance_default_agent(monkeypatch, tmp_path) -> None:+ """Default selection follows Agent management at service and HTTP layers.- A member is refused twice over -- by the store's own permission check and by- the route policy -- and the Owner may then point routing at any Agent,- including one narrower than the instance audience. Nothing about the target's- policy shape is validated here: a default is advisory and the ACL is enforced- per-principal at use time (``core.vibe_agents.resolve_usable_default_agent``),- which is covered in ``tests/test_resource_acl_agents.py``.+ Member may point routing at any Agent it can manage, including one narrower+ than the instance audience. Editor and Viewer stay denied. The default stays+ advisory: per-principal degradation remains covered in+ ``tests/test_resource_acl_agents.py``."""from core.vibe_agents import VibeAgentAccessError, VibeAgentStore@@ -1149,9 +1147,15 @@ def test_member_cannot_set_instance_default_agent(monkeypatch, tmp_path) -> Nonebackend="codex",user_context=member,)- with pytest.raises(VibeAgentAccessError):- store.set_default_agent_name(private_agent.name, user_context=member)+ for role in ("viewer", "editor"):+ with pytest.raises(VibeAgentAccessError):+ store.set_default_agent_name(+ private_agent.name,+ user_context=_context(role, remote=True),+ )assert store.get_default_agent_name() == before+ store.set_default_agent_name(private_agent.name, user_context=member)+ assert store.get_default_agent_name() == private_agent.namefinally:store.close()@@ -1175,11 +1179,11 @@ def test_member_cannot_set_instance_default_agent(monkeypatch, tmp_path) -> Nonebase_url="https://alex.avibe.bot",environ_base=remote_peer(),)- assert member_response.status_code == 403- assert member_response.get_json()["error"] == "instance_access_forbidden"+ assert member_response.status_code == 200+ assert member_response.get_json()["default_agent_name"] == "member-private"store = VibeAgentStore()try:- assert store.get_default_agent_name() == before+ assert store.get_default_agent_name() == "member-private"finally:store.close()diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.pyindex 780bd1825..dd75ff68a 100644--- a/tests/test_resource_acl_agents.py+++ b/tests/test_resource_acl_agents.py@@ -12,6 +12,7 @@ from core.vibe_agents import (VibeAgent,VibeAgentAccessError,VibeAgentStore,+ ensure_agent_name_access,ensure_agent_selection_access,ensure_default_agent_access,ensure_session_agent_access,@@ -131,7 +132,7 @@ def _restricted_agent_keys() -> list[str]:def _set_default_agent_row(store: VibeAgentStore, agent_name: str) -> None:- """Point instance-wide routing at an Agent, bypassing the Owner-only gate.+ """Point instance-wide routing at an Agent, bypassing the management gate.Defaults are advisory: the setter accepts any Agent its caller may manage,including one whose policy admits less than the whole instance. Writing the@@ -236,10 +237,9 @@ def test_owner_can_create_agent_without_a_trusted_local_identity(monkeypatch, tmdef test_active_org_agent_management_is_allowed_inside_the_store(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))store, agents = _seed_agents_with_policies()- # Resource ACL management stays reserved to owner/admin Organization roles- # under the temporary full-access rollout (see #1343); a plain member has- # no management authority.- member = _organization_context("member-1")+ member = _organization_context("member-1", instance_role="member")+ editor = _organization_context("editor-1")+ resource_owner_editor = _organization_context("owner-1")admin = resource_access_service.ResourceUserContext(subject="admin-1",email="[email protected]",@@ -253,19 +253,56 @@ def test_active_org_agent_management_is_allowed_inside_the_store(monkeypatch, tm)owner = _organization_context("owner-1", instance_role="owner")try:+ builtin = store.ensure_builtin_default_agent(backend="codex")+ with store.engine.connect() as connection:+ # Member management is owner-equivalent across every policy shape,+ # including another subject's policy and a built-in with no row.+ for agent in (*agents.values(), builtin):+ assert resource_access_service.can_manage_resource_acl(+ member,+ "agent",+ agent.id,+ connection=connection,+ )+ assert not resource_access_service.can_manage_resource_acl(+ editor,+ "agent",+ agent.id,+ connection=connection,+ )+ for agent in agents.values():+ assert resource_access_service.can_manage_resource_acl(+ resource_owner_editor,+ "agent",+ agent.id,+ connection=connection,+ )+ assert not resource_access_service.can_manage_resource_acl(+ resource_owner_editor,+ "agent",+ builtin.id,+ connection=connection,+ )+with pytest.raises(VibeAgentAccessError):- store.update(agents["public"].name, description="member update", user_context=member)+ store.update(agents["public"].name, description="editor update", user_context=editor)with pytest.raises(VibeAgentAccessError):- store.remove(agents["public"].name, user_context=member)+ store.remove(agents["public"].name, user_context=editor)+ member_updated = store.update(+ agents["public"].name,+ description="member update",+ user_context=member,+ )+ assert member_updated.description == "member update"updated = store.update(agents["public"].name, description="admin update", user_context=admin)assert updated.description == "admin update"- store.set_default_agent_name(agents["public"].name, user_context=admin)+ store.set_default_agent_name(agents["public"].name, user_context=member)assert store.get_default_agent_name() == agents["public"].name# A default is advisory: an Agent narrower than the whole audience is a# legitimate assignment, because the ACL is enforced per-principal at use# time (see ``resolve_usable_default_agent``) rather than at bind time.for key in _restricted_agent_keys():- store.set_default_agent_name(agents[key].name, user_context=admin)+ store.set_default_agent_name(agents[key].name, user_context=member)assert store.get_default_agent_name() == agents[key].namestore.set_default_agent_name(agents["public"].name, user_context=admin)assert store.remove(agents["public"].name, user_context=admin) is True@@ -594,29 +631,86 @@ def test_personal_install_default_routing_never_degrades(monkeypatch, tmp_path)store.close()-def test_missing_agent_selector_fails_closed_for_editor_only(monkeypatch, tmp_path) -> None:+def test_legacy_runtime_fallbacks_follow_management_entitlement(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))store = VibeAgentStore()try:with store.engine.connect() as connection:- with pytest.raises(VibeAgentAccessError):- ensure_agent_selection_access(- connection,- agent_name="deleted-legacy-agent",- user_context=_organization_context("member-1"),- )- assert (- ensure_agent_selection_access(- connection,- agent_name="deleted-legacy-agent",- user_context=_organization_context("owner-1", instance_role="owner"),- )- is None- )+ for role in ("viewer", "editor", "member", "owner"):+ context = _organization_context(f"{role}-1", instance_role=role)+ if context.can_manage_agents:+ assert (+ ensure_agent_selection_access(+ connection,+ agent_name="codex",+ user_context=context,+ )+ is None+ )+ assert (+ ensure_session_agent_access(+ connection,+ {"agent_backend": "codex"},+ user_context=context,+ )+ is None+ )+ else:+ with pytest.raises(VibeAgentAccessError):+ ensure_agent_selection_access(+ connection,+ agent_name="codex",+ user_context=context,+ )+ with pytest.raises(VibeAgentAccessError):+ ensure_session_agent_access(+ connection,+ {"agent_backend": "codex"},+ user_context=context,+ )finally:store.close()+def test_member_cannot_save_non_catalog_task_or_watch_bindings(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ context = _organization_context("member-1", instance_role="member")+ task_store = ScheduledTaskStore(tmp_path / "tasks.json")+ watch_store = ManagedWatchStore(tmp_path / "watches.json")++ with pytest.raises(ValueError):+ task_store.add_task(+ session_key="slack::channel::C123",+ prompt="run task",+ schedule_type="cron",+ agent_name="deleted-legacy-agent",+ cron="0 * * * *",+ timezone_name="UTC",+ user_context=context,+ )+ with pytest.raises(ValueError):+ watch_store.add_watch(+ name="legacy watch",+ session_key="slack::channel::C123",+ command=["true"],+ shell_command=None,+ prefix=None,+ cwd=str(tmp_path),+ mode="once",+ timeout_seconds=1,+ lifetime_timeout_seconds=0,+ retry_exit_codes=[75],+ retry_delay_seconds=1,+ post_to=None,+ deliver_key=None,+ agent_name="deleted-legacy-agent",+ user_context=context,+ )++ assert task_store.list_tasks() == []+ assert watch_store.list_watches() == []++def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path, paired=True, instance_kind="organization")@@ -669,6 +763,7 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmpmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path, paired=True, instance_kind="organization")store, agents = _seed_agents_with_policies()+ builtin = store.ensure_builtin_default_agent(backend="codex")private_agent = agents["private"]_set_default_agent_row(store, private_agent.name)store.close()@@ -697,8 +792,7 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmpassert {"public-agent", "scope-agent"} == {agent["name"] for agent in catalog.get_json()["agents"]}- # A plain active Organization member is denied mutations under the- # Resource ACL boundary.+ # Editor and Viewer remain below the Agent-management tier.denied_mutation = client.patch("/api/agents/public-agent",json={"description": "member update"},@@ -707,30 +801,57 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmpenviron_base=_remote_peer(),)assert denied_mutation.status_code == 403- # Only the Instance Owner can manage Agents.client.set_cookie(remote_access.SESSION_COOKIE_NAME,_organization_cookie(config,- subject="admin-1",+ subject="viewer-1",groups=["group-engineering"],- instance_role="owner",- organization_role="admin",+ instance_role="viewer",+ ),+ domain="alex.avibe.bot",+ )+ denied_viewer_mutation = client.patch(+ f"/api/agents/{builtin.name}",+ json={"enabled": False, "model": "gpt-5.4-mini"},+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert denied_viewer_mutation.status_code == 403++ # Member can mutate a policy-less built-in and another subject's Agent.+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _organization_cookie(+ config,+ subject="member-1",+ groups=["group-engineering"],+ instance_role="member",),domain="alex.avibe.bot",)- mutation = client.patch(+ builtin_mutation = client.patch(+ f"/api/agents/{builtin.name}",+ json={"enabled": False, "model": "gpt-5.4-mini"},+ headers=csrf_headers(client, "https://alex.avibe.bot"),+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )+ assert builtin_mutation.status_code == 200+ assert builtin_mutation.get_json()["agent"]["enabled"] is False+ assert builtin_mutation.get_json()["agent"]["model"] == "gpt-5.4-mini"+ member_mutation = client.patch("/api/agents/public-agent",- json={"description": "admin update"},+ json={"description": "member update"},headers=csrf_headers(client, "https://alex.avibe.bot"),base_url="https://alex.avibe.bot",environ_base=_remote_peer(),)- assert mutation.status_code == 200- # Instance-wide default routing is Owner-only, but the Agent it points at is- # not constrained by policy shape: the default is advisory and the ACL is- # enforced per-principal at use time, so a narrower Agent is accepted here- # and degrades for whoever cannot use it.+ assert member_mutation.status_code == 200++ # A member may set the advisory instance default to a narrower Agent. The+ # ACL is still enforced per principal when that default is resolved.for key in _restricted_agent_keys():default_mutation = client.post("/api/agents/default",@@ -740,6 +861,16 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmpenviron_base=_remote_peer(),)assert default_mutation.status_code == 200+ degraded_context = _organization_context("editor-1", group_ids=None)+ engine = get_cached_sqlite_engine()+ with engine.connect() as connection:+ configured_default = resolve_effective_default_agent(connection)+ degraded_default = ensure_default_agent_access(+ connection,+ user_context=degraded_context,+ )+ assert configured_default.id == agents[_restricted_agent_keys()[-1]].id+ assert degraded_default.id == agents["public"].idshared_default = client.post("/api/agents/default",json={"name": agents["public"].name},@@ -749,7 +880,7 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmp)assert shared_default.status_code == 200- engine = get_cached_sqlite_engine()+ editor_context = _organization_context("editor-1")with engine.begin() as connection:scope_id = upsert_scope(connection,@@ -764,16 +895,24 @@ def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmpagent_backend="codex",agent_name=agents["scope"].name,agent_id=agents["scope"].id,- user_context=context,+ user_context=editor_context,)assert session["agent_id"] == agents["scope"].idbackend_only = workbench_sessions_service.create_session(connection,scope_id=scope_id,agent_backend="codex",- user_context=context,+ user_context=_organization_context("member-1", instance_role="member"),)assert backend_only["agent_backend"] == "codex"+ assert (+ ensure_session_agent_access(+ connection,+ backend_only,+ user_context=_organization_context("member-1", instance_role="member"),+ )+ is None+ )task_store = ScheduledTaskStore(tmp_path / "tasks.json")watch_store = ManagedWatchStore(tmp_path / "watches.json")diff --git a/ui/src/features/permissions/PermissionsPage.test.tsx b/ui/src/features/permissions/PermissionsPage.test.tsxindex 7a9211143..ca828a9e8 100644--- a/ui/src/features/permissions/PermissionsPage.test.tsx+++ b/ui/src/features/permissions/PermissionsPage.test.tsx@@ -281,7 +281,7 @@ describe('PermissionsPage state model', () => {expect(screen.queryByRole('button', { name: /permissions.actions.addAccess/ })).toBeNull();});- it('shows an Instance Member both access tabs read-only', async () => {+ it('shows a Member both access tabs read-only', async () => {const withMember = response();withMember.projection.access.entries = [{kind: 'email',@@ -308,7 +308,7 @@ describe('PermissionsPage state model', () => {expect(screen.queryByRole('button', { name: 'permissions.actions.manage' })).toBeNull();});- it('offers Instance Member in the access role picker for owners', async () => {+ it('offers Member in the access role picker for owners', async () => {const user = userEvent.setup();renderPage();diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9091a6e4e..a749a2cae 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4736,7 +4736,7 @@},"roles": {"owner": "Owner",- "member": "Instance Member",+ "member": "Member","editor": "Editor","viewer": "Viewer"},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex ea6d916e1..49fd4c315 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4736,7 +4736,7 @@},"roles": {"owner": "所有者",- "member": "Avibe 成员",+ "member": "成员","editor": "编辑者","viewer": "查看者"},diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 31aeee6da..e8ea5678b 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -468,12 +468,12 @@ _REMOTE_ACCESS_MEMBER_HTTP_RULES = tuple(# ``require_bind``.# * bulk Agent onboarding, a one-way instance-wide migration whose GET# discloses every Agent row and whose POST claims every policy-less one under-# the caller's private ACL, and instance-wide default routing.+# the caller's private ACL._MEMBER_HTTP_RULES = tuple((method, re.compile(pattern))for method, pattern in (- # can_manage_agents: Agent CRUD. /api/agents/default and- # /api/agent-onboarding are instance-wide and stay Owner by default.+ # can_manage_agents: Agent CRUD and instance-wide default selection.+ # /api/agent-onboarding is a bulk migration and stays Owner by default.## ``/api/agent/<name>/install`` is absent on purpose, and so is its job# status sibling: the handler runs a package manager, a self-update, or a@@ -488,6 +488,7 @@ _MEMBER_HTTP_RULES = tuple(("PATCH", r"^/api/agents/[^/]+$"),("DELETE", r"^/api/agents/[^/]+$"),("POST", r"^/api/agents/import$"),+ ("POST", r"^/api/agents/default$"),# can_manage_agents: selecting among already-authenticated model sources.# Adding or re-authenticating a source is credential work and stays Owner.("GET", r"^/api/models/agents$"),@@ -617,8 +618,8 @@ def required_instance_role(method: str, path: str) -> str | None:is never reachable by a role that predates it. The member rank widens onlythe routes listed in ``_MEMBER_HTTP_RULES`` plus the read/ops quartet under``/api/remote-access``; access administration, credential and lifecycle- routes, ACL writes, bulk Agent migration, and instance-wide default-agent- routing are Owner by that default rather than by per-route exception.+ routes, ACL writes, and bulk Agent migration are Owner by that default+ rather than by per-route exception."""return http_authorization_policy(method, path).minimum_role