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(permissions): align Member current-instance operations (#2030)
Maxa77558ecea37
diff --git a/core/show_pages.py b/core/show_pages.pyindex 72ddcbc6d..66c688e38 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -1145,12 +1145,8 @@ class ShowPageStore:returnfrom storage import project_access_service- scope_id = connection.execute(- select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id).limit(1)- ).scalar_one_or_none()- project_id = project_access_service.project_id_from_scope_id(scope_id)- if project_id is None or not project_access_service.role_allows(- project_access_service.get_effective_project_role(connection, user_context, project_id),+ if not project_access_service.role_allows(+ project_access_service.get_effective_session_role(connection, user_context, session_id),"editor",):raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")diff --git a/core/web_push_notifications.py b/core/web_push_notifications.pyindex 28090f821..5be985642 100644--- a/core/web_push_notifications.py+++ b/core/web_push_notifications.py@@ -959,7 +959,7 @@ def _badge_count_for_user_key(# Legacy remote messages predate persisted authorization claims. Keep# delivering eligible content, but never attach a machine-global count.return 0- if context.is_instance_owner:+ if context.can_manage_instance:return messages_service.total_unread(conn, platform="avibe")from storage import project_access_servicediff --git a/docs/plans/instance-access-role-member.md b/docs/plans/instance-access-role-member.mdindex b613316d2..c642aca0b 100644--- a/docs/plans/instance-access-role-member.md+++ b/docs/plans/instance-access-role-member.md@@ -1,5 +1,15 @@# Instance access role `member` (owner minus member management)+> **Superseded Member operation scope (2026-09-17):**+> [Instance Member operations](member-instance-operations.md) is authoritative for+> Member resource use and runtime visibility on both instance kinds. Member is a+> current-instance operator; the older Organization Agent/Project/session ACL+> restrictions below are historical and no longer apply to Member. Editor/Viewer,+> true Owner identity, access-administration and ownership safeguards remain.+> Existing Show publication policy and shared inbox read-state semantics remain+> unchanged. Shipped pre-catalog Member selection/session fallbacks are retained;+> new Task/Watch binding names still require catalog entries.+Issue: https://github.com/avibe-bot/avibe/issues/1596Related: https://github.com/avibe-bot/avibe/pull/1562 (Personal editor resource-ACL semantics — the capability model this role plugs into)diff --git a/docs/plans/member-instance-operations.md b/docs/plans/member-instance-operations.mdnew file mode 100644index 000000000..8298d0c3c--- /dev/null+++ b/docs/plans/member-instance-operations.md@@ -0,0 +1,358 @@+# Instance Member operations++Status: approved behavior contract, implementation under validation (2026-09-17).+Orchestrator: Avibe Session `sesnps2m743r5`.+Baseline: `06a864947` on `avibe-bot/avibe` master.+Branch: `fix/member-instance-operations`.++## Intent and precedence++An Instance Member can operate and manage the entire current instance but cannot+change access grants, instance identity, or ownership. This applies to Personal+and Organization instances. Organization membership alone grants no instance+authority. The owner explicitly approved implementing this Member contract while+deferring the unified Editor/Viewer redesign.++Example: a Member can already edit a built-in Agent and set it as default, but+the Organization resource-use check hides that same Agent when no policy row+exists and prevents chat. The intended result is one consistent list/detail/+selection/chat path, including existing Projects and sessions.++This contract supersedes the retained Member resource-use and private runtime+record restrictions in `member-management-parity.md` and+`instance-access-role-member.md`. Their access-administration safeguards remain+authoritative. Update those documents to make this precedence explicit.++## Frozen behavior++1. **Current-instance operation scope.** A validated Instance Member receives+ Owner-equivalent operational access to resources and runtime records held by+ this instance. Agent, Project and session list/read/use/edit/execute paths must+ agree. Missing resource policy, another resource owner, restrictive bindings,+ unmatched policy groups, or legacy policy metadata must not narrow Member+ operations within this instance. The grant does not reach another instance+ or create cloud organization-administration rights.+2. **Access and identity remain protected.** Member cannot change authorized+ principals, access-member enabled/admin/role state, binding codes, Project or+ resource access policy, pairing identity, session-signing identity or instance+ ownership. Existing protected mixed writers retain fresh-state, atomic+ comparisons, omission/alias/concurrency handling, and honest rejection.+ Operational writes must not silently rewrite stored ACL or ownership rows.+ Ordinary creation keeps its existing ownership/lifecycle semantics; bulk+ ownership onboarding remains protected.+3. **Keep identity distinct.** `is_instance_owner` remains false for Member.+ Reuse the existing appropriate management capabilities as the owner of+ operational scope; do not mint another role or a redundant permission axis.+ Memory principal isolation, terminal attachment identity, per-user preferences,+ notification subscriptions and protected Vault authorization/proofs still+ apply where they also apply to Owner. Preserve the existing shared+ `messages.read_at` and global Workbench toggle semantics; this repair does not+ introduce per-person read state or merge identity where it already isolates.+ IM binding/admin is a separate identity system and is not elevated by a cloud Instance Member grant.+4. **Preserve other roles.** Editor, Viewer, unauthenticated and invalid-context+ behavior remain unchanged. Existing restrictive resource rules still apply to+ those roles. Preserve CSRF, signed identity validation, resource existence,+ Agent enabled/available checks and other ordinary execution preconditions.+ Preserve shipped Member pre-catalog selection/session fallbacks. Do not expand+ the separate Owner-only missing-name fallback for new Task/Watch bindings:+ those Member bindings still require an existing catalog Agent. Released Member+ deferred snapshots participate in the existing binding migration. A repair of+ a previously completed pass must prove its original pairing and row cutoff;+ it cannot make later unbound work executable.+5. **Effect-based policy, bounded implementation.** Evolve the existing central+ capabilities and route policy. Member operational permission should follow+ that common decision, while access/identity effects retain explicit gates.+ Do not default-allow unknown APIs, redefine Owner, or rebuild the complete+ four-role policy framework. Registered routes must remain deliberately+ classified and covered by the existing complete-router invariant.+6. **Project/session identity and Show policy.** Effective Member roles stay+ `member`, never synthetic `owner`. Project archive is reversible: Member+ can list archived Projects explicitly, read their record context and reopen+ their folder like Owner. Missing Projects still fail; Editor/Viewer keep+ archived-Project denial. Archived sessions remain inert under the existing+ mutation/fork/execution guards. Project bootstrap, Show and deferred execution+ use the same effective-role decision rather than treating archive as an ACL.+ Show's single `/p` publication/link-visibility/limited-email axis already admits Editors.+ Only session-dependent create/get/ensure authorization changes here; existing+ sharing/owner-control guards stay unchanged. Unified publication/role design+ is deferred with Editor/Viewer.++## Required consumers++- Agent discovery, detail, selection/default resolution, new chat, existing chat,+ forks, and Harness bindings/execution must consume the same Member operation+ scope. Default Agent remains advisory for principals still subject to ACL.+- Project and session operations include restricted Projects, sessions without a+ Project, and dependent Show session operations. Lists, details, mutation,+ search/inbox, graph/running records, callback source metadata and notifications+ must agree with the operation scope. Preserve per-user delivery identity and+ read/preferences state.+- Member management event delivery must survive both event-role authorization+ and runtime visibility filtering. Cover real publisher payloads, including+ `vaults.updated`, `definitions.updated`, sessionless `runs.updated`, and+ `remote_access.quality.changed`. Lower-role events remain scoped.+- Skill usage and runtime observations are instance operational diagnostics.+ Audit the `vibe data skill-usage`, `skill_usage_daily` and `agent_events` gates;+ admit Member where the only restriction is Owner operational authority.+ Preserve SQL read-only enforcement, raw-secret denial and principal-scoped data.+- RemoteAccess pairing/re-pair controls must reflect the retained pairing gate+ for paired and unpaired Member views, using existing disabled/read-only and+ localization patterns. Ordinary transport controls stay usable. No redesign.++## Implementation scope++One coherent application lane owns the change and its full PR lifecycle. No+backend repository change is currently justified by the audit.++Allowed production scope: `vibe/authorization.py`, `vibe/ui_server.py`,+`vibe/api.py`, narrow diagnostic guards in `vibe/cli.py` and+`storage/read_only_query.py`, `storage/resource_access_service.py`,+`storage/project_access_service.py`, `storage/workbench_sessions_service.py`,+`storage/messages_service.py`, `core/vibe_agents.py`,+`core/services/session_fork.py`, `core/show_pages.py`,+`core/web_push_notifications.py`, and existing Harness/resource consumer modules+only where a traced Member authorization call path requires alignment.+PM-approved narrow extension (2026-09-17): `vibe/i18n/en.json` and+`vibe/i18n/zh.json`, only the existing `data.skillUsage.ownerRequired` and+`data.skillUsage.helpCommand` values, so diagnostic denial and parser help+accurately name Member or Owner; no new key. The help value was approved during+the second review diagnosis below.+UI scope: `ui/src/components/RemoteAccess.tsx`, its focused tests, and existing+EN/ZH translation files only as necessary. Related focused tests, permission+scenario catalog/harness and concise permission documentation are allowed.++Do not modify unrelated runtime/Memory features, dependency versions, schema,+cloud role aggregation, onboarding design, Editor/Viewer policy, production+state or the primary checkout. Report any required scope extension to the+orchestrator with the concrete call path first.++## Verification invariants++1. Seed each existing resource-policy and session shape in test-owned storage;+ a Member can complete the same current-instance operation through discovery,+ detail, mutation, execution and dependent visibility consumers. Assert the+ original ACL/ownership records remain unchanged by the permission fix.+2. Exercise signed remote HTTP + CSRF through a real Member Agent/session flow,+ including an Organization built-in Agent without a policy. Use real local+ services/storage and stub external providers/host operations/IPC only after+ authorization; verify stored mutations and resulting execution dispatch.+3. Compare existing roles and both instance kinds. Assert retained Member denials+ before protected effects, and unchanged Editor/Viewer scope. Preserve relevant+ #2004 mixed-write, Vault proof and principal-isolation coverage.+4. Consume real SSE generator/broker output for publisher-shaped management and+ scoped events, proving delivery rather than only testing one predicate.+5. Render RemoteAccess under actual capability providers, exercise Member+ pairing controls and normal operations, and assert no forbidden pair request;+ preserve the Owner flow. This is existing UI permission binding, not a visual+ redesign requiring new mockups.+6. Update the existing permissions scenario catalog and executable scenarios with+ stable IDs. Run focused Python/UI tests, Ruff for changed Python, and UI build.+ Record evidence layers and any manual end-to-end gap without claiming a live+ tenant fix. All probes must be hermetic.++## Delivery and acceptance++- Follow `AGENTS.md` and `.agents/skills/pr-delivery-loop/SKILL.md` in the task+ worktree. Open one non-draft PR to current master with the behavior contract,+ scenario IDs, evidence and retained-boundary ledger. No manual Codex trigger:+ current repository policy delegates triggering to cyhhao's automation.+- Require exact-head Codex pass, expected CI green, zero unresolved threads,+ clean merge state and independent orchestrator diff/consumer-test verification.+ Use one durable lane PR/CI Watch and one independent orchestrator gate Watch.+ Enforce review root-cause circuit breaking before another fix push.+- Do not merge, deploy, install, restart the local service, alter production+ permissions, or repair regression pairing as a side effect. Owner approval is+ still required for merge/release. Tests may use the sanctioned local Incus+ runner with test-owned state if needed; preserve all existing regression data.+- Acceptance after authorized integration: an Instance Member opens Agents,+ selects a built-in Agent and completes a conversation; opens existing Project+ and standalone sessions; receives live management/session updates; can operate+ RemoteAccess transport but cannot pair or edit access grants. Editor/Viewer+ remain restricted exactly as before.++## Work status++- [x] Complete and independently verify the three-lane baseline audit.+- [x] Recover the owner discussion and freeze the approved Member semantics.+- [x] Implement and validate in the isolated task worktree.+- [ ] Complete exact-head review and CI; independently verify the final diff.+- [ ] Present the concrete merge-ready PR and residual acceptance steps.++## Implementation and evidence map++The existing management capabilities own current-instance operations. Resource+use, Project/session projection, runtime list/graph/search/inbox/media, callback+source metadata, notification badge visibility and SSE filtering consume that+scope. Owner identity and protected access writers remain independent. The+runtime helper was renamed only at its consumers; bulk onboarding retains an+explicit true-Owner guard. No schema, dependencies or cloud aggregation changed.++- PERMISSIONS-014: Personal/Organization signed HTTP + CSRF Agent/session+ lifecycle, ACL-shape comparison, Project archive/restore and mutation/reuse,+ real Show store, real fork reservation, runtime discovery and persisted Harness+ bindings. Signed HTTP Deliveries also pass the real execution-time+ `SessionTurnManager._remote_delivery_execution_denial` before provider acceptance+ is stubbed; a changed pairing still rejects those persisted Deliveries. Released+ Task/Watch/Run/Delivery fixtures also exercise fresh and completed-marker+ migration through Harness admission and the queued-chat execution recheck,+ preserving principal attributes and recalculating the Delivery snapshot hash.+- PERMISSIONS-015: protected access/pairing/onboarding denials, missing resources,+ disabled Agent, existing lower-role and compatibility checks.+- PERMISSIONS-016: actual SSE generator and broker with publisher-shaped Vault,+ definition, sessionless run, tunnel-quality and session events; unknown events+ stay Owner-only and Editor/Viewer remain scoped.+- PERMISSIONS-017: per-subject Web Push subscription storage and badge/delivery+ filtering; message authorship remains the signed subject. Callback source+ enrichment now follows the same instance operation scope.+- PERMISSIONS-018: RemoteAccess rendered with the actual authorization provider;+ paired/unpaired Member pairing cannot submit, transport works and Owner pairs.+- PERMISSIONS-019: real skill diagnostics/clear storage and read-only SQL including+ CTEs; Member admitted, lower roles denied, SQL writes/raw Vault secrets denied.++Known by design: Show publication policy is unchanged; inbox read markers and+Workbench toggles retain their existing shared semantics. Memory principal,+terminal attachment identity, Vault proofs, IM admin and protected mixed writes+are unchanged. Historical Member selection/session fallbacks remain supported;+new Task/Watch names still resolve the catalog. Local tests stub execution IPC+and provider/host effects after authorization; no tenant or live provider result+is claimed. Post-merge acceptance still needs an authorized real Member browser+conversation and live transport/session updates in the regression instance.++Completed-marker repair uses the existing key and only released versions 1/2+with a valid absolute completion time, exact instance/kind and a matching ready+binding. Only Member records created/submitted and last updated strictly before+that original cutoff qualify. Completion retains the original timestamp and seals+version 3; later rows cannot reopen the opportunity. Missing/corrupt/unknown or+sealed provenance, equal-second/later row clocks, another pairing, contradictory+claims and terminal work remain unchanged. Ambiguous historical work may therefore+remain denied; this repair does not guess identity or authorize recovery by+re-pairing. Other roles do not enter the completed-marker repair.++The cutoff attributes the legacy row and its remote authorization snapshot; it+is not evidence that every byte of the row stayed unchanged. Released user edits+that replace `resource_user_context` advance `updated_at`; timestamped lifecycle+writes and new creation/submission clocks also exclude post-cutoff work.+Diagnostic stamps/clears and stable-Agent reference canonicalization+can preserve both the authorization snapshot and the lifecycle clock. Such rows+remain eligible: under the shared writer reservation, repair preserves their+current metadata/columns and every original principal/claims field, adding only+the missing instance ID/kind to the snapshot. No complete mutation history is+claimed. Soft deletion can also preserve `updated_at`; repair does not revive it.+Execution still applies existing lifecycle, Agent and pairing rules.++First review round: one findings-bearing head (`02b96d475`), one root cause+(released deferred Member compatibility). The repair and stale Member Project/Vault+expectations have 474 focused regression passes, including the negative marker,+row, binding and terminal-work cases. Project/Resource ACL rows and protected+Vault approval requirements remain intact.++Focused local evidence: 493 Python tests across permissions, Agent/Project/session+ACL consumers, messages/notifications, forks and diagnostics; 188 retained+Skills/terminal/Memory-admission/Permissions scenarios; 32 Show sharing cases;+6 RemoteAccess render tests; changed-file Ruff and production UI build. An+additional broad Show run was interrupted during unrelated runtime preparation+network I/O after three cases; it is not counted as passing. Targeted sharing+coverage above replaces that irrelevant preparation path. CI supplies the full+repository gate. All state is test-owned; execution/provider IPC is stubbed.+++## Review circuit-breaker diagnosis and resumption++Three findings-bearing heads were independently inventoried by PM:++- `02b96d475`, review `5237360393`, thread `PRRT_kwDOPbFPYs6jaBH1`:+ Member was omitted from legacy deferred binding and previously completed+ markers skipped the omitted rows. Fixed with the conservative proof above.+- `e6987dc74`, review `5237677043`, thread `PRRT_kwDOPbFPYs6jaoeb`:+ cutoff/provenance reads and ID-only updates were not one serialized decision.+ This repeats the deferred migration compatibility/safety class, so the lane+ stopped before editing or pushing. Thread `PRRT_kwDOPbFPYs6jaoeR` on this head+ separately identified stale Owner-only EN/ZH Skill-usage parser help.+- `e943feee7`, review `5238087139`, thread `PRRT_kwDOPbFPYs6jbZHm`:+ released diagnostic writers change Run metadata without advancing `updated_at`.+ This is the third head in the same provenance/safety class; the lane stopped+ before editing/pushing and PM independently diagnosed the proof invariant.++PM reproduced a lost concurrent Task metadata update with two real SQLite/WAL+engines and independently audited the call paths. Importer's migration file lock+only excludes other migrations; runtime writers remain possible, and+`engine.begin()` alone does not reserve SQLite's writer slot. The proof rule was+correct only if the marker, config/binding, row eligibility and seal were evaluated+against one serialized database state.++PM authorized resumption on 2026-09-17 with a shared transaction-boundary fix:+reuse `reserve_write_lock` at `migrate_legacy_deferred_resource_contexts` entry,+before every decision read, holding it through the caller's commit/rollback.+No per-table CAS, retry policy, new role model or migration state machine was+introduced. `_configured_resource_state` remains read-only with+`persist_migrations=False`, preserving config-before-database lock order and+avoiding recursive bootstrap. The terminal/idempotent path also takes this short+writer reservation.++Callers audited: importer data migrations, post-stamp migrations, remote-access+pending migration and authorization bootstrap all use caller-owned transactions.+The initial released schema already supplies `agent_sessions.id` needed by the+existing-transaction no-op reservation. Real initial-schema new/writer/savepoint+fixtures and existing pre-Show/unversioned stamp tests cover that path; a successful+repair inside an existing writer/savepoint remains rollbackable by its caller.++Deterministic real two-connection tests cover each of Task, Watch, Run, Delivery,+binding and marker. A peer attempting writes after migration reads is refused+until the migration transaction completes, and its later legitimate update+survives. A peer committing first is read after reservation, so now-ineligible or+terminal rows and changed provenance remain untouched. All six after-read race+cases fail against the reviewed `e6987dc74` migration function. Existing cutoff,+identity, snapshot/hash, terminal-work and config-lock-order tests stay in the+regression set. Actual parser help is exercised in both languages and names+Member or Owner. This round passed 540 related regression tests, three existing+initial/unversioned/pre-Show schema cases, changed-file Ruff and the UI build. PM+independently inspected the shared boundary and ran 19 concurrency, legacy-schema,+rollback and parser-help cases, all passing, then authorized this round's push.+Subsequent exact-head review/CI remain required.++The third-head diagnosis corrected the overbroad "untouched row" requirement,+not runtime semantics. PM and lane independently used real SQLite producers:+`record_run_skip_reason` preserves the authorization snapshot and hold clock;+`_clear_transport_skip_evidence` removes its reason and reason-start timestamp.+After skip then clear, decoded metadata equals pristine metadata, so a+`last_skip_at` deny-list cannot establish historical immutability. Advancing that+clock would change released hold/transition behavior. The invariant above instead+protects authorization attribution while retaining legitimate current diagnostics.++PM authorized comments, contract and producer-to-consumer evidence on 2026-09-17;+no scheduler, schema, cutoff, binding, concurrency or role decision changed.+The production-writer audit found:++- Task/Watch user add/update re-snapshot authority and advance `updated_at`;+ full-row upsert callers also advance it. Internal runtime writes preserve the+ principal and advance lifecycle time where applicable.+- Run producers construct a new `TaskExecutionRequest` ID with current creation+ time, including definition fires, callbacks and atomic completion/escalation+ outboxes. A duplicate callback returns its existing child. Requeue and metadata+ merge callers advance time; they do not silently replace old remote authority.+- UI Delivery submission builds verified metadata and sets current submission+ and update clocks. Retry either inserts a new Delivery or records history on+ retained input through timestamped CAS; it does not replace its snapshot.+- Legacy Task/Watch file imports emit empty metadata; task-request import retains+ only `ok`. Watch runtime import carries process-state entries whose actual+ producer contains no remote authorization snapshot. These are insert paths,+ not edits that replace old authority while retaining old clocks.+- Diagnostic skip/clear, Agent reference pin/rename, soft deletion and Delivery+ dedupe normalization do not change `resource_user_context`. Agent catalog+ identity and existing archived-reference execution policy are preserved.++Focused tests use real skip/clear, Task/Watch user updates, Run/Delivery lifecycle+writes and stable-Agent pin/rename before repair. They assert exact retained+principal/claims plus only two binding additions, current nonauthorization+metadata/columns, Harness admission and queued-Delivery execution recheck,+post-cutoff refusals and sealed idempotence. Existing concurrency, terminal/hash+and conservative negative-provenance tests remain required. This evidence makes+no claim to recover unrecorded mutation history or support forged database files.+This round passes 10 new producer/consumer cases, 160 combined resource-permission+and signed Member scenarios (including the existing concurrency/provenance matrix),+and five retained runtime/Agent regressions. Changed-file Ruff and diff whitespace+checks pass. PM independently inspected the complete three-file diff and PR ledger, ran all+10 new producer/consumer cases successfully, and compared the production AST+(excluding comments/docstrings) with `e943feee7`: executable logic is identical.+On 2026-09-18 PM approved explanatory closure and this comments/contract/tests+push. Another exact-head review and complete CI remain required.diff --git a/docs/plans/member-management-parity.md b/docs/plans/member-management-parity.mdindex f64072bd1..442562cbd 100644--- a/docs/plans/member-management-parity.md+++ b/docs/plans/member-management-parity.md@@ -1,5 +1,15 @@# Instance Member management parity+> **Superseded Member operation scope (2026-09-17):**+> [Instance Member operations](member-instance-operations.md) is authoritative for+> Member resource use and runtime visibility on both instance kinds. Member is a+> current-instance operator; the older Organization Agent/Project/session ACL+> restrictions below are historical and no longer apply to Member. Editor/Viewer,+> true Owner identity, access-administration and ownership safeguards remain.+> Existing Show publication policy and shared inbox read-state semantics remain+> unchanged. Shipped pre-catalog Member selection/session fallbacks are retained;+> new Task/Watch binding names still require catalog entries.+Status: authoritative implementation contract, 2026-09-16.Orchestrator: Avibe Session `sescctptxwqdq`.Implementation Session: `sesb5c3sb2ayz`.diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 623cc5754..01fdd5786 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -300,7 +300,7 @@ def _attach_harness_provenance().mappings():project_id = project_access_service.project_id_from_scope_id(row["scope_id"])if (- not context.is_instance_owner+ not context.can_manage_instanceand (project_id is Noneor not project_access_service.can_read_project(conn, context, project_id)diff --git a/storage/project_access_service.py b/storage/project_access_service.pyindex ffc298f5c..f23c416dc 100644--- a/storage/project_access_service.py+++ b/storage/project_access_service.py@@ -151,7 +151,7 @@ def validate_project_access_intent(intent: Any) -> dict[str, Any]:}-def _active_project_scope(conn: Connection, project_id: str) -> str | None:+def _project_scope(conn: Connection, project_id: str, *, include_archived: bool = False) -> str | None:scope_id = project_scope_id(project_id)row = conn.execute(select(scopes.c.id, scope_settings.c.enabled)@@ -163,13 +163,13 @@ def _active_project_scope(conn: Connection, project_id: str) -> str | None:).limit(1)).first()- if row is None or row.enabled == 0:+ if row is None or (row.enabled == 0 and not include_archived):return Nonereturn str(row.id)def is_active_project(conn: Connection, project_id: str) -> bool:- return _active_project_scope(conn, project_id) is not None+ return _project_scope(conn, project_id) is not Nonedef apply_project_access_intent(@@ -194,7 +194,7 @@ def apply_project_access_intent(project_id = normalized["project_id"]revision = normalized["revision"]- scope_id = _active_project_scope(conn, project_id)+ scope_id = _project_scope(conn, project_id)if scope_id is None:return ProjectAccessIntentResult(project_id=project_id,@@ -314,6 +314,10 @@ def get_effective_project_role() -> str | None:if context.is_instance_owner:return "owner"+ if context.can_manage_projects:+ # Project archive is reversible. Managers must still see its record to+ # reopen the folder; session archive/execution guards remain separate.+ return context.instance_role if _project_scope(conn, project_id, include_archived=True) else Noneif not is_active_project(conn, project_id):return Noneinstance_role = context.instance_role@@ -343,7 +347,9 @@ def can_chat_project(conn: Connection, context: AuthorizationContext, project_iddef can_manage_project(conn: Connection, context: AuthorizationContext, project_id: str) -> bool:- return get_effective_project_role(conn, context, project_id) == "owner"+ return context.can_manage_projects and role_allows(+ get_effective_project_role(conn, context, project_id), "member"+ )def filter_accessible_projects(@@ -365,7 +371,11 @@ def get_effective_session_role() -> str | None:project_id = get_session_project_id(conn, session_id)if project_id is None:- return "owner" if context.is_instance_owner else None+ if context.is_instance_owner:+ return "owner"+ if context.can_manage_instance and session_exists(conn, session_id):+ return context.instance_role+ return Nonereturn get_effective_project_role(conn, context, project_id)diff --git a/storage/read_only_query.py b/storage/read_only_query.pyindex 664b467cc..e5e43aedc 100644--- a/storage/read_only_query.py+++ b/storage/read_only_query.py@@ -42,7 +42,7 @@ def run_read_only_query() -> QueryResult:from storage.resource_access_service import resolve_resource_access_context- allow_skill_statistics = resolve_resource_access_context(user_context).is_instance_owner+ allow_skill_statistics = resolve_resource_access_context(user_context).can_manage_instancestatement = _validate_single_statement(sql)resolved_db_path = db_path or paths.get_sqlite_state_path()if db_path is None:@@ -61,7 +61,7 @@ def run_read_only_query(conn.execute("PRAGMA query_only = ON")def authorize(action, arg1, arg2, db_name, source):# SQL has no resource-row filter. Raw Skill observations share- # agent_events, so non-owners cannot query that table wholesale.+ # agent_events, so roles below Member cannot query that table wholesale.if (not allow_skill_statistics and action == sqlite3.SQLITE_READand arg1 in {"skill_usage_daily", "agent_events"}):return sqlite3.SQLITE_DENYdiff --git a/storage/resource_access_service.py b/storage/resource_access_service.pyindex f8de1f4c2..4babdbc72 100644--- a/storage/resource_access_service.py+++ b/storage/resource_access_service.py@@ -21,6 +21,7 @@ from sqlalchemy import text as sqlalchemy_textfrom sqlalchemy.engine import Connectionfrom storage.db import get_cached_sqlite_engine+from storage.agent_session_rows import reserve_write_lockfrom storage.models import (agent_runs,message_deliveries,@@ -30,6 +31,7 @@ from storage.models import (state_meta,)from vibe.authorization import (+ INSTANCE_ROLES,AuthorizationContext,context_from_session_payload,instance_owner_context,@@ -596,7 +598,7 @@ def _legacy_deferred_context_binding("""Return a safe current binding for one pre-instance metadata snapshot."""context = current_resource_context(snapshot, is_remote=True)- if context.instance_role not in {"owner", "editor", "viewer"}:+ if context.instance_role not in INSTANCE_ROLES:return Noneraw_instance_id = snapshot.get("vibe_instance_id")@@ -719,17 +721,44 @@ def _has_unbound_deferred_snapshots(connection: Connection) -> bool:return False+def _deferred_provenance_time(value: Any) -> datetime | None:+ """Read a persisted timestamp only when it identifies an absolute instant."""++ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo is not None else None++def _migrate_deferred_metadata_value(metadata: Any,*,paired_instance_id: str,paired_kind: str,+ member_repair_cutoff: datetime | None = None,+ created_at: Any = None,+ updated_at: Any = None,) -> dict[str, Any] | None:if not isinstance(metadata, dict):return Nonesnapshot = metadata.get(RESOURCE_USER_CONTEXT_METADATA_KEY)if not isinstance(snapshot, Mapping):return None+ if member_repair_cutoff is not None:+ # Attribute an old Member authorization snapshot, not an immutable row.+ # Authorization re-snapshot and timestamped lifecycle writes advance+ # updated_at; diagnostics and stable-Agent rewrites can preserve it.+ # Current lifecycle checks still apply, including soft deletion.+ # Preserve their CURRENT metadata below. These clocks are not a complete+ # mutation history. Equal-second timestamps are ambiguous, so deny.+ if snapshot.get("vibe_instance_role") != "member" or any(+ (instant := _deferred_provenance_time(value)) is None or instant >= member_repair_cutoff+ for value in (created_at, updated_at)+ ):+ return Nonebinding = _legacy_deferred_context_binding(snapshot,paired_instance_id=paired_instance_id,@@ -757,8 +786,21 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[stpairing can retry later. A successfully observed unpaired state is sealed,while a known instance with an unknown kind remains pending until that sameinstance is authoritatively classified.++ Repairing a completed pre-Member pass requires the original pairing/cutoff+ and an authorization snapshot whose row clocks precede it. Released+ diagnostic/reference writers preserve that snapshot without advancing the+ lifecycle clock; their current values survive the binding-only repair.+ No complete historical row immutability is inferred from those clocks."""+ # This migration decides from a marker, pairing config, durable binding and+ # several deferred row families before updating any of them. Reserve the+ # SQLite writer slot before the first read so that decision and seal share+ # one serialized state. This also covers callers that already hold a+ # transaction; reserve_write_lock is explicitly nested-transaction safe.+ reserve_write_lock(connection)+def _counts(*,binding_status: str,@@ -792,6 +834,8 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[streturn _counts(binding_status=RESOURCE_BINDING_STATE_UNAVAILABLE)marker = parsed_markermarker_state = marker.get("state")+ if marker_state is not None and marker_state not in {"pending", "completed", "sealed_unattributed"}:+ return empty_unavailableif marker_state not in {"pending", "completed", "sealed_unattributed"}:marker_state = "completed" if marker.get("completed_at") else "pending"# Markers written by e64/d667 used ``completed`` with no instance ID@@ -823,7 +867,7 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[st) -> None:now = _utc_now_iso()payload: dict[str, Any] = {- "schema_version": 2,+ "schema_version": 3 if state == "completed" else 2,"state": state,"instance_id": instance_id,"updated_at": now,@@ -831,7 +875,7 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[stif instance_kind in {"personal", "organization"}:payload["instance_kind"] = instance_kindif state == "completed":- payload["completed_at"] = now+ payload["completed_at"] = marker["completed_at"] if retry_member else nowvalues = {"value_json": json.dumps(payload, sort_keys=True, separators=(",", ":")),"updated_at": now,@@ -850,7 +894,23 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[st.values(**values))- if marker is not None and marker.get("state") in {"completed", "sealed_unattributed"}:+ # Released migrations omitted Member. Revisit only those snapshots when a+ # completed marker proves the SAME pairing identity and kind. Never reopen+ # an unattributed seal, infer missing provenance, or retry other roles.+ completed_at = _deferred_provenance_time(marker.get("completed_at")) if marker else None+ retry_member = bool(+ marker is not None+ and marker.get("state") == "completed"+ and type(marker.get("schema_version")) is int+ and marker.get("schema_version") in {1, 2}+ and completed_at is not None+ and configured.status == RESOURCE_BINDING_STATE_READY+ and current_instance_id is not None+ and marker.get("instance_id") == current_instance_id+ and current_kind in {"personal", "organization"}+ and marker.get("instance_kind") == current_kind+ )+ if marker is not None and marker.get("state") in {"completed", "sealed_unattributed"} and not retry_member:return _counts(binding_status=RESOURCE_BINDING_STATE_SEALED)raw_marker_instance_id = marker.get("instance_id") if marker else None@@ -912,19 +972,23 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[strow_id = binding_row.get("instance_id")row_kind = binding_row.get("instance_kind")row_state = binding_row.get("state")+ if retry_member and row_state != RESOURCE_BINDING_STATE_READY:+ return _counts(binding_status=RESOURCE_BINDING_STATE_PARTIAL)identity_matches = row_id == current_instance_id and (row_kind == current_kindor (row_state == _BINDING_RECONCILING and row_kind in {None, current_kind}))if not identity_matches:- write_marker(state="pending", instance_id=current_instance_id)+ if not retry_member:+ write_marker(state="pending", instance_id=current_instance_id)return _counts(binding_status=RESOURCE_BINDING_STATE_PARTIAL)else:# Known-kind config with no durable binding row is an upgrade# artifact, not a validated pairing. Leave the opportunity pending# so a later heartbeat/bootstrap can attribute snapshots after the# server-owned kind is confirmed.- write_marker(state="pending", instance_id=current_instance_id)+ if not retry_member:+ write_marker(state="pending", instance_id=current_instance_id)return _counts(binding_status=RESOURCE_BINDING_STATE_PARTIAL)paired_instance_id = current_instance_idpaired_kind = current_kind@@ -937,7 +1001,8 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[st}definition_rows = (connection.execute(- select(run_definitions.c.id, run_definitions.c.metadata_json).where(+ select(run_definitions.c.id, run_definitions.c.metadata_json,+ run_definitions.c.created_at, run_definitions.c.updated_at).where(run_definitions.c.definition_type.in_(("scheduled", "watch")))).mappings()@@ -953,6 +1018,9 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[stmetadata,paired_instance_id=paired_instance_id,paired_kind=paired_kind,+ member_repair_cutoff=completed_at if retry_member else None,+ created_at=row["created_at"],+ updated_at=row["updated_at"],)if migrated is None:continue@@ -972,7 +1040,8 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[strun_rows = (connection.execute(- select(agent_runs.c.id, agent_runs.c.metadata_json)+ select(agent_runs.c.id, agent_runs.c.metadata_json,+ agent_runs.c.created_at, agent_runs.c.updated_at).where(agent_runs.c.status.in_(("pending", "queued", "processing", "running")))).mappings()if _connection_has_table(connection, "agent_runs")@@ -987,6 +1056,9 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[stmetadata,paired_instance_id=paired_instance_id,paired_kind=paired_kind,+ member_repair_cutoff=completed_at if retry_member else None,+ created_at=row["created_at"],+ updated_at=row["updated_at"],)if migrated is None:continue@@ -1017,6 +1089,8 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[stselect(message_deliveries.c.id,message_deliveries.c.snapshot_json,+ message_deliveries.c.submitted_at.label("created_at"),+ message_deliveries.c.updated_at,).where(message_deliveries.c.snapshot_json.is_not(None),message_deliveries.c.state.in_(executable_delivery_states),@@ -1035,6 +1109,9 @@ def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[stmetadata,paired_instance_id=paired_instance_id,paired_kind=paired_kind,+ member_repair_cutoff=completed_at if retry_member else None,+ created_at=row["created_at"],+ updated_at=row["updated_at"],)if migrated_metadata is None:continue@@ -1323,7 +1400,9 @@ def _policy_allows(policy: Mapping[str, Any] | None,group_ids: Sequence[str],) -> bool:- if context.is_instance_owner:+ # Current-instance operators use every supported resource without rewriting+ # its stored ownership or ACL. Protected Vault proofs are enforced by use.+ if context.can_manage_instance:return Trueif resource_kind == "agent" and context.is_personal_instance:return context.can_use_resource(resource_kind)diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 17249f929..2b48a3aaf 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -148,8 +148,8 @@ def _dumps_metadata(metadata: dict[str, Any]) -> str:return json.dumps(metadata)-def _has_runtime_owner_access(context: AuthorizationContext) -> bool:- return context.is_instance_owner+def _has_runtime_management_access(context: AuthorizationContext) -> bool:+ return context.can_manage_instancedef _include_local_details(context: AuthorizationContext) -> bool:@@ -185,7 +185,7 @@ def list_sessions(context = require_instance_role(authorization_context, "viewer")query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")- if not _has_runtime_owner_access(context):+ 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)@@ -279,7 +279,7 @@ def get_session().mappings().first()if row is None:raise LookupError(f"Session not found: {session_id}")- if not _has_runtime_owner_access(context):+ if not _has_runtime_management_access(context):project_id = project_access_service.project_id_from_scope_id(row["scope_id"])if project_id is None or not project_access_service.can_read_project(conn, context, project_id@@ -373,7 +373,7 @@ def create_session("""authorization = require_instance_role(authorization_context, "editor")- if not _has_runtime_owner_access(authorization):+ if not _has_runtime_management_access(authorization):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, authorization, project_id@@ -663,7 +663,7 @@ def update_session(# reads). Same split as ``sessions_service.bind_agent_session_by_id``.if existing.status == "archived":raise SessionArchivedError(session_id)- if not _has_runtime_owner_access(authorization):+ if not _has_runtime_management_access(authorization):project_id = project_access_service.project_id_from_scope_id(existing.scope_id)if project_id is None or not project_access_service.can_chat_project(conn, authorization, project_id@@ -1428,7 +1428,7 @@ def archive_session().scalar_one_or_none()if existing is None:raise LookupError(f"Session not found: {session_id}")- if not _has_runtime_owner_access(context):+ if not _has_runtime_management_access(context):if not project_access_service.role_allows(project_access_service.get_effective_session_role(conn, context, session_id),"editor",diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex f1a123197..e766d95e0 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -221,6 +221,7 @@ capabilities:observations: tests/scenarios/permissions/observations.yamlscenario_tests:- tests/scenarios/permissions/test_permissions_scenarios.py+ - tests/scenarios/permissions/test_member_instance_operations.pyharness:- tests/scenario_harness/permissions.pyunit_or_contract_tests:diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yamlindex 850a8e91e..ed4c2b00a 100644--- a/tests/scenarios/permissions/catalog.yaml+++ b/tests/scenarios/permissions/catalog.yaml@@ -6,6 +6,7 @@ capability:- tests/scenarios/permissions/test_permissions_scenarios.py- tests/test_permissions.py- tests/test_member_management_parity.py+ - tests/scenarios/permissions/test_member_instance_operations.pystatus_legend:covered: scenario coverage existspartial: unit or contract coverage exists but the closed loop is incomplete@@ -130,3 +131,63 @@ scenarios:given: A signed Organization instance Member and existing bound users and channelswhen: The Member saves channel operation and DM preferences and attempts access mutationsthen: Ordinary writes persist while user creation, role changes and reactivation are refused without mutation++ - id: PERMISSIONS-014+ name: Member operates current-instance Agents Projects and sessions+ status: covered+ kind: authorization+ layer: scenario+ test: tests/scenarios/permissions/test_member_instance_operations.py::test_permissions_014_member_signed_agent_session_lifecycle+ given: A signed Member has a policy-less built-in Agent and restricted or standalone sessions+ when: The Member discovers selects mutates chats forks and opens Show+ then: Operations succeed with original ACL and ownership rows unchanged++ - id: PERMISSIONS-015+ name: Member cannot administer access or bypass execution preconditions+ status: covered+ kind: authorization+ layer: scenario+ test: tests/scenarios/permissions/test_member_instance_operations.py::test_permissions_015_access_administration_and_missing_resources+ given: Member operation scope is instance-wide+ when: The Member attempts access grants pairing onboarding or a disabled Agent+ then: Protected effects are denied and real resource checks remain++ - id: PERMISSIONS-016+ name: Management events reach Member through the real SSE stream+ status: covered+ kind: authorization+ layer: scenario+ 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++ - id: PERMISSIONS-017+ name: Broader notification visibility preserves subject identity+ status: covered+ kind: authorization+ layer: scenario+ test: tests/scenarios/permissions/test_member_instance_operations.py::test_permissions_017_notifications_keep_recipient_identity+ given: Two signed users hold separate push subscriptions+ when: Member reads badges and delayed recipients are authorized+ then: Member sees instance records without rewriting or combining subscription keys++ - id: PERMISSIONS-018+ name: RemoteAccess pairing controls reflect true Owner identity+ status: covered+ kind: authorization+ layer: scenario+ test: ui/src/components/RemoteAccess.test.tsx::PERMISSIONS-018 keeps Member transport usable while pairing is disabled+ given: The existing component renders with actual Member or Owner capability providers+ when: Paired and unpaired users interact with pairing and transport controls+ then: Member cannot submit pairing but can operate transport while Owner pairing remains usable++ - id: PERMISSIONS-019+ name: Instance operational diagnostics admit Member and preserve query safety+ status: covered+ kind: authorization+ layer: scenario+ test: tests/test_skill_observability.py::test_manager_sql_access_including_cte+ 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 remaindiff --git a/tests/scenarios/permissions/observations.yaml b/tests/scenarios/permissions/observations.yamlindex 3b050d37e..39d1122da 100644--- a/tests/scenarios/permissions/observations.yaml+++ b/tests/scenarios/permissions/observations.yaml@@ -41,3 +41,24 @@ observations:- bind every Resource ACL request to the paired instance and strip the browser match field before Backend contact- keep Show Page link visibility and Limited-email grants as a separate local policy dimension with no show_page Resource ACL- reject the retired show_page resource kind as invalid_request without any Backend contact++ - id: OBS-PERMISSIONS-004+ source: approved_owner_contract+ related_scenarios:+ - PERMISSIONS-014+ - PERMISSIONS-015+ - PERMISSIONS-016+ - PERMISSIONS-017+ - PERMISSIONS-018+ - PERMISSIONS-019+ summary: Member manages and operates the current instance without becoming Owner or rewriting stored ACLs.+ previous_assumption: Organization Member management could coexist with hidden Agents Projects and standalone sessions.+ observed_behavior: Management and use conflicted at resource and runtime consumers; management SSE was also dropped after its role gate.+ required_updates:+ - use existing management capabilities for operation scope and keep access administration separate+ - 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++ - 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 reservationdiff --git a/tests/scenarios/permissions/test_member_instance_operations.py b/tests/scenarios/permissions/test_member_instance_operations.pynew file mode 100644index 000000000..13bd27f90--- /dev/null+++ b/tests/scenarios/permissions/test_member_instance_operations.py@@ -0,0 +1,498 @@+"""PERMISSIONS-014..017: signed Member operations with test-owned state.++Only execution IPC is stubbed, after route and resource authorization. Services,+identity cookies, CSRF, persistence, ACLs and SSE delivery are real.+"""++from __future__ import annotations++import asyncio+import json+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from sqlalchemy import select++from core.inbox_events import run_updated_payload, vaults_updated_payload+from core.show_pages import ShowPageStore+from core.vibe_agents import VibeAgentAccessError, VibeAgentStore, ensure_agent_name_access+from core.web_push_notifications import _badge_count_for_user_key, _filter_project_authorized_user_keys+from storage import messages_service, 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, messages, resource_access_policies, resource_access_groups+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.sse_broker import broker+from vibe.ui_compat import g++ORIGIN = "https://alex.avibe.bot"++[email protected](params=["personal", "organization"])+def operations(request, tmp_path, monkeypatch):+ config = _save_config(tmp_path, paired=True, instance_kind=request.param)+ ensure_sqlite_state()+ monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda *args: None)+ store = VibeAgentStore()+ store.ensure_builtin_default_agent(backend="codex")+ agent = store.require("codex")+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ # A built-in without an ACL is the reported Organization failure.+ conn.execute(resource_access_policies.delete().where(resource_access_policies.c.resource_id == agent.id))+ project = projects_service.create_project(conn, str(tmp_path), display_name="项目 α")+ project_access_service.apply_project_access_intent(+ conn,+ {+ "project_id": project["id"],+ "revision": 1,+ "mode": "restricted",+ "organization_id": "foreign-org",+ "bindings": [+ {+ "principal_kind": "organization_group",+ "principal_value": "other-group",+ "access_role": "viewer",+ }+ ],+ },+ )+ from storage.settings_service import upsert_scope++ im_scope = upsert_scope(+ conn, platform="slack", scope_type="channel", native_id="C_TEST", now="2026-09-17T00:00:00Z"+ )+ sessions = [+ create_session(conn, scope_id=scope, agent_backend=agent.backend, agent_name=agent.name, title="旧会话 α")+ for scope in (project["scope_id"], None, im_scope)+ ]+ for session in sessions:+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == session["id"])+ .values(native_session_id="native-test")+ )+ messages_service.append(+ conn,+ session_id=session["id"],+ scope_id=session["scope_id"],+ platform="avibe",+ author="agent",+ message_type="result",+ text="实例内容 α",+ )++ def context(role="member", subject="operator"):+ return 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,+ )++ def client(role="member", subject="operator"):+ value = ui_server.app.test_client()+ value.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(+ config,+ f"{subject}@example.com",+ subject,+ role=role,+ access_source="owner" if role == "owner" else "email",+ organization_id="org-1",+ organization_member_id="org-member",+ organization_role="member",+ group_ids=[],+ ),+ domain="alex.avibe.bot",+ )+ headers = csrf_headers(value, ORIGIN)++ def call(method, path, payload=None, csrf=True):+ return value.request(+ method, path, json=payload, headers=headers if csrf else {}, base_url=ORIGIN, environ_base=remote_peer()+ )++ return call++ yield SimpleNamespace(+ config=config,+ engine=engine,+ store=store,+ agent=agent,+ project=project,+ sessions=sessions,+ client=client,+ context=context,+ kind=request.param,+ )+ store.close()+ engine.dispose()+++def _policies(state):+ with state.engine.connect() as conn:+ return (+ project_access_service.get_project_policy(conn, state.project["id"]),+ [dict(row) for row in conn.execute(select(resource_access_policies)).mappings()],+ [dict(row) for row in conn.execute(select(resource_access_groups)).mappings()],+ )+++def test_permissions_014_member_signed_agent_session_lifecycle(operations, monkeypatch):+ """PERMISSIONS-014: discovery, selection, chat, fork and Show agree."""+ state = operations+ call = state.client()+ before = _policies(state)+ from tests.test_ui_session_stream import _settle_reserved_delivery++ async def accept(payload):+ from core.session_turns import SessionTurnManager+ from storage import message_deliveries++ # Consume the exact persisted remote Delivery at the final execution+ # authorization seam, before stubbing the external provider acceptance.+ with state.engine.connect() as conn:+ delivery = message_deliveries.get_delivery(conn, payload["user_message_id"])+ assert message_deliveries.delivery_has_remote_resource_context(delivery)+ assert SessionTurnManager._remote_delivery_execution_denial(conn, delivery) is None+ _settle_reserved_delivery(payload, state="accepted")+ return {"status_code": 202, "body": {"ok": True, "delivery_state": "accepted"}}++ dispatch = AsyncMock(side_effect=accept)+ monkeypatch.setattr(internal_client, "dispatch_async", dispatch)+ listing = call("GET", "/api/agents").get_json()+ assert state.agent.name in {agent["name"] for agent in listing["agents"]}+ assert call("GET", f"/api/agents/{state.agent.name}").status_code == 200+ assert call("POST", "/api/agents/default", {"name": state.agent.name}).status_code == 200+ assert call("PATCH", f"/api/agents/{state.agent.name}", {"description": "成员管理 α"}).status_code == 200+ assert state.store.require(state.agent.name).description == "成员管理 α"+ assert (+ call(+ "POST", "/api/sessions", {"project_id": state.project["id"], "agent_name": state.agent.name}, csrf=False+ ).status_code+ == 403+ )+ created = call("POST", "/api/sessions", {"project_id": state.project["id"], "agent_name": state.agent.name})+ assert created.status_code == 201, created.get_json()+ current = created.get_json()+ visible = {row["id"] for row in call("GET", "/api/sessions").get_json()["sessions"]}+ assert {current["id"], *(session["id"] for session in state.sessions)} <= visible+ show = ShowPageStore()+ try:+ for session in [*state.sessions, current]:+ session_id = session["id"]+ assert call("GET", f"/api/sessions/{session_id}").status_code == 200+ changed = call("PATCH", f"/api/sessions/{session_id}", {"title": "改名 α"})+ assert changed.status_code == 200, changed.get_json()+ sent = call(+ "POST", f"/api/sessions/{session_id}/messages", {"text": "你好 α", "author_id": "remote:spoofed"}+ )+ assert sent.status_code == 201, sent.get_json()+ assert sent.get_json()["author_id"] == "remote:operator"+ assert dispatch.await_args.args[0]["session_id"] == session_id+ with state.engine.connect() as conn:+ row = conn.execute(select(messages).where(messages.c.id == sent.get_json()["id"])).mappings().one()+ metadata = json.loads(row["metadata_json"])+ assert row["author_id"] == "remote:operator"+ assert metadata["_web_push_user_key"] == "remote:operator"+ assert project_access_service.get_effective_session_role(conn, state.context(), session_id) == "member"+ page = show.ensure(session_id, user_context=state.context())+ assert show.get_for_use(session_id, user_context=state.context()).session_id == page.session_id+ finally:+ show.close()+ monkeypatch.setattr(internal_client, "turn_state", AsyncMock(return_value={"body": {"in_flight": False}}))+ forked = call("POST", f"/api/sessions/{state.sessions[1]['id']}/fork", {})+ assert forked.status_code == 201, forked.get_json()+ assert call("GET", f"/api/sessions/{forked.get_json()['id']}").status_code == 200+ ensure_agent_name_access(state.agent.name, user_context=state.context())+ with pytest.raises(ValueError):+ ensure_agent_name_access("missing-agent", user_context=state.context())+ assert not state.context().is_instance_owner+ assert _policies(state) == before++[email protected]("shape", ["absent", "private", "foreign", "unmatched", "legacy"])+def test_permissions_014_resource_policy_shapes_preserve_rows(operations, shape):+ state = operations+ if shape != "absent":+ with state.engine.begin() as conn:+ resource_access_service.ensure_resource_policy(+ conn,+ resource_kind="agent",+ resource_id=state.agent.id,+ owner_user_id="someone-else",+ organization_id="foreign-org" if shape == "foreign" else "org-1",+ access_level="scope" if shape == "unmatched" else "private",+ group_ids=["other"] if shape == "unmatched" else [],+ )+ if shape == "legacy":+ conn.execute(+ resource_access_policies.update()+ .where(resource_access_policies.c.resource_id == state.agent.id)+ .values(organization_id=None, owner_user_id=None)+ )+ before = _policies(state)+ assert state.store.require_accessible(state.agent.name, user_context=state.context()).id == state.agent.id+ for role in ("editor", "viewer"):+ context = state.context(role)+ if role == "editor" and state.kind == "personal":+ assert state.store.require_accessible(state.agent.name, user_context=context)+ else:+ with pytest.raises(VibeAgentAccessError):+ state.store.require_accessible(state.agent.name, user_context=context)+ assert _policies(state) == before+++def test_permissions_015_access_administration_and_missing_resources(operations, monkeypatch):+ """PERMISSIONS-015: manager is neither owner nor a new access grant."""+ state = operations+ call = state.client()+ before = _policies(state)+ for method, path, body in [+ ("PUT", "/api/permissions/authorized-users", {"entries": []}),+ ("PUT", f"/api/permissions/projects/{state.project['id']}/access", {"mode": "inherit"}),+ ("PUT", f"/api/permissions/resources/agent/{state.agent.id}/access", {"access_level": "public"}),+ ("POST", "/api/remote-access/vibe-cloud/pair", {"pairing_key": "synthetic"}),+ ("POST", "/api/agent-onboarding", {}),+ ("POST", "/api/bind-codes", {}),+ ]:+ denied = call(method, path, body)+ assert denied.status_code == 403, (path, denied.get_json())+ assert call("GET", "/api/sessions/missing-session").status_code == 404+ with state.engine.connect() as conn:+ assert project_access_service.get_effective_project_role(conn, state.context(), "missing") is None+ assert project_access_service.get_effective_session_role(conn, state.context(), "missing") is None+ state.store.update(state.agent.name, enabled=False)+ denied = call("POST", "/api/sessions", {"project_id": state.project["id"], "agent_name": state.agent.name})+ assert denied.status_code == 404, denied.get_json()+ assert _policies(state) == before++[email protected]("role", ["member", "owner", "editor", "viewer"])+def test_permissions_016_real_sse_management_and_session_delivery(operations, role):+ """PERMISSIONS-016: publisher payloads traverse both stream gates."""+ state = operations+ events = [+ ("vaults.updated", vaults_updated_payload(scope="requests", request_id="request-α")),+ ("definitions.updated", {"definition_type": "scheduled"}),+ ("runs.updated", run_updated_payload(run_id="run-α", status="running")),+ ("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"}),+ ]++ async def collect():+ with ui_server.app.test_request_context("/api/events"):+ g.authorization_context = state.context(role)+ response = await ui_server.workbench_events()+ iterator = response.body_iterator.__aiter__()+ try:+ for _ in range(3):+ await iterator.__anext__()+ for event_type, data in events:+ broker.publish(event_type, data)+ broker.publish("future.management.event", {"secret": "not-a-known-event"})+ broker.publish("projects.changed", {})+ frames = []+ while True:+ frame = await asyncio.wait_for(iterator.__anext__(), timeout=2)+ if isinstance(frame, bytes):+ frame = frame.decode()+ if "event: projects.changed\n" in frame:+ return frames+ frames.append(frame)+ finally:+ await iterator.aclose()++ frames = asyncio.run(collect())+ delivered = [+ json.loads(next(line[6:] for line in frame.splitlines() if line.startswith("data: "))) for frame in frames+ ]+ 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]]+ else:+ assert delivered == []+++def test_permissions_017_notifications_keep_recipient_identity(operations):+ """PERMISSIONS-017: visibility widens without changing subscription identity."""+ state = operations+ contexts = {"remote:operator": state.context(), "remote:other": state.context("viewer", "other")}+ for subject in ("operator", "other"):+ subscribed = state.client(subject=subject)(+ "POST",+ "/api/web-push/subscriptions",+ {+ "subscription": {+ "endpoint": f"https://push.example/{subject}",+ "keys": {"p256dh": "test-key", "auth": "test-auth"},+ },+ "device_id": "same-device-id",+ },+ )+ assert subscribed.status_code == 200+ assert subscribed.get_json()["subscription"]["user_key"] == f"remote:{subject}"+ from storage.models import web_push_subscriptions++ with state.engine.connect() as conn:+ assert set(conn.execute(select(web_push_subscriptions.c.user_key)).scalars()) == {+ "remote:operator",+ "remote:other",+ }+ assert _filter_project_authorized_user_keys(+ conn, user_keys=list(contexts), contexts=contexts, session_id=state.sessions[0]["id"]+ ) == ["remote:operator"]+ assert _badge_count_for_user_key(conn, user_key="remote:operator", contexts=contexts) == len(state.sessions)+ assert _badge_count_for_user_key(conn, user_key="remote:other", contexts=contexts) == 0+ assert _badge_count_for_user_key(conn, user_key="remote:unknown", contexts=contexts) == 0+++def test_permissions_014_runtime_discovery_and_harness_bindings(operations, tmp_path, monkeypatch):+ state = operations+ call = state.client()+ live = [+ {+ "session_id": row["id"],+ "agent_id": state.agent.id,+ "agent_name": state.agent.name,+ "backend": state.agent.backend,+ "state": "active",+ }+ for row in state.sessions+ ]+ monkeypatch.setattr(+ internal_client,+ "list_running_agents",+ AsyncMock(return_value={"status_code": 200, "body": {"agents": live, "counts": {"total": len(live)}}}),+ )+ assert call("GET", "/api/running-agents").get_json()["agents"] == live+ graph = call("GET", "/api/agents-graph").get_json()+ assert {row["id"] for row in state.sessions} <= {node["session_id"] for node in graph["nodes"]}+ inbox = call("GET", "/api/inbox").get_json()+ assert {row["id"] for row in state.sessions} <= {item["session_id"] for item in inbox["sessions"]}+ search = call("GET", "/api/search/messages?q=实例内容").get_json()+ assert {row["id"] for row in state.sessions} <= {item["session_id"] for item in search["sessions"]}+ from core.scheduled_tasks import ScheduledTaskStore+ from core.watches import ManagedWatchStore++ tasks = ScheduledTaskStore(tmp_path / "tasks.json")+ watches = ManagedWatchStore(tmp_path / "watches.json")+ task = tasks.add_task(+ session_key=state.project["scope_id"],+ prompt="test",+ schedule_type="cron",+ agent_name=state.agent.name,+ cron="0 * * * *",+ timezone_name="UTC",+ user_context=state.context(),+ )+ watch = watches.add_watch(+ name="test",+ session_key=state.project["scope_id"],+ 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=state.agent.name,+ user_context=state.context(),+ )+ assert task.agent_name == watch.agent_name == state.agent.name+ assert tasks.get_task(task.id).agent_name == state.agent.name+ assert watches.get_watch(watch.id).agent_name == state.agent.name+++def test_permissions_015_archived_sessions_remain_inert(operations, monkeypatch):+ state = operations+ call = state.client()+ session_id = state.sessions[1]["id"]+ before = _policies(state)+ with state.engine.begin() as conn:+ conn.execute(agent_sessions.update().where(agent_sessions.c.id == session_id).values(status="archived"))+ dispatch = AsyncMock()+ monkeypatch.setattr(internal_client, "dispatch_async", dispatch)+ monkeypatch.setattr(internal_client, "turn_state", AsyncMock(return_value={"body": {"in_flight": False}}))+ assert call("GET", f"/api/sessions/{session_id}").status_code == 200+ assert session_id not in {row["id"] for row in call("GET", "/api/sessions?status=active").get_json()["sessions"]}+ for method, path, payload in [+ ("PATCH", f"/api/sessions/{session_id}", {"title": "must not change"}),+ ("POST", f"/api/sessions/{session_id}/messages", {"text": "must not run"}),+ ("POST", f"/api/sessions/{session_id}/fork", {}),+ ]:+ denied = call(method, path, payload)+ assert denied.status_code == 409, denied.get_json()+ dispatch.assert_not_awaited()+ with state.engine.connect() as conn:+ assert (+ conn.execute(select(agent_sessions.c.title).where(agent_sessions.c.id == session_id)).scalar_one()+ == "旧会话 α"+ )+ assert _policies(state) == before+++def test_permissions_014_member_restores_archived_project_and_deferred_authority(operations, monkeypatch):+ from core.session_turns import SessionTurnManager+ from storage import message_deliveries++ state = operations+ call = state.client()+ project_id = state.project["id"]+ session_id = state.sessions[0]["id"]+ before = _policies(state)+ dispatch = AsyncMock(return_value={"status_code": 202, "body": {"ok": True}})+ monkeypatch.setattr(internal_client, "dispatch_async", dispatch)+ monkeypatch.setattr(internal_client, "turn_state", AsyncMock(return_value={"body": {"in_flight": False}}))+ sent = call("POST", f"/api/sessions/{session_id}/messages", {"text": "queued before project archive"})+ assert sent.status_code == 202+ delivery_id = dispatch.await_args.args[0]["user_message_id"]+ assert call("DELETE", f"/api/projects/{project_id}").status_code == 200+ assert project_id not in {row["id"] for row in call("GET", "/api/projects").get_json()["projects"]}+ assert project_id in {row["id"] for row in call("GET", "/api/projects?include_archived=1").get_json()["projects"]}+ assert call("GET", f"/api/projects/{project_id}").status_code == 200+ for role in ("viewer", "editor"):+ assert state.client(role, subject=role)("GET", f"/api/projects/{project_id}").status_code == 404+ with state.engine.connect() as conn:+ assert project_access_service.get_effective_project_role(conn, state.context(), project_id) == "member"+ assert project_access_service.can_manage_project(conn, state.context(), project_id)+ assert project_access_service.get_effective_project_role(conn, state.context(), "missing") is None+ delivery = message_deliveries.get_delivery(conn, delivery_id)+ assert SessionTurnManager._remote_delivery_execution_denial(conn, delivery) is None+ show = ShowPageStore()+ try:+ assert show.ensure(session_id, user_context=state.context()).session_id == session_id+ assert show.get_for_use(session_id, user_context=state.context()).session_id == session_id+ finally:+ show.close()+ forked = call("POST", f"/api/sessions/{session_id}/fork", {})+ assert forked.status_code == 201, forked.get_json()+ reopened = call("POST", "/api/projects", {"folder_path": state.project["folder_path"]})+ assert reopened.status_code == 201, reopened.get_json()+ assert reopened.get_json()["id"] == project_id+ assert project_id in {row["id"] for row in call("GET", "/api/projects").get_json()["projects"]}+ assert _policies(state) == before+ # Operational Member scope does not bypass the deferred pairing fence.+ state.config.remote_access.vibe_cloud.instance_id = "another-instance"+ state.config.save()+ with state.engine.connect() as conn:+ assert SessionTurnManager._remote_delivery_execution_denial(conn, delivery) == "remote_chat_access_forbidden"diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 22e141a2f..5b983527f 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -430,6 +430,15 @@ def test_agent_run_provenance_hides_inaccessible_source_session(isolated_state):assert "source_session_title" not in remote_messageassert "source_session_agent_name" not in remote_message+ with engine.connect() as conn:+ member_result = messages_service.list_session_messages(+ conn, session_id="ses_target",+ authorization_context=AuthorizationContext(instance_role="member", is_remote=True),+ )+ member_message = next(row for row in member_result["messages"] if row["id"] == "msg_hidden")+ assert member_message["source_session_id"] == "ses_hidden_source"+ assert member_message["source_session_title"] == "Hidden Source"+local_message = next(row for row in local_result["messages"] if row["id"] == "msg_hidden")assert local_message["source_session_id"] == "ses_hidden_source"assert local_message["source_session_title"] == "Hidden Source"diff --git a/tests/test_project_access_service.py b/tests/test_project_access_service.pyindex b6c72fe87..01e265617 100644--- a/tests/test_project_access_service.py+++ b/tests/test_project_access_service.py@@ -199,7 +199,7 @@ def test_highest_match_is_capped_by_instance_role(tmp_path) -> None:) == "editor"assert project_access_service.get_effective_project_role(conn, _context("member"), project["id"]- ) == "editor"+ ) == "member"def test_project_binding_rejects_member_access_role(tmp_path) -> None:@@ -347,7 +347,7 @@ def test_archived_or_missing_project_intent_is_rejected(tmp_path) -> None:assert result.error_code == "project_not_found"-def test_archived_project_denies_non_owner_effective_roles(tmp_path) -> None:+def test_archived_project_denies_lower_role_effective_roles(tmp_path) -> None:engine, project = _engine_with_project(tmp_path)editor = _context("editor")with engine.begin() as conn:diff --git a/tests/test_projects_service.py b/tests/test_projects_service.pyindex 9c2cfac63..5b29f5c5e 100644--- a/tests/test_projects_service.py+++ b/tests/test_projects_service.py@@ -113,7 +113,7 @@ def test_project_positions_survive_activity_metadata_and_restoration(engine, tmpassert [p["id"] for p in projects_service.list_projects(conn, navigation_order=True)] == [*saved, new["id"]]-def test_project_reorder_preserves_hidden_and_archived_slots(engine, tmp_path):+def test_member_project_reorder_includes_restricted_and_preserves_archived_slots(engine, tmp_path):with engine.begin() as conn:rows = _ordered_projects(conn, tmp_path)ids = [row["id"] for row in rows]@@ -121,11 +121,11 @@ def test_project_reorder_preserves_hidden_and_archived_slots(engine, tmp_path):projects_service.archive_project(conn, ids[2])context = _acl_context("member", email="[email protected]")result = projects_service.reorder_projects(- conn, [ids[3], ids[0]], expected_order=[ids[0], ids[3]], authorization_context=context+ conn, [ids[3], ids[0], ids[1]], expected_order=[ids[0], ids[1], ids[3]], authorization_context=context)- assert [p["id"] for p in result] == [ids[3], ids[0]]+ assert [p["id"] for p in result] == [ids[3], ids[0], ids[1]]assert [p["id"] for p in projects_service.list_projects(conn, include_archived=True, navigation_order=True)] == [- ids[3], ids[1], ids[2], ids[0]+ ids[3], ids[0], ids[2], ids[1]]@@ -259,9 +259,8 @@ def test_remote_project_order_invalidation_reaches_the_real_event_stream(role):if isinstance(frame, bytes):frame = frame.decode("utf-8")assert "event: projects.changed\n" in frame- assert "hidden-project" not in framedata = next(line.removeprefix("data: ") for line in frame.splitlines() if line.startswith("data: "))- assert json.loads(data)["data"] == {}+ assert json.loads(data)["data"] == ({"project_ids": ["hidden-project"]} if role == "member" else {})def _remote_context(role: str) -> AuthorizationContext:@@ -373,93 +372,37 @@ def _restrict_project_to(conn, project_id: str, email: str, *, access_role: strassert result.outcome == "applied"-def test_project_mutations_follow_the_acl_that_hides_them(engine, tmp_path):- """Whether a member administers Projects and *which* are separate questions.-- ``can_manage_projects`` answers the first; the Project ACL answers the second.- Checking only the first is what let a member who knew a Project id PATCH or- archive a restricted Project that ``list_projects`` and ``get_project``- correctly hide from them -- the read half was ACL-checked and the write half- was not, which is the wrong way round for an asymmetry to fall.-- The floor is the ACL's *visibility* floor rather than a second predicate: a- member holding an explicit editor binding has an effective Project role of- editor, so demanding a "member" Project role would refuse exactly the- Projects the list shows them.- """-[email protected]("role", ["member", "owner", "editor", "viewer"])+def test_project_mutations_follow_instance_operations_and_lower_role_acl(engine, tmp_path, role):+ """Instance managers operate restricted Projects; lower roles retain ACLs."""folder = tmp_path / "restricted"folder.mkdir()+ excluded = _acl_context(role, email="[email protected]")+ included = _acl_context(role, email="[email protected]")with engine.begin() as conn:- project = projects_service.create_project(- conn,- str(folder),- display_name="Restricted",- authorization_context=_remote_context("owner"),- )+ project = projects_service.create_project(conn, str(folder), display_name="Restricted")_restrict_project_to(conn, project["id"], "[email protected]")-- excluded = _acl_context("member", email="[email protected]")- included = _acl_context("member", email="[email protected]")-- with engine.connect() as conn:- visible_to_excluded = {- listed["id"] for listed in projects_service.list_projects(conn, authorization_context=excluded)- }- visible_to_included = {- listed["id"] for listed in projects_service.list_projects(conn, authorization_context=included)+ policy = project_access_service.get_project_policy(conn, project["id"])+ listed = {p["id"] for p in projects_service.list_projects(conn, authorization_context=excluded)}+ assert (project["id"] in listed) == (role in {"member", "owner"})+ assert project["id"] in {+ p["id"] for p in projects_service.list_projects(conn, authorization_context=included)}- assert project["id"] not in visible_to_excluded- assert project["id"] in visible_to_included-- # Hidden by the list, hidden by every mutation: LookupError, the same signal- # ``get_project`` already raises, so a 404 does not enumerate the Projects a- # caller is excluded from.- with engine.begin() as conn:- with pytest.raises(LookupError):- projects_service.get_project(conn, project["id"], authorization_context=excluded)- with pytest.raises(LookupError):- projects_service.update_project(- conn,- project["id"],- display_name="Stolen",- authorization_context=excluded,- )- with pytest.raises(LookupError):- projects_service.archive_project(- conn,- project["id"],- authorization_context=excluded,- )-- with engine.connect() as conn:- assert projects_service.get_project(conn, project["id"])["display_name"] == "Restricted"-- # A bound member and the Instance Owner are both unaffected.- with engine.begin() as conn:- assert (- projects_service.update_project(- conn,- project["id"],- display_name="Insider Renamed",- authorization_context=included,- )["display_name"]- == "Insider Renamed"- )- assert (- projects_service.update_project(- conn,- project["id"],- display_name="Owner Renamed",- authorization_context=_remote_context("owner"),- )["display_name"]- == "Owner Renamed"- )- projects_service.archive_project(- conn,- project["id"],- authorization_context=included,- )+ if role in {"member", "owner"}:+ assert projects_service.get_project(conn, project["id"], authorization_context=excluded)+ assert projects_service.update_project(+ conn, project["id"], display_name="Renamed", authorization_context=excluded,+ )["display_name"] == "Renamed"+ projects_service.archive_project(conn, project["id"], authorization_context=excluded)+ else:+ with pytest.raises(LookupError):+ projects_service.get_project(conn, project["id"], authorization_context=excluded)+ for context in (excluded, included):+ with pytest.raises(InstanceAuthorizationError):+ projects_service.update_project(conn, project["id"], display_name="Denied", authorization_context=context)+ with pytest.raises(InstanceAuthorizationError):+ projects_service.archive_project(conn, project["id"], authorization_context=context)+ assert project_access_service.get_project_policy(conn, project["id"]) == policydef test_every_project_entry_point_resolves_through_the_visibility_check():@@ -529,94 +472,30 @@ def test_every_project_entry_point_resolves_through_the_visibility_check():assert ungated == [], f"Project entry points that never reach a visibility check: {ungated}"-def test_folder_path_is_not_a_side_door_onto_a_hidden_project(engine, tmp_path):- """Create-or-reuse is a Project lookup, so it carries the visibility rule too.-- A folder path is a lookup key exactly as much as a Project id is. Reuse- resolved the match without the ACL, so a member who submitted the folder of- a restricted Project they are excluded from got its payload back -- and,- when the Project was archived, revived it on the way, since reuse is also- the unarchive path.-- Applying the *same* check the list applies carries one declared consequence:- ``get_effective_project_role`` returns nothing for an inactive Project below- the Instance Owner, so restoring an archived Project by re-opening its- folder is Owner-only. That is not a new rule, it is the existing one finally- reaching this path -- ``list_projects(include_archived=True)``,- ``get_project``, ``update_project``, and ``archive_project`` already answer- a non-owner with nothing for an archived Project.- """-- folder = tmp_path / "hidden"[email protected]("role", ["member", "owner", "editor", "viewer"])+def test_project_folder_reuse_and_restore_follow_instance_operations(engine, tmp_path, role):+ """Managers reuse/restore restricted folders without changing their ACL."""+ folder = tmp_path / "restricted"folder.mkdir()- owner = _remote_context("owner")+ context = _acl_context(role, email="[email protected]")with engine.begin() as conn:- project = projects_service.create_project(- conn,- str(folder),- display_name="Hidden",- authorization_context=owner,- )+ project = projects_service.create_project(conn, str(folder), display_name="Restricted")_restrict_project_to(conn, project["id"], "[email protected]")-- excluded = _acl_context("member", email="[email protected]")- included = _acl_context("member", email="[email protected]")-- with engine.begin() as conn:- with pytest.raises(LookupError):- projects_service.create_project(- conn,- str(folder),- display_name="Stolen",- authorization_context=excluded,- )-- # The bound member reaches the same folder normally, so the refusal above is- # the ACL talking and not create-or-reuse breaking for everyone.- with engine.begin() as conn:- reused = projects_service.create_project(- conn,- str(folder),- display_name="Ignored On Reuse",- authorization_context=included,- )- assert reused["id"] == project["id"]- assert reused["display_name"] == "Hidden"-- # Archived: invisible to every non-owner, so reuse cannot revive it either.- with engine.begin() as conn:- projects_service.archive_project(conn, project["id"], authorization_context=owner)- for context in (excluded, included):- with pytest.raises(LookupError):- projects_service.create_project(- conn,- str(folder),- display_name="Revived",- authorization_context=context,- )-- # Refused without side effects: still archived, still named as its owner- # left it, and no duplicate scope minted over the same folder.- with engine.connect() as conn:- owned = projects_service.list_projects(- conn,- include_archived=True,- authorization_context=owner,- )- assert len(owned) == 1- assert owned[0]["id"] == project["id"]- assert owned[0]["display_name"] == "Hidden"- assert owned[0]["archived"] is True-- # The Owner still restores it the documented way, by re-opening the folder.- with engine.begin() as conn:- restored = projects_service.create_project(- conn,- str(folder),- authorization_context=owner,- )- assert restored["id"] == project["id"]- assert restored["archived"] is False+ policy = project_access_service.get_project_policy(conn, project["id"])+ for archived in (False, True):+ if archived:+ projects_service.archive_project(conn, project["id"])+ if role in {"member", "owner"}:+ reused = projects_service.create_project(conn, str(folder), display_name="Ignored", authorization_context=context)+ assert reused["id"] == project["id"]+ assert reused["display_name"] == "Restricted"+ assert reused["archived"] is False+ else:+ with pytest.raises(InstanceAuthorizationError):+ projects_service.create_project(conn, str(folder), authorization_context=context)+ assert projects_service.get_project(conn, project["id"])["archived"] == archived+ assert project_access_service.get_project_policy(conn, project["id"]) == policy+ assert len(projects_service.list_projects(conn, include_archived=True)) == 1def test_personal_instance_member_mutates_without_a_project_acl(engine, tmp_path):diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.pyindex 03642b16c..1c9147524 100644--- a/tests/test_resource_access_service.py+++ b/tests/test_resource_access_service.py@@ -697,13 +697,15 @@ def test_kindless_deferred_context_adopts_matching_validated_pairing(("organization", "email", False),],)[email protected](("instance_role", "completed_marker"), [("editor", False), ("member", False), ("member", True)])def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliveries(monkeypatch,tmp_path,paired_kind: str,access_source: str,- organization_claims: bool, sqlite_schema_db_factory,+ organization_claims: bool, sqlite_schema_db_factory, instance_role, completed_marker,) -> None:+ """PERMISSIONS-014: released metadata reaches Harness and queued-chat consumers."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))config = V2Config.default()config.remote_access.vibe_cloud.enabled = True@@ -713,8 +715,8 @@ def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliverieconfig.save()legacy_context = {- "sub": "legacy-user",- "vibe_instance_role": "editor",+ "sub": "legacy-user α",+ "vibe_instance_role": instance_role,"vibe_instance_access_source": access_source,"claims_issued_at": 1_700_000_000,}@@ -800,10 +802,19 @@ def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliveriesession_id="session-1",text="queued",metadata=legacy_metadata,+ now="2026-08-20T00:00:00Z",)from storage.importer import _run_sqlite_data_migrations_seed_ready_binding(connection, instance_id="paired-instance", instance_kind=paired_kind)+ if completed_marker:+ connection.execute(state_meta.insert().values(+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,+ value_json=json.dumps({+ "schema_version": 2, "state": "completed", "instance_id": "paired-instance",+ "instance_kind": paired_kind, "completed_at": "2026-08-21T00:00:00Z",+ }), updated_at="2026-08-21T00:00:00Z",+ ))counts = _run_sqlite_data_migrations(connection)assert _migration_counts(counts) == {"legacy_deferred_definitions": 2,@@ -832,7 +843,10 @@ def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliverieinstance_kind=paired_kind,generation=started["generation"],)- assert resource_access_service.resource_user_context_from_metadata(metadata) is not None+ restored = resource_access_service.resource_user_context_from_metadata(metadata)+ assert restored is not None and restored.instance_role == instance_role+ assert restored.subject == "legacy-user α"+ assert resource_access_service.metadata_allows_harness_runtime(metadata)run_metadata = connection.execute(select(agent_runs.c.metadata_json).where(agent_runs.c.definition_id == "legacy-task")@@ -842,9 +856,10 @@ def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliverie]assert run_snapshot["vibe_instance_id"] == "paired-instance"assert run_snapshot["vibe_instance_kind"] == paired_kind+ assert resource_access_service.metadata_allows_harness_runtime(json.loads(run_metadata))delivery = connection.execute(- select(message_deliveries.c.snapshot_json, message_deliveries.c.snapshot_sha256).where(+ select(message_deliveries).where(message_deliveries.c.session_id == "session-1")).mappings().one()@@ -860,6 +875,14 @@ def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliveriedelivery["snapshot_json"].encode("utf-8")).hexdigest()+ if instance_role == "member":+ from core.session_turns import SessionTurnManager+ assert SessionTurnManager._remote_delivery_execution_denial(connection, dict(delivery)) is None+ marker_after = _stored_migration_marker(connection)+ if completed_marker:+ assert json.loads(marker_after)["completed_at"] == "2026-08-21T00:00:00Z"+ # A later imported/unbound row is not a new migration opportunity.+ enqueue_queued(connection, scope_id=None, session_id="session-1", text="later", metadata=legacy_metadata)assert _migration_counts(_run_sqlite_data_migrations(connection)) == {@@ -867,11 +890,154 @@ def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliverie"legacy_deferred_runs": 0,"legacy_deferred_deliveries": 0,}+ assert _stored_migration_marker(connection) == marker_after+ later = connection.execute(select(message_deliveries).where(message_deliveries.c.id != delivery["id"])).mappings().one()+ assert "vibe_instance_id" not in json.loads(json.loads(later["snapshot_json"])["metadata_json"])[+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY+ ]finally:store.close()engine.dispose()[email protected]("case", [+ "sealed", "missing_kind", "invalid_kind", "other_instance", "other_kind",+ "corrupt", "unknown_state", "unknown_version", "missing_cutoff", "invalid_cutoff",+ "naive_cutoff", "reconciling", "binding_mismatch", "binding_absent",+ "snapshot_instance", "snapshot_kind", "snapshot_unknown_kind", "snapshot_org", "editor",+ "new_row", "changed_row", "equal_second", "invalid_timestamp",+])+def test_completed_member_repair_preserves_unproven_rows(monkeypatch, tmp_path, sqlite_schema_db_factory, case):+ """PERMISSIONS-014: a completed marker cannot attribute later or foreign work."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ _paired_cloud_config(tmp_path)+ db = tmp_path / "vibe.sqlite"+ sqlite_schema_db_factory(db)+ engine = create_sqlite_engine(db)+ old = "2026-08-20T00:00:00Z"+ cutoff = "2026-08-21T00:00:00Z"+ marker = {+ "schema_version": 2, "state": "completed", "instance_id": "same-instance",+ "instance_kind": "personal", "completed_at": cutoff,+ }+ overrides = {+ "sealed": {"state": "sealed_unattributed"},+ "missing_kind": {"instance_kind": None},+ "invalid_kind": {"instance_kind": "enterprise"},+ "other_instance": {"instance_id": "other-instance"},+ "other_kind": {"instance_kind": "organization"},+ "unknown_state": {"state": "future-state"},+ "unknown_version": {"schema_version": 999},+ "missing_cutoff": {"completed_at": None},+ "invalid_cutoff": {"completed_at": "yesterday"},+ "naive_cutoff": {"completed_at": "2026-08-21T00:00:00"},+ }+ marker.update(overrides.get(case, {}))+ marker_json = "corrupt" if case == "corrupt" else json.dumps(marker)+ snapshot = {"sub": "legacy-member α", "vibe_instance_role": "member", "vibe_instance_access_source": "email"}+ snapshot.update({+ "snapshot_instance": {"vibe_instance_id": "other-instance"},+ "snapshot_kind": {"vibe_instance_kind": "organization"},+ "snapshot_unknown_kind": {"vibe_instance_kind": "enterprise"},+ "snapshot_org": {"vibe_organization_id": "old-org"},+ "editor": {"vibe_instance_role": "editor"},+ }.get(case, {}))+ metadata_json = json.dumps({resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: snapshot})+ later = "2026-08-22T00:00:00Z"+ created_at = later if case == "new_row" else cutoff if case == "equal_second" else old+ updated_at = later if case in {"new_row", "changed_row"} else cutoff if case == "equal_second" else old+ if case == "invalid_timestamp":+ updated_at = "invalid"+ try:+ with engine.begin() as conn:+ conn.execute(state_meta.insert().values(+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,+ value_json=marker_json, updated_at=cutoff,+ ))+ if case != "binding_absent":+ _seed_ready_binding(conn, instance_id="other" if case == "binding_mismatch" else "same-instance", instance_kind="personal")+ if case == "reconciling":+ conn.execute(state_meta.update().where(state_meta.c.key == "remote_access.instance_binding.v1").values(+ value_json=json.dumps({"schema_version": 1, "state": "reconciling", "instance_id": "same-instance",+ "instance_kind": "personal", "generation": 1}),+ ))+ for kind in ("scheduled", "watch"):+ conn.execute(run_definitions.insert().values(+ id=kind, definition_type=kind, enabled=1, metadata_json=metadata_json,+ created_at=created_at, updated_at=updated_at,+ ))+ conn.execute(agent_runs.insert().values(+ id="run", run_type="scheduled", status="queued", metadata_json=metadata_json,+ created_at=created_at, updated_at=updated_at,+ ))+ conn.execute(agent_sessions.insert().values(+ id="session", agent_backend="codex", agent_variant="default", session_anchor="session",+ native_session_id="native", status="active", metadata_json="{}", created_at=old, updated_at=old,+ ))+ enqueue_queued(conn, scope_id=None, session_id="session", text="你好", metadata=json.loads(metadata_json), now=created_at)+ conn.execute(message_deliveries.update().values(updated_at=updated_at))+ tables = (run_definitions, agent_runs, message_deliveries)+ before = [[dict(row) for row in conn.execute(select(table)).mappings()] for table in tables]+ for _ in range(2):+ assert _migration_counts(resource_access_service.migrate_legacy_deferred_resource_contexts(conn)) == _EMPTY_MIGRATION_COUNTS+ assert [[dict(row) for row in conn.execute(select(table)).mappings()] for table in tables] == before+ if case in overrides or case in {"corrupt", "reconciling", "binding_mismatch", "binding_absent"}:+ assert _stored_migration_marker(conn) == marker_json+ finally:+ engine.dispose()++[email protected]("completed_marker", [False, True])+def test_member_migration_preserves_terminal_records(monkeypatch, tmp_path, sqlite_schema_db_factory, completed_marker):+ """Queued/reserved work may bind; retired Deliveries and completed Runs stay intact."""+ from storage.delivery_states import DELIVERY_STATE_MATRIX++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ _paired_cloud_config(tmp_path)+ db = tmp_path / "vibe.sqlite"+ sqlite_schema_db_factory(db)+ engine = create_sqlite_engine(db)+ old = "2026-08-20T00:00:00Z"+ metadata = {resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {+ "sub": "member", "vibe_instance_role": "member", "vibe_instance_access_source": "email",+ }}+ try:+ with engine.begin() as conn:+ _seed_ready_binding(conn, instance_id="same-instance", instance_kind="personal")+ if completed_marker:+ conn.execute(state_meta.insert().values(+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,+ value_json=json.dumps({"schema_version": 2, "state": "completed", "instance_id": "same-instance",+ "instance_kind": "personal", "completed_at": "2026-08-21T00:00:00Z"}), updated_at=old,+ ))+ conn.execute(agent_sessions.insert().values(+ id="session", agent_backend="codex", agent_variant="default", session_anchor="session",+ native_session_id="native", status="active", metadata_json="{}", created_at=old, updated_at=old,+ ))+ deliveries = {}+ for state in ("reserved", "queued", "retired"):+ payload = enqueue_queued(conn, scope_id=None, session_id="session", text=state, metadata=metadata, now=old)+ delivery_id = payload["id"]+ conn.execute(message_deliveries.update().where(message_deliveries.c.id == delivery_id).values(state=state))+ deliveries[state] = dict(conn.execute(select(message_deliveries).where(message_deliveries.c.id == delivery_id)).mappings().one())+ terminal_run = dict(id="terminal-run", run_type="agent_run", status="completed", metadata_json=json.dumps(metadata), created_at=old, updated_at=old)+ conn.execute(agent_runs.insert().values(**terminal_run))+ terminal_before = dict(conn.execute(select(agent_runs)).mappings().one())+ counts = resource_access_service.migrate_legacy_deferred_resource_contexts(conn)+ assert counts["legacy_deferred_deliveries"] == 2+ assert dict(conn.execute(select(agent_runs)).mappings().one()) == terminal_before+ for state, before in deliveries.items():+ after = dict(conn.execute(select(message_deliveries).where(message_deliveries.c.id == before["id"])).mappings().one())+ if DELIVERY_STATE_MATRIX[state].ordering == "terminal":+ assert after == before+ else:+ assert after["state"] == state+ assert after["snapshot_sha256"] == hashlib.sha256(after["snapshot_json"].encode()).hexdigest()+ assert json.loads(json.loads(after["snapshot_json"])["metadata_json"])[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]["vibe_instance_id"] == "same-instance"+ finally:+ engine.dispose()++def test_legacy_migration_keeps_opposite_instance_semantics_unbound(monkeypatch, tmp_path, sqlite_schema_db_factory) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))config = V2Config.default()@@ -1770,7 +1936,7 @@ def test_pre_member_resource_user_context_snapshot_keeps_editor_role() -> None:assert not restored.can_manage_instance-def test_organization_member_remains_subject_to_resource_acl_for_use(tmp_path, sqlite_schema_db_factory) -> None:+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)engine = create_sqlite_engine(db)@@ -1783,13 +1949,13 @@ def test_organization_member_remains_subject_to_resource_acl_for_use(tmp_path, sgroup_ids=frozenset({"group-sales"}),)assert member.can_manage_instance- assert not resource_access_service.can_use_resource(+ assert resource_access_service.can_use_resource(member, "agent", "private-agent", connection=connection)assert resource_access_service.can_use_resource(member, "agent", "public-agent", connection=connection)- assert not resource_access_service.can_use_resource(+ assert resource_access_service.can_use_resource(member, "agent", "scoped-agent", connection=connection)finally:@@ -2261,3 +2427,469 @@ def test_kindless_deferred_snapshot_fails_closed_when_pairing_is_unpaired(assert restored is not Noneassert restored.instance_role == "editor"assert restored.instance_kind is None+++def member_repair_race(monkeypatch, tmp_path, sqlite_schema_db_factory, family):+ """Real WAL state shared by the migration and an independent runtime writer."""+ from types import SimpleNamespace++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ _paired_cloud_config(tmp_path)+ db = tmp_path / "race.sqlite"+ sqlite_schema_db_factory(db)+ engine = create_sqlite_engine(db)+ peer = create_sqlite_engine(db)+ old = "2026-08-20T00:00:00Z"+ metadata = {resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {+ "sub": "member α", "vibe_instance_role": "member", "vibe_instance_access_source": "email",+ }}+ marker = {"schema_version": 2, "state": "completed", "instance_id": "same-instance",+ "instance_kind": "personal", "completed_at": "2026-08-21T00:00:00Z"}+ with engine.begin() as conn:+ _seed_ready_binding(conn, instance_id="same-instance", instance_kind="personal")+ conn.execute(state_meta.insert().values(+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,+ value_json=json.dumps(marker), updated_at=old,+ ))+ for kind in ("scheduled", "watch"):+ conn.execute(run_definitions.insert().values(+ id=kind, definition_type=kind, enabled=1, metadata_json=json.dumps(metadata),+ created_at=old, updated_at=old,+ ))+ conn.execute(agent_runs.insert().values(+ id="run", run_type="scheduled", status="queued", metadata_json=json.dumps(metadata),+ created_at=old, updated_at=old,+ ))+ conn.execute(agent_sessions.insert().values(+ id="session", agent_backend="codex", agent_variant="default", session_anchor="session",+ native_session_id="native", status="active", metadata_json="{}", created_at=old, updated_at=old,+ ))+ delivery = enqueue_queued(conn, scope_id=None, session_id="session", text="你好", metadata=metadata, now=old)+ # Only the selected family is eligible: an earlier table's write must+ # not accidentally reserve the lock and hide a later family's race.+ if family in {"scheduled", "watch"}:+ conn.execute(run_definitions.delete().where(run_definitions.c.id != family))+ elif family in {"run", "delivery"}:+ conn.execute(run_definitions.delete())+ if family not in {"run", "binding", "marker"}:+ conn.execute(agent_runs.delete())+ if family not in {"delivery", "binding", "marker"}:+ conn.execute(message_deliveries.delete())+ expected = {"legacy_deferred_definitions": 2, "legacy_deferred_runs": 1, "legacy_deferred_deliveries": 1}+ if family not in {"binding", "marker"}:+ expected = dict(_EMPTY_MIGRATION_COUNTS)+ key = "legacy_deferred_definitions" if family in {"scheduled", "watch"} else f"legacy_deferred_{'runs' if family == 'run' else 'deliveries'}"+ expected[key] = 1++ def mutation(family):+ later = "2026-08-22T00:00:00Z"+ changed = json.dumps({**metadata, "concurrent_edit": "survives α"})+ if family in {"scheduled", "watch"}:+ return run_definitions, run_definitions.c.id == family, {"metadata_json": changed, "updated_at": later}+ if family == "run":+ return agent_runs, agent_runs.c.id == "run", {"metadata_json": changed, "updated_at": later, "status": "completed"}+ if family == "delivery":+ snapshot = json.dumps({"metadata_json": changed, "text": "peer α"})+ return message_deliveries, message_deliveries.c.id == delivery["id"], {+ "snapshot_json": snapshot, "snapshot_sha256": hashlib.sha256(snapshot.encode()).hexdigest(),+ "updated_at": later, "state": "retired",+ }+ if family == "binding":+ return state_meta, state_meta.c.key == "remote_access.instance_binding.v1", {+ "value_json": json.dumps({"schema_version": 1, "state": "reconciling", "instance_id": "other-instance",+ "instance_kind": "personal", "generation": 2}), "updated_at": later,+ }+ assert family == "marker"+ return state_meta, state_meta.c.key == resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY, {+ "value_json": json.dumps({**marker, "state": "sealed_unattributed"}), "updated_at": later,+ }++ try:+ yield SimpleNamespace(engine=engine, peer=peer, mutation=mutation, expected=expected)+ finally:+ peer.dispose()+ engine.dispose()++[email protected]("family", ["scheduled", "watch", "run", "delivery", "binding", "marker"])+def test_member_repair_serializes_peer_writes_through_marker_seal(member_repair_race, family):+ """PERMISSIONS-014: a writer after decision reads cannot race any repair effect."""+ from concurrent.futures import ThreadPoolExecutor+ from sqlalchemy import event+ from sqlalchemy.exc import OperationalError++ state = member_repair_race+ table, predicate, values = state.mutation(family)+ attempts = []++ def peer_write():+ try:+ with state.peer.begin() as conn:+ conn.exec_driver_sql("PRAGMA busy_timeout = 0")+ conn.execute(table.update().where(predicate).values(**values))+ except OperationalError as exc:+ assert "locked" in str(exc)+ return "blocked"+ return "committed"++ with ThreadPoolExecutor(max_workers=1) as pool:+ def after_read(_conn, _cursor, statement, parameters, _context, _many):+ sql = " ".join(statement.split())+ if attempts or not sql.startswith("SELECT") or f"FROM {table.name}" not in sql:+ return+ if family in {"marker", "binding"}:+ key = "remote_access.instance_binding.v1" if family == "binding" else resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY+ if key not in parameters:+ return+ # The SELECT has executed, but migration has not consumed its rows.+ # Await a real second connection's completed write attempt, not time.+ attempts.append(pool.submit(peer_write).result(timeout=5))++ event.listen(state.engine, "after_cursor_execute", after_read)+ try:+ with state.engine.begin() as conn:+ result = resource_access_service.migrate_legacy_deferred_resource_contexts(conn)+ assert attempts == ["blocked"]+ assert _migration_counts(result) == state.expected+ assert json.loads(_stored_migration_marker(conn))["schema_version"] == 3+ # The writer slot lasts through sealing until the caller commits.+ assert pool.submit(peer_write).result(timeout=5) == "blocked"+ finally:+ event.remove(state.engine, "after_cursor_execute", after_read)+ assert pool.submit(peer_write).result(timeout=5) == "committed"+ with state.engine.connect() as conn:+ row = conn.execute(select(table).where(predicate)).mappings().one()+ assert {key: row[key] for key in values} == values++[email protected]("family", ["scheduled", "watch", "run", "delivery", "binding", "marker"])+def test_member_repair_reads_peer_first_commit_after_writer_reservation(member_repair_race, family):+ """A peer holding the writer first changes eligibility before the repair reads."""+ from concurrent.futures import ThreadPoolExecutor+ from threading import Event+ from sqlalchemy import event++ state = member_repair_race+ table, predicate, values = state.mutation(family)+ entering = Event()+ peer_committed = Event()++ def entering_transaction(_conn, _cursor, statement, _parameters, _context, _many):+ entering.set()+ if statement.lstrip().startswith("SELECT"):+ assert peer_committed.wait(timeout=5)++ def repair():+ with state.engine.begin() as conn:+ return resource_access_service.migrate_legacy_deferred_resource_contexts(conn)++ event.listen(state.engine, "before_cursor_execute", entering_transaction)+ try:+ with ThreadPoolExecutor(max_workers=1) as pool:+ with state.peer.begin() as conn:+ conn.execute(table.update().where(predicate).values(**values))+ future = pool.submit(repair)+ assert entering.wait(timeout=5)+ # Release the earlier writer only once the migration is entering.+ peer_committed.set()+ counts = _migration_counts(future.result(timeout=5))+ finally:+ event.remove(state.engine, "before_cursor_execute", entering_transaction)+ assert counts == _EMPTY_MIGRATION_COUNTS+ with state.engine.connect() as conn:+ row = conn.execute(select(table).where(predicate)).mappings().one()+ assert {key: row[key] for key in values} == values++[email protected]("transaction", ["new", "writer", "savepoint"])+def test_member_migration_reservation_supports_initial_schema_and_existing_transactions(tmp_path, transaction):+ """The released initial schema owns agent_sessions.id used by nested reservation."""+ from storage.migrations import INITIAL_REVISION++ db = tmp_path / "initial.sqlite"+ run_migrations(db, revision=INITIAL_REVISION)+ engine = create_sqlite_engine(db)+ try:+ with engine.connect() as conn:+ with conn.begin():+ if transaction == "writer":+ conn.execute(state_meta.insert().values(key="caller-write", value_json="{}", updated_at="now"))+ nested = conn.begin_nested() if transaction == "savepoint" else None+ result = resource_access_service.migrate_legacy_deferred_resource_contexts(conn)+ assert _migration_counts(result) == _EMPTY_MIGRATION_COUNTS+ assert conn.connection.dbapi_connection.in_transaction+ if nested:+ nested.rollback()+ finally:+ engine.dispose()++[email protected]("family", ["scheduled"])[email protected]("nested", [False, True])+def test_member_repair_keeps_existing_transaction_owned_by_caller(member_repair_race, family, nested):+ state = member_repair_race+ with state.engine.connect() as conn:+ outer = conn.begin()+ conn.execute(state_meta.insert().values(key="caller-write", value_json="{}", updated_at="now"))+ savepoint = conn.begin_nested() if nested else None+ assert _migration_counts(resource_access_service.migrate_legacy_deferred_resource_contexts(conn)) == state.expected+ assert json.loads(_stored_migration_marker(conn))["schema_version"] == 3+ if savepoint:+ savepoint.rollback()+ assert json.loads(_stored_migration_marker(conn))["schema_version"] == 2+ assert conn.execute(select(state_meta.c.key).where(state_meta.c.key == "caller-write")).first()+ outer.rollback()+ with state.engine.connect() as conn:+ assert json.loads(_stored_migration_marker(conn))["schema_version"] == 2+ assert not conn.execute(select(state_meta.c.key).where(state_meta.c.key == "caller-write")).first()+ snapshot = _legacy_definition_metadata(conn, "scheduled")[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]+ assert "vibe_instance_id" not in snapshot+++def member_repair_provenance(monkeypatch, tmp_path, sqlite_schema_db_factory):+ """Released rows with a completed marker, before a real runtime producer writes."""+ from types import SimpleNamespace++ from config import paths++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ _paired_cloud_config(tmp_path)+ db = paths.get_sqlite_state_path()+ db.parent.mkdir(parents=True, exist_ok=True)+ sqlite_schema_db_factory(db)+ store = SQLiteBackgroundTaskStore(db)+ old = "2026-08-20T00:00:00Z"+ cutoff = "2026-08-21T00:00:00Z"+ later = "2026-08-22T00:00:00Z"+ context = {+ "sub": "member α", "vibe_instance_role": "member",+ "vibe_instance_access_source": "email", "claims_issued_at": 1_700_000_000,+ "vibe_membership_version": 7, "vibe_instance_authorization_revision": 9,+ "authorization_expires_at": 1_700_003_600,+ }+ metadata = {"resource_user_context": context, "note": {"text": "preserve 当前", "value": [1, 2]}}+ for kind in ("scheduled", "watch"):+ values = dict(id=kind, name=kind, message="run", schedule_type="interval",+ created_at=old, updated_at=old, metadata=metadata)+ writer = store.upsert_scheduled_task if kind == "scheduled" else store.upsert_watch+ assert writer(values)+ store.enqueue_run(dict(id="run", run_type="hook_send", status="queued", session_id="session",+ created_at=old, updated_at=old, metadata=metadata))+ with store.engine.begin() as conn:+ _seed_ready_binding(conn, instance_id="same-instance", instance_kind="personal")+ conn.execute(state_meta.insert().values(+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,+ value_json=json.dumps({"schema_version": 2, "state": "completed", "instance_id": "same-instance",+ "instance_kind": "personal", "completed_at": cutoff}), updated_at=cutoff,+ ))+ conn.execute(agent_sessions.insert().values(+ id="session", agent_backend="codex", agent_variant="default", session_anchor="session",+ native_session_id="native", status="active", metadata_json="{}", created_at=old, updated_at=old,+ ))+ delivery = enqueue_queued(conn, scope_id=None, session_id="session", text="你好", metadata=metadata, now=old)+ try:+ yield SimpleNamespace(store=store, db=db, old=old, cutoff=cutoff, later=later,+ context=context, metadata=metadata, delivery_id=delivery["id"])+ finally:+ store.close()++[email protected]("diagnostic", ["pristine", "present", "cleared"])+def test_member_repair_preserves_real_run_diagnostics_and_authorization(member_repair_provenance, diagnostic):+ """PERMISSIONS-014: skip history is not authorization history or a hold-clock update."""+ state = member_repair_provenance+ store = state.store+ if diagnostic != "pristine":+ assert store.record_run_skip_reason("run", reason="transport_unavailable", at=state.later)+ if diagnostic == "cleared":+ assert store._clear_transport_skip_evidence({"run"}) == 1+ before = store.get_run("run")+ assert before["updated_at"] == state.old+ assert before["metadata"]["resource_user_context"] == state.context+ if diagnostic in {"pristine", "cleared"}:+ assert before["metadata"] == state.metadata # Clearing leaves no mutation history.+ else:+ assert before["metadata"]["last_skip_at"] == state.later+ assert not resource_access_service.metadata_allows_harness_runtime(before["metadata"])+ with store.engine.begin() as conn:+ assert resource_access_service.migrate_legacy_deferred_resource_contexts(conn)["legacy_deferred_runs"] == 1+ after = store.get_run("run")+ assert after["metadata"] == {+ **before["metadata"], "resource_user_context": {+ **state.context, "vibe_instance_id": "same-instance", "vibe_instance_kind": "personal",+ },+ }+ assert {k: v for k, v in after.items() if k not in {"metadata", "updated_at"}} == {+ k: v for k, v in before.items() if k not in {"metadata", "updated_at"}+ }+ assert resource_access_service.metadata_allows_harness_runtime(after["metadata"])+ from core.session_turns import SessionTurnManager+ with store.engine.begin() as conn:+ delivery = conn.execute(select(message_deliveries)).mappings().one()+ assert SessionTurnManager._remote_delivery_execution_denial(conn, dict(delivery)) is None+ marker = _stored_migration_marker(conn)+ assert _migration_counts(resource_access_service.migrate_legacy_deferred_resource_contexts(conn)) == _EMPTY_MIGRATION_COUNTS+ assert _stored_migration_marker(conn) == marker+ assert store.get_run("run") == after++[email protected]("kind", ["scheduled", "watch"])+def test_member_repair_refuses_real_post_cutoff_authorization_update(member_repair_provenance, monkeypatch, tmp_path, kind):+ """PERMISSIONS-014: the user-edit producer replaces authority and advances its clock."""+ from core import scheduled_tasks, watches++ state = member_repair_provenance+ module = scheduled_tasks if kind == "scheduled" else watches+ monkeypatch.setattr(module, "_utc_now_iso", lambda: state.later)+ context = _context("replacement β", organization_id=None, instance_role="member", access_source="email")+ # An old no-kind caller can still save a legacy-shaped snapshot. Its new+ # timestamp, not an assumption that every caller already supplies binding,+ # must prevent the original marker from claiming that replacement authority.+ if kind == "scheduled":+ definitions = scheduled_tasks.ScheduledTaskStore(tmp_path / "unused-tasks.json")+ definitions._sqlite = state.store+ definitions.load()+ definitions.update_task(kind, name=kind, session_key="", prompt="edited", schedule_type="interval",+ post_to=None, deliver_key=None, cron=None, run_at=None, timezone_name="UTC",+ user_context=context)+ else:+ definitions = watches.ManagedWatchStore(tmp_path / "unused-watches.json")+ definitions._sqlite = state.store+ definitions.load()+ definitions.update_watch(kind, name=kind, session_key="", session_id=None, command=["true"],+ shell_command=None, prefix=None, cwd=None, mode="once", timeout_seconds=0,+ lifetime_timeout_seconds=0, retry_exit_codes=[75], retry_delay_seconds=30,+ post_to=None, deliver_key=None, user_context=context)+ with state.store.engine.begin() as conn:+ before = dict(conn.execute(select(run_definitions).where(run_definitions.c.id == kind)).mappings().one())+ metadata = json.loads(before["metadata_json"])+ assert metadata["resource_user_context"]["sub"] == "replacement β"+ assert metadata["resource_user_context"]["vibe_instance_id"] is None+ assert before["updated_at"] == state.later+ assert resource_access_service.migrate_legacy_deferred_resource_contexts(conn)["legacy_deferred_definitions"] == 1+ after = dict(conn.execute(select(run_definitions).where(run_definitions.c.id == kind)).mappings().one())+ assert after == before+ assert not resource_access_service.metadata_allows_harness_runtime(metadata)++[email protected]("kind", ["run", "delivery"])+def test_member_repair_refuses_real_post_cutoff_lifecycle_update(member_repair_provenance, monkeypatch, kind):+ from storage import message_deliveries as deliveries++ state = member_repair_provenance+ if kind == "run":+ assert state.store.claim_pending_run("run", started_at=state.later) is not None+ table, row_id = agent_runs, "run"+ else:+ monkeypatch.setattr(deliveries, "utc_now_iso", lambda: state.later)+ with state.store.engine.begin() as conn:+ row = deliveries.get_delivery(conn, state.delivery_id)+ assert deliveries.cas_delivery(conn, row["id"], expected_version=row["version"],+ expected_states=("queued",), values={},+ history_event={"kind": "retry_claim"}) is not None+ table, row_id = message_deliveries, state.delivery_id+ with state.store.engine.begin() as conn:+ before = dict(conn.execute(select(table).where(table.c.id == row_id)).mappings().one())+ assert before["updated_at"] == state.later+ counts = resource_access_service.migrate_legacy_deferred_resource_contexts(conn)+ assert counts[f"legacy_deferred_{'runs' if kind == 'run' else 'deliveries'}"] == 0+ assert dict(conn.execute(select(table).where(table.c.id == row_id)).mappings().one()) == before+++def test_member_repair_preserves_real_stable_agent_reference_rewrites(member_repair_provenance):+ """PERMISSIONS-014: catalog canonicalization changes routing, not the initiating principal."""+ from core.vibe_agents import VibeAgentStore, ensure_agent_selection_access+ from storage.session_reclaim import DEFINITION_AGENT_BINDING_REVISION_KEY++ state = member_repair_provenance+ agents = VibeAgentStore(state.db)+ try:+ original = agents.create(name="repair-agent", backend="codex")+ metadata = {**state.metadata, "session_settings_snapshot": {"agent_name": original.name, "model": "keep"}}+ with state.store.engine.begin() as conn:+ conn.execute(run_definitions.update().values(agent_name=original.name, metadata_json=json.dumps(metadata)))+ conn.execute(agent_runs.update().values(agent_name=original.name, agent_id=None))+ assert state.store.refresh_run_agent_reference("run") == {"agent_id": original.id, "agent_name": original.name}+ renamed = agents.rename(original.name, "repair-agent-renamed")+ assert renamed.id == original.id+ with state.store.engine.begin() as conn:+ before = list(conn.execute(select(run_definitions)).mappings())+ run_before = dict(conn.execute(select(agent_runs)).mappings().one())+ assert run_before["agent_id"] == original.id and run_before["agent_name"] == renamed.name+ assert run_before["updated_at"] == state.old+ for row in before:+ current = json.loads(row["metadata_json"])+ assert current["resource_user_context"] == state.context+ assert current["session_settings_snapshot"] == {"agent_name": renamed.name, "model": "keep"}+ assert current[DEFINITION_AGENT_BINDING_REVISION_KEY]+ assert row["updated_at"] == state.old+ assert resource_access_service.migrate_legacy_deferred_resource_contexts(conn)["legacy_deferred_definitions"] == 2+ for row in before:+ after = dict(conn.execute(select(run_definitions).where(run_definitions.c.id == row["id"])).mappings().one())+ expected = json.loads(row["metadata_json"])+ expected["resource_user_context"] = {**state.context, "vibe_instance_id": "same-instance", "vibe_instance_kind": "personal"}+ assert json.loads(after.pop("metadata_json")) == expected+ assert after == {k: v for k, v in row.items() if k != "metadata_json"}+ assert resource_access_service.metadata_allows_harness_runtime(expected)+ context = resource_access_service.resource_user_context_from_metadata(expected)+ selected = ensure_agent_selection_access(conn, agent_name=renamed.name, agent_id=original.id,+ user_context=context, missing_is_error=True)+ assert selected.id == original.id+ run_after = dict(conn.execute(select(agent_runs)).mappings().one())+ assert {k: v for k, v in run_after.items() if k not in {"metadata_json", "updated_at"}} == {+ k: v for k, v in run_before.items() if k not in {"metadata_json", "updated_at"}+ }+ assert json.loads(run_after["metadata_json"])["resource_user_context"] == {+ **state.context, "vibe_instance_id": "same-instance", "vibe_instance_kind": "personal",+ }+ finally:+ agents.close()+++def test_member_repair_preserves_real_soft_deletion(member_repair_provenance):+ state = member_repair_provenance+ state.store.remove_task("scheduled")+ assert state.store.get_scheduled_task("scheduled") is None+ with state.store.engine.begin() as conn:+ before = dict(conn.execute(select(run_definitions).where(run_definitions.c.id == "scheduled")).mappings().one())+ assert before["deleted_at"] and before["updated_at"] == state.old+ resource_access_service.migrate_legacy_deferred_resource_contexts(conn)+ after = dict(conn.execute(select(run_definitions).where(run_definitions.c.id == "scheduled")).mappings().one())+ assert {k: v for k, v in after.items() if k != "metadata_json"} == {+ k: v for k, v in before.items() if k != "metadata_json"+ }+ assert state.store.get_scheduled_task("scheduled") is None+++def test_member_repair_preserves_real_delivery_dedupe_normalization(member_repair_provenance):+ from core.session_turns import SessionTurnManager+ from storage import message_deliveries as deliveries++ state = member_repair_provenance+ with state.store.engine.begin() as conn:+ row = deliveries.insert_delivery(+ conn, delivery_id="legacy-native", session_id="session", priority="p3", state="queued",+ snapshot=deliveries.message_snapshot(scope_id="scope", session_id="session", platform="slack",+ author="user", source="user", text="hello", metadata=state.metadata),+ dispatch_text="hello", dedupe_key=deliveries.native_dedupe_key("slack", "native"), now=state.old,+ )+ normalized = deliveries.get_delivery_by_native_identity(+ conn, platform="slack", native_message_id="native", scope_id="scope", session_id="session", normalize_legacy=True,+ )+ assert normalized["dedupe_key"] != row["dedupe_key"]+ assert normalized["snapshot_json"] == row["snapshot_json"]+ assert normalized["updated_at"] == state.old+ resource_access_service.migrate_legacy_deferred_resource_contexts(conn)+ repaired = deliveries.get_delivery(conn, "legacy-native")+ assert repaired["dedupe_key"] == normalized["dedupe_key"]+ snapshot = json.loads(repaired["snapshot_json"])+ expected = json.loads(normalized["snapshot_json"])+ metadata = json.loads(expected["metadata_json"])+ metadata["resource_user_context"].update(vibe_instance_id="same-instance", vibe_instance_kind="personal")+ assert json.loads(snapshot.pop("metadata_json")) == metadata+ expected.pop("metadata_json")+ assert snapshot == expected+ assert repaired["snapshot_sha256"] == hashlib.sha256(repaired["snapshot_json"].encode()).hexdigest()+ assert SessionTurnManager._remote_delivery_execution_denial(conn, repaired) is Nonediff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.pyindex dd75ff68a..d1471410e 100644--- a/tests/test_resource_acl_agents.py+++ b/tests/test_resource_acl_agents.py@@ -510,7 +510,7 @@ def test_unpinned_session_dispatches_the_agent_the_default_degraded_to(monkeypatmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))store, agents = _seed_agents_with_policies()engine = get_cached_sqlite_engine()- member = _organization_context("member-1", instance_role="member")+ member = _organization_context("editor-1", instance_role="editor")try:# The configured instance default is another owner's private Agent; the# caller is entitled to others.diff --git a/tests/test_resource_acl_vaults.py b/tests/test_resource_acl_vaults.pyindex 99142c6b5..bc19fb391 100644--- a/tests/test_resource_acl_vaults.py+++ b/tests/test_resource_acl_vaults.py@@ -754,10 +754,9 @@ def test_secret_management_follows_instance_manager_capability(vault, role):@pytest.mark.parametrize("policy", ["missing", "foreign"])-def test_management_parity_does_not_bypass_direct_secret_use_policy(vault, policy):- # Direct service contexts retain ACL checks; validated remote Organization- # use intentionally has the existing Editor-or-higher behavior above.- context = _context("manager", instance_role="member", is_remote=False)[email protected]("role", ["owner", "member", "editor", "viewer"])+def test_direct_secret_operations_preserve_protected_approval_and_lower_role_acl(vault, policy, role):+ context = _context("manager", instance_role=role, is_remote=False)with vault.begin() as conn:_create_secret(conn, "DIRECT_PRIVATE", protection="protected")resource_id = _secret_id(conn, "DIRECT_PRIVATE")@@ -769,6 +768,15 @@ def test_management_parity_does_not_bypass_direct_secret_use_policy(vault, policaccess_level="private", group_ids=[], policy_revision=1,last_applied_control_plane_revision=1,)- vault_service.update_secret_metadata(conn, "DIRECT_PRIVATE", description="managed", user_context=context)- with pytest.raises(vault_service.VaultSecretAccessError):- vault_service.resolve_secret_access(conn, "DIRECT_PRIVATE", session_id="ses-private", user_context=context)+ before = [dict(row) for row in conn.execute(select(resource_access_policies)).mappings()]+ if role in {"owner", "member"}:+ vault_service.update_secret_metadata(conn, "DIRECT_PRIVATE", description="managed", user_context=context)+ access = vault_service.resolve_secret_access(conn, "DIRECT_PRIVATE", session_id="ses-private", user_context=context)+ assert access["status"] == "approval_required"+ assert access["request"]["status"] == "pending"+ assert access.get("envelope") is None+ assert access["request"]["card"]["value"] is None+ else:+ with pytest.raises(vault_service.VaultSecretAccessError):+ vault_service.resolve_secret_access(conn, "DIRECT_PRIVATE", session_id="ses-private", user_context=context)+ assert [dict(row) for row in conn.execute(select(resource_access_policies)).mappings()] == beforediff --git a/tests/test_skill_observability.py b/tests/test_skill_observability.pyindex 52af0f33e..475918cd2 100644--- a/tests/test_skill_observability.py+++ b/tests/test_skill_observability.py@@ -356,19 +356,23 @@ def test_invalid_observations_do_not_write(engine, mutate):assert counts(engine) == (0, None)-def test_owner_only_sql_access_including_cte(engine):[email protected]("role", ["owner", "member", "editor", "viewer", None])+def test_manager_sql_access_including_cte(engine, role):from storage.read_only_query import ReadOnlyQueryError, run_read_only_queryfrom vibe.authorization import AuthorizationContextwrite(engine, load())- remote = AuthorizationContext(is_remote=True, instance_role="editor")+ remote = AuthorizationContext(is_remote=True, instance_role=role)for table in ("skill_usage_daily", "agent_events"):+ query = f"WITH stats AS (SELECT * FROM {table}) SELECT count(*) AS n FROM stats"+ if role in {"member", "owner"}:+ assert run_read_only_query(query, page_request=None, user_context=remote).rows == [{"n": 1}]+ else:+ with pytest.raises(ReadOnlyQueryError):+ run_read_only_query(query, page_request=None, user_context=remote)+ for query in ("DELETE FROM skill_usage_daily", "SELECT * FROM vault_secrets"):with pytest.raises(ReadOnlyQueryError):- run_read_only_query(- f"WITH stats AS (SELECT * FROM {table}) SELECT count(*) FROM stats",- page_request=None,- user_context=remote,- )+ run_read_only_query(query, page_request=None, user_context=remote)assert run_read_only_query("SELECT count(*) AS n FROM skill_usage_daily", page_request=None).rows == [{"n": 1}]@@ -584,7 +588,7 @@ def test_skill_usage_errors_follow_cli_language(monkeypatch, capsys, language, omonkeypatch.setattr(cli, "_configured_cli_language", lambda: language)monkeypatch.setattr("storage.resource_access_service.resolve_resource_access_context",- lambda _caller: SimpleNamespace(is_instance_owner=owner),+ lambda _caller: SimpleNamespace(can_manage_instance=owner),)assert cli.cmd_data_skill_usage(SimpleNamespace(clear=clear, yes=yes)) == 1captured = capsys.readouterr()@@ -606,3 +610,20 @@ def test_skill_usage_help_follows_cli_language(monkeypatch, capsys, language):output = capsys.readouterr().outfor 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 ("Owner only" if language == "en" else "仅限实例所有者") not in output++[email protected]("role", ["owner", "member"])+def test_manager_cli_skill_diagnostics_use_real_storage(engine, monkeypatch, capsys, role):+ from vibe import cli+ from vibe.authorization import AuthorizationContext++ write(engine, load())+ monkeypatch.setattr(cli, "caller_resource_user_context", lambda _caller: AuthorizationContext(instance_role=role))+ assert cli.cmd_data_skill_usage(SimpleNamespace(clear=False, yes=False)) == 0+ assert json.loads(capsys.readouterr().out)["ok"] is True+ assert counts(engine) == (1, 1)+ assert cli.cmd_data_skill_usage(SimpleNamespace(clear=True, yes=True)) == 0+ assert json.loads(capsys.readouterr().out)["ok"] is True+ assert counts(engine) == (0, None)diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.pyindex 3de068c89..d55b584c8 100644--- a/tests/test_ui_project_access.py+++ b/tests/test_ui_project_access.py@@ -295,113 +295,41 @@ def test_active_org_member_can_use_every_project_runtime_surface(monkeypatch, tmassert hidden_action.status_code != 403 or hidden_action.get_json().get("code") != "remote_execution_disabled"-def test_member_project_mutations_are_bounded_by_the_acl_that_hides_them(monkeypatch, tmp_path) -> None:- """Instance role admits the route; the Project ACL still picks the Project.-- ``can_manage_projects`` is instance-wide Project administration, but every- one of these routes names a single Project, and the instance role says- nothing about which. The middleware used to skip member-tier routes- entirely, so a member who knew an id could PATCH or archive a Project that- ``GET /api/projects`` and ``GET /api/projects/<id>`` already hid from them.-- 404 on every hidden Project, matching the read path: a 403/404 split would- let a caller enumerate the restricted Projects they are excluded from.- """-+def test_member_operates_restricted_projects_by_id_and_folder(monkeypatch, tmp_path) -> None:+ """Member list/detail/reuse/mutation share current-instance scope."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config, ids = _setup_state(tmp_path)-- def _patch(client, project_id, headers, name):- return client.patch(- f"/api/projects/{project_id}",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=headers,- json={"display_name": name},+ client = _remote_client(config, role="member", email="[email protected]")+ headers = csrf_headers(client, REMOTE_ORIGIN)+ assert {row["id"] for row in _get(client, "/api/projects").get_json()["projects"]} == {+ ids["project_a"], ids["project_b"]+ }+ engine = create_sqlite_engine()+ with engine.connect() as conn:+ before = [project_access_service.get_project_policy(conn, ids[key]) for key in ("project_a", "project_b")]+ for key, folder in (("project_a", "project-a"), ("project_b", "project-b")):+ project_id = ids[key]+ assert _get(client, f"/api/projects/{project_id}").status_code == 200+ reused = client.post(+ "/api/projects", base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER,+ headers=headers, json={"folder_path": str(tmp_path / folder)},)-- def _archive(client, project_id, headers):- return client.delete(- f"/api/projects/{project_id}",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=headers,+ assert reused.status_code == 201+ assert reused.get_json()["id"] == project_id+ changed = client.patch(+ f"/api/projects/{project_id}", base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER,+ headers=headers, json={"display_name": "成员管理"},)-- # Bound to neither Project: the list is empty, and so is what they can touch.- excluded = _remote_client(config, role="member", email="[email protected]")- excluded_headers = csrf_headers(excluded, REMOTE_ORIGIN)- assert _get(excluded, "/api/projects").get_json()["projects"] == []- for project_id in (ids["project_a"], ids["project_b"]):- assert _get(excluded, f"/api/projects/{project_id}").status_code == 404- assert _patch(excluded, project_id, excluded_headers, "Stolen").status_code == 404- assert _archive(excluded, project_id, excluded_headers).status_code == 404-- # An explicit editor binding is below "member", and that is the point: the- # floor for these routes is the ACL's visibility floor, so the Projects the- # list shows are exactly the Projects that can be mutated.- included = _remote_client(config, role="member", email="[email protected]")- included_headers = csrf_headers(included, REMOTE_ORIGIN)- assert {row["id"] for row in _get(included, "/api/projects").get_json()["projects"]} == {- ids["project_a"]- }- renamed = _patch(included, ids["project_a"], included_headers, "Alice Renamed")- assert renamed.status_code == 200- assert renamed.get_json()["display_name"] == "Alice Renamed"- assert _patch(included, ids["project_b"], included_headers, "Stolen").status_code == 404- assert _archive(included, ids["project_b"], included_headers).status_code == 404- assert _archive(included, ids["project_a"], included_headers).status_code == 200---def test_member_cannot_reach_a_hidden_project_through_its_folder(monkeypatch, tmp_path) -> None:- """``POST /api/projects`` is create-or-reuse, so it is also a Project lookup.-- The middleware only sees routes that name a Project id, and this one names a- folder, so the whole visibility rule for it lives in the service. A member- excluded from the Project gets the same 404 the id-keyed routes answer with- -- not its payload, and not a revived copy of it.- """-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- config, ids = _setup_state(tmp_path)- project_b_dir = str((tmp_path / "project-b").resolve())-- # ``alice`` is bound to project_a only; project_b is restricted to a group- # she is not in, so it is hidden from her exactly as the list shows.- alice = _remote_client(config, role="member", email="[email protected]")- headers = csrf_headers(alice, REMOTE_ORIGIN)- assert {row["id"] for row in _get(alice, "/api/projects").get_json()["projects"]} == {- ids["project_a"]- }-- hidden = alice.post(- "/api/projects",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=headers,- json={"folder_path": project_b_dir, "display_name": "Stolen"},- )- assert hidden.status_code == 404- assert "project_b" not in json.dumps(hidden.get_json())-- owner = _remote_client(config, role="owner", email="[email protected]")- owner_view = {- row["id"]: row for row in _get(owner, "/api/projects").get_json()["projects"]- }- assert owner_view[ids["project_b"]]["display_name"] == "B"-- # Reuse still works for a folder the caller can see, so the refusal above is- # the ACL and not create-or-reuse breaking.- project_a_dir = str((tmp_path / "project-a").resolve())- visible = alice.post(- "/api/projects",- base_url=REMOTE_ORIGIN,- environ_base=REMOTE_PEER,- headers=headers,- json={"folder_path": project_a_dir, "display_name": "Ignored On Reuse"},- )- assert visible.status_code == 201- assert visible.get_json()["id"] == ids["project_a"]+ assert changed.status_code == 200+ assert changed.get_json()["display_name"] == "成员管理"+ with engine.connect() as conn:+ assert [project_access_service.get_project_policy(conn, ids[key]) for key in ("project_a", "project_b")] == before+ for key in ("project_a", "project_b"):+ assert client.delete(+ f"/api/projects/{ids[key]}", base_url=REMOTE_ORIGIN, environ_base=REMOTE_PEER,+ headers=headers,+ ).status_code == 200+ engine.dispose()def test_session_bootstrap_uses_effective_project_chat_role(monkeypatch, tmp_path) -> None:@@ -1263,7 +1191,7 @@ def test_show_page_payload_redacts_path_when_session_is_missing(monkeypatch) ->assert "path" not in payload[email protected]("role", ["viewer", "editor", "member"])[email protected]("role", ["viewer", "editor"])def test_retry_notice_update_stream_keeps_remote_session_acl(monkeypatch, tmp_path, role) -> None:import asynciodiff --git a/ui/src/components/RemoteAccess.test.tsx b/ui/src/components/RemoteAccess.test.tsxindex 650f0a0eb..0321e43de 100644--- a/ui/src/components/RemoteAccess.test.tsx+++ b/ui/src/components/RemoteAccess.test.tsx@@ -1,10 +1,12 @@/* @vitest-environment jsdom */import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cleanup, render, screen, waitFor } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { RemoteAccess } from './RemoteAccess';import type { RemoteAccessStatus } from '../context/ApiContext';+import { InstanceAuthorizationProvider } from '../context/InstanceAuthorizationProvider';+import { normalizeSessionInfo, OWNER_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';const api = vi.hoisted(() => ({connectWorkbenchEvents: vi.fn(() => () => undefined),@@ -67,8 +69,17 @@ const runningStatus = (overrides: Partial<RemoteAccessStatus> = {}): RemoteAcces...overrides,});-function renderPage() {- return render(<RemoteAccess />);+function renderPage(role: 'member' | 'owner' = 'owner') {+ const session = normalizeSessionInfo({+ remote: true, authenticated: true, authorization_state: 'current',+ instance_role: role, instance_kind: 'organization',+ capabilities: {+ ...OWNER_INSTANCE_CAPABILITIES,+ is_instance_owner: role === 'owner',+ can_manage_access_members: role === 'owner',+ },+ });+ return render(<InstanceAuthorizationProvider session={session}><RemoteAccess /></InstanceAuthorizationProvider>);}describe('RemoteAccess', () => {@@ -103,4 +114,49 @@ describe('RemoteAccess', () => {expect(screen.queryByText('remoteAccess.networkTechnicalDetails')).toBeNull();expect(screen.queryByText('remoteAccess.networkPath')).toBeNull();});+ it('PERMISSIONS-018 keeps Member transport usable while pairing is disabled', async () => {+ api.stopRemoteAccess.mockResolvedValue(runningStatus({ running: false }));+ api.startRemoteAccess.mockResolvedValue(runningStatus());+ api.optimizeRemoteAccessRoute.mockResolvedValue(runningStatus());+ renderPage('member');+ const repair = await screen.findByRole('button', { name: 'remoteAccess.repair' });+ expect((repair as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(repair);+ expect(screen.queryByLabelText('remoteAccess.pairingKey')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.optimizeRoute' }));+ await waitFor(() => expect(api.optimizeRemoteAccessRoute).toHaveBeenCalledOnce());+ fireEvent.click(screen.getByRole('button', { name: 'common.stop' }));+ await waitFor(() => expect(api.stopRemoteAccess).toHaveBeenCalledOnce());+ await waitFor(() => expect((screen.getByRole('button', { name: 'common.start' }) as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByRole('button', { name: 'common.start' }));+ await waitFor(() => expect(api.startRemoteAccess).toHaveBeenCalledOnce());+ expect(api.pairVibeCloudRemoteAccess).not.toHaveBeenCalled();+ });++ it('PERMISSIONS-018 explains unpaired Member access without a pair request', async () => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus({ paired: false, running: false }));+ renderPage('member');+ await screen.findByText('remoteAccess.ownerPairingRequired');+ const input = screen.getByLabelText('remoteAccess.pairingKey');+ expect((input as HTMLInputElement).disabled).toBe(true);+ fireEvent.change(input, { target: { value: 'synthetic-key' } });+ const pair = screen.getByRole('button', { name: 'remoteAccess.pair' });+ expect((pair as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(pair);+ expect(api.pairVibeCloudRemoteAccess).not.toHaveBeenCalled();+ });++ it.each([true, false])('PERMISSIONS-018 preserves Owner pairing (paired=%s)', async (paired) => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus({ paired, running: paired }));+ api.pairVibeCloudRemoteAccess.mockResolvedValue(runningStatus());+ renderPage('owner');+ if (paired) fireEvent.click(await screen.findByRole('button', { name: 'remoteAccess.repair' }));+ const input = await screen.findByLabelText('remoteAccess.pairingKey');+ fireEvent.change(input, { target: { value: 'synthetic-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.pair' }));+ await waitFor(() => expect(api.pairVibeCloudRemoteAccess).toHaveBeenCalledWith({+ backend_url: 'https://avibe.bot', pairing_key: 'synthetic-key', device_name: 'avibe',+ }));+ });+});diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsxindex fc73df93e..a55f581b0 100644--- a/ui/src/components/RemoteAccess.tsx+++ b/ui/src/components/RemoteAccess.tsx@@ -25,6 +25,7 @@ import {useApi,} from '../context/ApiContext';import { useToast } from '../context/ToastContext';+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';import { onPageReactivated } from '../lib/pageActivity';import { getTunnelQualityDisplayState, getTunnelRequestPathDisplayState } from '../lib/tunnelQuality';import { CompactField } from './settings/SettingsPrimitives';@@ -57,6 +58,8 @@ const formatEdgeLocation = (location: CloudflareEdgeLocation) => (export const RemoteAccess: React.FC = () => {const { t } = useTranslation();const api = useApi();+ const { capabilities } = useInstanceAuthorization();+ const canPair = capabilities.is_instance_owner;const { showToast } = useToast();const [loading, setLoading] = useState(true);const [pairing, setPairing] = useState(false);@@ -128,6 +131,7 @@ export const RemoteAccess: React.FC = () => {}, [settingsDirty, status?.settings]);const pair = async () => {+ if (!canPair) return;setPairing(true);setActionMessage(null);try {@@ -274,7 +278,7 @@ export const RemoteAccess: React.FC = () => {const publicUrl = status?.public_url;const paired = Boolean(status?.paired);const running = Boolean(status?.running);- const showPairingForm = !paired || reconfiguring;+ const showPairingForm = !paired || (canPair && reconfiguring);const connectorState = status?.pid_state === 'unknown'? t('remoteAccess.stateNeedsAttention'): running@@ -737,6 +741,7 @@ export const RemoteAccess: React.FC = () => {value={pairingKey}onChange={(event) => setPairingKey(event.target.value)}placeholder="vrp_xxxxxxxxxxxxxxxxx"+ disabled={!canPair}/><div className="flex shrink-0 flex-wrap gap-2"><Button@@ -744,7 +749,7 @@ export const RemoteAccess: React.FC = () => {variant="default"size="xs"className="font-semibold"- disabled={pairing || !pairingKey.trim()}+ disabled={!canPair || pairing || !pairingKey.trim()}onClick={pair}><Link2 className="size-3.5" />@@ -765,7 +770,7 @@ export const RemoteAccess: React.FC = () => {)}</div></div>- <span className="block text-[10px] text-muted">{t('remoteAccess.pairingKeyHelp')}</span>+ <span className="block text-[10px] text-muted">{canPair ? t('remoteAccess.pairingKeyHelp') : t('remoteAccess.ownerPairingRequired')}</span></div>) : (<div className="flex flex-col gap-3 px-5 py-4 md:flex-row md:items-center md:justify-between">@@ -805,6 +810,8 @@ export const RemoteAccess: React.FC = () => {type="button"variant="secondary"size="xs"+ disabled={!canPair}+ title={!canPair ? t('remoteAccess.ownerPairingRequired') : undefined}onClick={() => setReconfiguring(true)}>{t('remoteAccess.repair')}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 2e418baea..52bafcdd1 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1902,6 +1902,7 @@}},"remoteAccess": {+ "ownerPairingRequired": "Pairing changes the instance identity and requires the instance Owner.","badge": "Avibe Cloud provider","title": "Remote Access","subtitle": "Open this local Web UI from another device through a private avibe.bot URL. Your data and agents still run on this machine.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 5f4926048..1a4e14103 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1902,6 +1902,7 @@}},"remoteAccess": {+ "ownerPairingRequired": "配对会更改实例身份,需要实例所有者权限。","badge": "Avibe Cloud Provider","title": "远程访问","subtitle": "通过私有 avibe.bot 地址,从另一台设备打开这个本机 Web UI。你的数据和 Agent 仍然运行在这台机器上。",diff --git a/vibe/authorization.py b/vibe/authorization.pyindex aad344ad7..58b0d8435 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -82,6 +82,7 @@ _PRIVILEGED_RUNTIME_WORKBENCH_EVENTS = frozenset(DEFINITIONS_UPDATED_EVENT,RUNS_UPDATED_EVENT,VAULTS_UPDATED_EVENT,+ "remote_access.quality.changed",})@@ -163,9 +164,10 @@ class AuthorizationContext:def can_use_resource(self, resource_kind: str) -> bool:"""Return whether the Instance role may use this resource kind.- Effective Resource ACL is a separate, mandatory check performed by the- resource service. Unknown kinds fail closed so adding a resource type- never makes it editor-visible by accident.+ Effective resource access is checked by the resource service: managers+ operate instance-wide, while lower roles retain their resource ACLs.+ Unknown kinds fail closed so adding a resource type never makes it+ editor-visible by accident."""minimum_role = _RESOURCE_USE_MINIMUM_ROLES.get(resource_kind)diff --git a/vibe/cli.py b/vibe/cli.pyindex c0ac94a1e..24d89b301 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -7303,7 +7303,7 @@ def _print_data_retention_human(payload: dict, language: str) -> None:def cmd_data_skill_usage(args):- """Instance-owner maintenance; statistics remain off the user-facing UI."""+ """Instance-management diagnostics; statistics remain off the user-facing UI."""try:from storage.resource_access_service import resolve_resource_access_contextfrom storage import skill_observability@@ -7312,7 +7312,7 @@ def cmd_data_skill_usage(args):language = _configured_cli_language()caller = caller_resource_user_context(caller_context_from_env())- if not resolve_resource_access_context(caller).is_instance_owner:+ if not resolve_resource_access_context(caller).can_manage_instance:raise TaskCliError(i18n_t("data.skillUsage.ownerRequired", language), code="forbidden")if args.clear and not args.yes:raise TaskCliError(i18n_t("data.skillUsage.confirmationRequired", language), code="confirmation_required")diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 3b506711f..e19c12863 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1482,10 +1482,10 @@"helpCommand": "Inspect Avibe data, and run explicit trace-retention maintenance","helpDescription": "Inspect local Avibe SQLite state with guarded read-only SQL, or run explicit maintenance: `query` is read-only, while `retention --run` deletes old internal trace events and may compact the database.","skillUsage": {- "ownerRequired": "Instance Owner access is required.",+ "ownerRequired": "Instance Member or Owner access is required.","confirmationRequired": "Clearing Skill statistics requires --yes.","clearRequired": "--yes requires --clear.",- "helpCommand": "Inspect or clear local Skill statistics (Instance Owner only)",+ "helpCommand": "Inspect or clear local Skill statistics (Instance Member or Owner)","helpClear": "Clear Skill events and daily statistics.","helpYes": "Confirm clearing Skill statistics."},diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex f33f79578..511d74387 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1482,10 +1482,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/ui_server.py b/vibe/ui_server.pyindex c6d86f8af..cfd8ba29b 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2456,8 +2456,8 @@ def _request_authorization_context(context: Any = None):return resolved-def _has_runtime_owner_access(context: Any) -> bool:- return bool(context is not None and context.is_instance_owner)+def _has_runtime_management_access(context: Any) -> bool:+ return bool(context is not None and context.can_manage_instance)def _access_administration_forbidden(context: Any = None):@@ -2495,7 +2495,7 @@ def _runtime_record_agent_refs(record: Any) -> tuple[str | None, str | None]:def _runtime_record_visible(context: Any, record: Any, *, connection: Any | None = None) -> bool:"""Return whether a Project-bound Agent runtime record is authorized.- Owners see every record. Everyone else must pass both the Project ACL for+ Instance managers see every record. Other roles must pass both the Project ACL forthe bound session (when one exists) and the Agent ACL for the selectedAgent (when one exists). Harness definitions and runs intentionally do notuse this helper because Harness has no additional resource ACL in this MVP.@@ -2503,7 +2503,7 @@ def _runtime_record_visible(context: Any, record: Any, *, connection: Any | Noneif context is None:return False- if _has_runtime_owner_access(context):+ if _has_runtime_management_access(context):return Truesession_id = _runtime_record_session_id(record)agent_id, agent_name = _runtime_record_agent_refs(record)@@ -2561,7 +2561,7 @@ def _running_agent_counts(agents: list[Any] | tuple[Any, ...] | None) -> dict[stdef _authorized_graph_payload(context: Any, payload: dict[str, Any]) -> dict[str, Any]:- if _has_runtime_owner_access(context):+ if _has_runtime_management_access(context):return payloadfrom core.services.agent_graph import _counts as graph_counts@@ -2891,11 +2891,11 @@ def _project_access_resource(path: str) -> tuple[str, str] | None:@app.before_requestdef enforce_project_role_capabilities():- """Narrow remote non-owner Project/session routes through applied Project ACLs."""+ """Narrow non-manager Project/session routes through applied Project ACLs."""if _remote_auth_exempt_path():return Nonecontext = getattr(g, "authorization_context", None)- if context is None or _has_runtime_owner_access(context):+ if context is None or _has_runtime_management_access(context):return Nonefrom storage import project_access_service@@ -2914,18 +2914,8 @@ def enforce_project_role_capabilities():)if minimum_instance_role not in {"viewer", "editor", "member"}:return None- # A ``member`` route is instance-wide Project administration, but it still- # names one Project, and the instance role does not say *which* Projects the- # caller may touch. Ceiling this at "editor" is what let a member mutate a- # restricted Project by id that ``list_projects`` hides from them.- #- # The floor for those routes is the Project ACL's *visibility* floor, not- # "member": a member holding an explicit editor binding on a restricted- # Project has an effective Project role of editor, so demanding a "member"- # Project role would refuse the very Projects the list shows them. The- # instance-role half of the authorization is already enforced by the HTTP- # policy before this hook runs; this half only asks whether the Project is- # theirs to see.+ # Lower roles retain Project ACL floors. Member management was already+ # admitted above; this fallback keeps route and resource policy distinct.required_project_role = "viewer" if minimum_instance_role == "member" else minimum_instance_roleresource = _project_access_resource(request.path)if resource is None:@@ -3626,7 +3616,7 @@ def _websocket_context_authorized() -> bool:if not context.has_role(minimum_role):return False- if project_session_id is None or _has_runtime_owner_access(context):+ if project_session_id is None or _has_runtime_management_access(context):return Trueif minimum_role == "viewer":return context.has_role("viewer")@@ -3638,7 +3628,7 @@ def _project_session_access_allowed(context: Any, session_id: str, minimum_role:if context is None:return False- if _has_runtime_owner_access(context):+ if _has_runtime_management_access(context):return Trueif not context.has_role(minimum_role):return False@@ -5146,7 +5136,7 @@ def vibe_agent_onboarding():# instance-wide one-way Agent migration, not member management. The store# repeats the check in ``_require_agent_onboarding_access`` so non-HTTP# callers are gated too; both layers ask the same question.- if not _has_runtime_owner_access(user_context):+ if user_context is None or not user_context.is_instance_owner:return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403if request.method == "POST":return jsonify(api.onboard_vibe_agents(user_context=user_context))@@ -5174,7 +5164,7 @@ async def running_agents_get():body = result.get("body") or {}context = _request_authorization_context()agents = _filter_runtime_records(context, body.get("agents") or [])- counts = body.get("counts") if _has_runtime_owner_access(context) else _running_agent_counts(agents)+ counts = body.get("counts") if _has_runtime_management_access(context) else _running_agent_counts(agents)return jsonify({**body, "agents": agents, "counts": counts})@@ -5830,7 +5820,7 @@ def _is_remote_show_page_request() -> bool:def _show_page_payload_for_request(payload: dict, context: Any = None) -> dict:context = _request_authorization_context(context)- if context is None or _has_runtime_owner_access(context):+ if context is None or _has_runtime_management_access(context):return payloadfrom storage import project_access_service@@ -5863,7 +5853,7 @@ def _show_page_payload_for_connection(payload: dict, context: Any, conn: Any) ->def _show_page_payloads_for_request(payloads: list[dict], context: Any = None) -> list[dict]:context = _request_authorization_context(context)- if context is None or _has_runtime_owner_access(context):+ if context is None or _has_runtime_management_access(context):return payloadsengine = _projects_engine()with engine.connect() as conn:@@ -8278,10 +8268,10 @@ def _projects_engine():def _accessible_project_scope_ids_for_context(conn, context) -> list[str] | None:- """Return a principal's readable Project scopes; owners need no SQL filter."""+ """Return a principal's readable Project scopes; managers need no SQL filter."""from storage import project_access_service- if context is None or _has_runtime_owner_access(context):+ if context is None or _has_runtime_management_access(context):return Nonereturn sorted(project_access_service.project_scope_id(project_id)@@ -10677,7 +10667,7 @@ def _request_can_read_media_row(conn, token: str, row: dict[str, Any]) -> bool:# Project/session role below must not stack on top, or an admitted# Instance Viewer who is outside the page's Project loses the screenshot.return True- if context is None or _has_runtime_owner_access(context):+ if context is None or _has_runtime_management_access(context):return Truesession_ids = media_service.referenced_session_ids(conn, token)if session_ids:@@ -11918,7 +11908,7 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)# ACL. Project ACL gates page creation/editing, while §3.2 instance# admission gates Viewer reads and live event delivery.return context.has_role("viewer")- if _has_runtime_owner_access(context):+ if _has_runtime_management_access(context):return Trueif event_type in {"authorization.changed", "workbench.events.bridge.status"}:return True@@ -12164,7 +12154,7 @@ async def workbench_events():if (event_type == "authorization.changed"and authorization_context is not None- and not _has_runtime_owner_access(authorization_context)+ and not _has_runtime_management_access(authorization_context)):payload = json.dumps({