fix(scope): replace the owner/manager/member role with one administration right
Who administers an agent is decided where the signed claim is made (in Hermes Cloud: a personal agent's owner, and the org's owners and admins for an agent owned by the org or a group), so the scope carries only the result. A personal agent its owner shared runs a teammate's turn as that teammate, unable to administer it.
This commit is contained in:
@@ -41,12 +41,13 @@ def _same_home(a: str | Path, b: str | Path) -> bool:
|
||||
|
||||
|
||||
def _identity(scope: Scope) -> tuple[Any, ...]:
|
||||
return scope.tenant, scope.agent, scope.actor, scope.owner, scope.role
|
||||
return scope.tenant, scope.agent, scope.actor, scope.owner, scope.can_administer
|
||||
|
||||
|
||||
def _refuse_inside_hosted(what: str, *, unless: Scope | None = None) -> None:
|
||||
"""Refuse inside a hosted scope, unless *unless* is the same tenant, agent, actor, owner and
|
||||
role (a turn of it): a hosted activity cannot change whom it acts for or what it may do."""
|
||||
administration right (a turn of it): a hosted activity cannot change whom it acts for or what
|
||||
it may do."""
|
||||
current = current_scope()
|
||||
if current is None or current.is_local:
|
||||
return
|
||||
@@ -101,7 +102,8 @@ def bind_state(
|
||||
on its own: removing the earlier change it was copied from cannot take the piece away. Every
|
||||
piece is computed before anything is installed, so a failure leaves nothing bound.
|
||||
|
||||
Inside a hosted scope, only a bind of the same tenant, agent, actor, owner and role is
|
||||
Inside a hosted scope, only a bind of the same tenant, agent, actor, owner and administration
|
||||
right is
|
||||
allowed; anything else raises :class:`~hermes_scope.ScopeSwitchRefused`."""
|
||||
_refuse_inside_hosted("a bind of another scope", unless=scope)
|
||||
home = scope.home()
|
||||
@@ -176,7 +178,8 @@ def claim_fence(row: Mapping[str, Any]) -> Fence:
|
||||
@contextmanager
|
||||
def bind_turn(session_id: str, turn_id: str, fence: Fence) -> Iterator[Scope | None]:
|
||||
"""Mark the body as one turn of the bound scope, claimed under *fence*: the scope becomes a
|
||||
:class:`~hermes_scope.TurnScope` with the same tenant, agent, actor, owner and role; nothing
|
||||
:class:`~hermes_scope.TurnScope` with the same tenant, agent, actor, owner and administration
|
||||
right; nothing
|
||||
else changes. With no scope bound (a single-profile gateway keeps its ambient scope) this
|
||||
binds nothing."""
|
||||
current = current_scope()
|
||||
|
||||
@@ -9,9 +9,10 @@ Every activity a gateway runs for a profile binds a :class:`Scope`: a turn, cach
|
||||
cron tick, a notifier, a deferred callback. A turn binds a :class:`TurnScope`, which adds the
|
||||
session, the turn and the turn's :class:`Fence`. The actor is always present: the person a turn
|
||||
serves, or a :class:`System` reason for work no person started. Every scope also names the agent's
|
||||
owner (one :class:`Principal` for a personal agent, one :class:`Group` for a shared one) and the
|
||||
role the activity holds on it. On a local install the tenant is :data:`LOCAL_TENANT`, the agent is
|
||||
the profile home path, and the actor, owner and role are :data:`LOCAL_OWNER` / ``"owner"``.
|
||||
owner (one :class:`Principal` for a personal agent, one :class:`Group` for a shared one) and
|
||||
whether the activity may administer the agent. On a local install the tenant is
|
||||
:data:`LOCAL_TENANT`, the agent is the profile home path, the actor and owner are
|
||||
:data:`LOCAL_OWNER`, and it may administer.
|
||||
|
||||
The scope and the profile state readers use (the ``HERMES_HOME`` override behind
|
||||
``get_hermes_home()``, the secret mapping behind ``get_secret()``, the terminal policy) are ONE
|
||||
@@ -28,7 +29,7 @@ from __future__ import annotations
|
||||
import weakref
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass, field, replace
|
||||
from typing import Any, Callable, Literal, Mapping, NamedTuple
|
||||
from typing import Any, Callable, Mapping, NamedTuple
|
||||
|
||||
LOCAL_TENANT = "local"
|
||||
|
||||
@@ -57,8 +58,8 @@ class System:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Group:
|
||||
"""A set of a tenant's principals that owns shared agents. Membership and each member's role
|
||||
live with the identity provider, not here: a scope carries only the role it was granted."""
|
||||
"""A set of a tenant's principals that owns shared agents. Membership lives with the identity
|
||||
provider, not here: a scope carries only what the signed claim granted."""
|
||||
|
||||
id: str
|
||||
|
||||
@@ -70,12 +71,6 @@ class Group:
|
||||
Actor = Principal | System
|
||||
Owner = Principal | Group
|
||||
|
||||
# The role an activity holds on its agent. A personal agent's only user is its owner ("owner"); a
|
||||
# group agent's users are its managers and members. Owners and managers administer the agent (its
|
||||
# keys, settings, plugins, cron, deletion); a member's turns still update its memory and skills.
|
||||
Role = Literal["owner", "manager", "member"]
|
||||
ROLES: frozenset[str] = frozenset({"owner", "manager", "member"})
|
||||
|
||||
# The single user of a local install. Local installs have one person, so every local activity
|
||||
# acts for them; a shared deployment resolves the actor from the signed inbound frame instead.
|
||||
LOCAL_OWNER = Principal("owner")
|
||||
@@ -102,22 +97,21 @@ class Fence:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Scope:
|
||||
"""Who an activity serves: ``(tenant, agent, actor)``, plus the agent's owner and the role
|
||||
the activity holds on it.
|
||||
"""Who an activity serves: ``(tenant, agent, actor)``, plus the agent's owner and whether the
|
||||
activity may administer the agent (its keys, settings, plugins, cron, deletion). Any turn,
|
||||
administering or not, still updates the agent's memory and skills.
|
||||
|
||||
``owner`` and ``role`` are keyword-only. A local scope may omit them: the owner is the local
|
||||
person (the actor when it is a person, else :data:`LOCAL_OWNER`) and the role is ``"owner"``.
|
||||
A hosted scope must name both, as its identity verifier read them from a signed claim.
|
||||
|
||||
A personal agent (a :class:`Principal` owner) is used only by that principal, so its role is
|
||||
``"owner"`` and a person acting on it is its owner. A group agent's role is ``"manager"`` or
|
||||
``"member"``."""
|
||||
``owner`` and ``can_administer`` are keyword-only. A local scope may omit them: the owner is
|
||||
the local person (the actor when it is a person, else :data:`LOCAL_OWNER`) and it may
|
||||
administer. A hosted scope must name both, as its identity verifier read them from a signed
|
||||
claim; who administers is decided there (in Hermes Cloud: a personal agent's owner, and the
|
||||
org's owners and admins for an agent owned by the org or a group), never here."""
|
||||
|
||||
tenant: str
|
||||
agent: str
|
||||
actor: Actor
|
||||
owner: Owner = field(default=None, kw_only=True) # type: ignore[assignment]
|
||||
role: Role = field(default=None, kw_only=True) # type: ignore[assignment]
|
||||
can_administer: bool = field(default=None, kw_only=True) # type: ignore[assignment]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.tenant, str) or not self.tenant:
|
||||
@@ -126,35 +120,22 @@ class Scope:
|
||||
raise ValueError("Scope.agent must be a non-empty string")
|
||||
if not isinstance(self.actor, (Principal, System)):
|
||||
raise TypeError("Scope.actor must be a Principal or a System")
|
||||
if self.owner is None or self.role is None:
|
||||
if self.owner is None or self.can_administer is None:
|
||||
if not self.is_local:
|
||||
raise ValueError("a hosted Scope must name its owner and role")
|
||||
raise ValueError("a hosted Scope must name its owner and whether it may administer")
|
||||
if self.owner is None:
|
||||
object.__setattr__(self, "owner", self.actor if isinstance(self.actor, Principal) else LOCAL_OWNER)
|
||||
if self.role is None:
|
||||
object.__setattr__(self, "role", "owner")
|
||||
if self.can_administer is None:
|
||||
object.__setattr__(self, "can_administer", True)
|
||||
if not isinstance(self.owner, (Principal, Group)):
|
||||
raise TypeError("Scope.owner must be a Principal or a Group")
|
||||
if self.role not in ROLES:
|
||||
raise ValueError(f"Scope.role must be one of {sorted(ROLES)}")
|
||||
if isinstance(self.owner, Principal):
|
||||
if self.role != "owner":
|
||||
raise ValueError("a personal agent's only role is 'owner'")
|
||||
if isinstance(self.actor, Principal) and self.actor != self.owner:
|
||||
raise ValueError("a personal agent is used only by its owner")
|
||||
elif self.role == "owner":
|
||||
raise ValueError("a group agent's roles are 'manager' and 'member'")
|
||||
if type(self.can_administer) is not bool:
|
||||
raise TypeError("Scope.can_administer must be a bool")
|
||||
|
||||
@property
|
||||
def is_local(self) -> bool:
|
||||
return self.tenant == LOCAL_TENANT
|
||||
|
||||
@property
|
||||
def can_administer(self) -> bool:
|
||||
"""Whether this activity may change the agent itself (keys, settings, plugins, cron,
|
||||
deletion): a personal agent's owner or a group agent's manager."""
|
||||
return self.role in ("owner", "manager")
|
||||
|
||||
def home(self) -> str | None:
|
||||
"""The profile home this scope's state lives in: the agent path on a local install.
|
||||
|
||||
@@ -165,7 +146,7 @@ class Scope:
|
||||
def for_turn(self, session: str, turn: str, fence: Fence) -> TurnScope:
|
||||
"""This scope as one turn of *session*, run under *fence*."""
|
||||
return TurnScope(self.tenant, self.agent, self.actor, session, turn, fence,
|
||||
owner=self.owner, role=self.role)
|
||||
owner=self.owner, can_administer=self.can_administer)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -46,7 +46,7 @@ F1 = Fence(1, 1)
|
||||
|
||||
def _hosted(tenant: str = "acme", agent: str = "agent-7", who: str = "u1") -> Scope:
|
||||
"""A hosted scope on a personal agent: the person acting is its owner."""
|
||||
return Scope(tenant, agent, Principal(who), owner=Principal(who), role="owner")
|
||||
return Scope(tenant, agent, Principal(who), owner=Principal(who), can_administer=True)
|
||||
|
||||
|
||||
def _profile(root: Path, name: str, backend: str) -> Path:
|
||||
@@ -503,46 +503,43 @@ def test_a_managed_reference_in_the_terminal_policy_resolves_against_the_target_
|
||||
managed_scope.invalidate_managed_cache()
|
||||
|
||||
|
||||
# --- owner, role and fence ---
|
||||
# --- owner, administration and fence ---
|
||||
|
||||
def test_local_scope_defaults_owner_and_role_to_the_local_person():
|
||||
def test_local_scope_defaults_owner_and_administration_to_the_local_person():
|
||||
assert Scope("local", "/h", LOCAL_OWNER).owner == LOCAL_OWNER
|
||||
assert Scope("local", "/h", Principal("alice")).owner == Principal("alice")
|
||||
boot = Scope("local", "/h", System("boot"))
|
||||
assert (boot.owner, boot.role, boot.can_administer) == (LOCAL_OWNER, "owner", True)
|
||||
assert (boot.owner, boot.can_administer) == (LOCAL_OWNER, True)
|
||||
|
||||
|
||||
def test_hosted_scope_must_name_owner_and_role():
|
||||
with pytest.raises(ValueError, match="owner and role"):
|
||||
def test_hosted_scope_must_name_owner_and_administration():
|
||||
with pytest.raises(ValueError, match="owner and whether it may administer"):
|
||||
Scope("acme", "agent-7", Principal("u1"))
|
||||
with pytest.raises(ValueError, match="owner and role"):
|
||||
with pytest.raises(ValueError, match="owner and whether it may administer"):
|
||||
Scope("acme", "agent-7", Principal("u1"), owner=Principal("u1"))
|
||||
with pytest.raises(ValueError, match="owner and whether it may administer"):
|
||||
Scope("acme", "agent-7", Principal("u1"), can_administer=True)
|
||||
|
||||
|
||||
def test_personal_agent_is_used_only_by_its_owner():
|
||||
with pytest.raises(ValueError, match="only by its owner"):
|
||||
Scope("acme", "x", Principal("bob"), owner=Principal("alice"), role="owner")
|
||||
with pytest.raises(ValueError, match="only role is 'owner'"):
|
||||
Scope("acme", "x", Principal("alice"), owner=Principal("alice"), role="member")
|
||||
# Work no person started (a cron tick) still runs on the owner's agent.
|
||||
assert Scope("acme", "x", System("cron"), owner=Principal("alice"), role="owner").can_administer
|
||||
|
||||
|
||||
def test_group_agent_roles_decide_administration():
|
||||
team = Group("support")
|
||||
manager = Scope("acme", "bot", Principal("m"), owner=team, role="manager")
|
||||
member = Scope("acme", "bot", Principal("u"), owner=team, role="member")
|
||||
assert manager.can_administer and not member.can_administer
|
||||
with pytest.raises(ValueError, match="'manager' and 'member'"):
|
||||
Scope("acme", "bot", Principal("m"), owner=team, role="owner")
|
||||
with pytest.raises(ValueError, match="role must be one of"):
|
||||
Scope("acme", "bot", Principal("m"), owner=team, role="admin") # type: ignore[arg-type]
|
||||
def test_scope_values_are_checked():
|
||||
with pytest.raises(TypeError, match="can_administer must be a bool"):
|
||||
Scope("acme", "bot", Principal("m"), owner=Group("g"), can_administer=1) # type: ignore[arg-type]
|
||||
with pytest.raises(TypeError, match="owner must be"):
|
||||
Scope("acme", "bot", Principal("m"), owner="support", role="member") # type: ignore[arg-type]
|
||||
Scope("acme", "bot", Principal("m"), owner="support", can_administer=False) # type: ignore[arg-type]
|
||||
with pytest.raises(ValueError):
|
||||
Group("")
|
||||
|
||||
|
||||
def test_a_shared_personal_agent_takes_a_teammate_who_cannot_administer_it():
|
||||
"""A personal agent its owner shared: the teammate's turn runs on it, as the teammate, and
|
||||
may not change the agent; the owner's own turn may."""
|
||||
shared = Scope("acme", "x", Principal("bob"), owner=Principal("alice"), can_administer=False)
|
||||
assert (shared.actor, shared.owner, shared.can_administer) == (Principal("bob"), Principal("alice"), False)
|
||||
assert Scope("acme", "x", Principal("alice"), owner=Principal("alice"), can_administer=True).can_administer
|
||||
# Work no person started (a cron tick) still runs on the owner's agent.
|
||||
assert Scope("acme", "x", System("cron"), owner=Principal("alice"), can_administer=True).can_administer
|
||||
|
||||
|
||||
def test_fence_is_two_positive_ints():
|
||||
for bad in ((0, 1), (1, 0), (True, 1), ("1", 1), (1, 1.0)):
|
||||
with pytest.raises(ValueError):
|
||||
@@ -551,15 +548,14 @@ def test_fence_is_two_positive_ints():
|
||||
TurnScope("local", "/h", LOCAL_OWNER, "s1", "t1", (1, 1)) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_a_turn_keeps_owner_and_role_and_carries_its_fence(two_profiles):
|
||||
def test_a_turn_keeps_owner_and_administration_and_carries_its_fence(two_profiles):
|
||||
a, _b = two_profiles
|
||||
member = Scope("acme", "bot", Principal("u"), owner=Group("support"), role="member")
|
||||
member = Scope("acme", "bot", Principal("u"), owner=Group("support"), can_administer=False)
|
||||
with bind_state(member):
|
||||
with bind_turn("s1", "t1", Fence(4, 9)) as turn:
|
||||
assert (turn.owner, turn.role, turn.fence) == (Group("support"), "member", Fence(4, 9))
|
||||
assert not turn.can_administer
|
||||
assert (turn.owner, turn.can_administer, turn.fence) == (Group("support"), False, Fence(4, 9))
|
||||
with bind_profile_scope(a), bind_turn("s1", "t1", Fence(2, 3)) as turn:
|
||||
assert (turn.owner, turn.role, turn.fence) == (LOCAL_OWNER, "owner", Fence(2, 3))
|
||||
assert (turn.owner, turn.can_administer, turn.fence) == (LOCAL_OWNER, True, Fence(2, 3))
|
||||
# A turn re-marked inside a turn (a nested drain) carries the newer claim's fence.
|
||||
with bind_turn("s1", "t2", Fence(2, 4)) as inner:
|
||||
assert (inner.turn, inner.fence) == ("t2", Fence(2, 4))
|
||||
@@ -568,12 +564,12 @@ def test_a_turn_keeps_owner_and_role_and_carries_its_fence(two_profiles):
|
||||
|
||||
@pytest.mark.parametrize("change", [
|
||||
dict(actor=Principal("other")),
|
||||
dict(role="manager"),
|
||||
dict(can_administer=True),
|
||||
dict(owner=Group("other-team")),
|
||||
])
|
||||
def test_hosted_scope_refuses_a_bind_that_changes_who_it_acts_for(change):
|
||||
from dataclasses import replace
|
||||
member = Scope("acme", "bot", Principal("u"), owner=Group("support"), role="member")
|
||||
member = Scope("acme", "bot", Principal("u"), owner=Group("support"), can_administer=False)
|
||||
with bind_state(member):
|
||||
with pytest.raises(ScopeSwitchRefused):
|
||||
bind_state(replace(member, **change))
|
||||
|
||||
@@ -42,5 +42,5 @@ async def test_each_claimed_turn_binds_its_admission_fence(monkeypatch):
|
||||
assert isinstance(scope, TurnScope), f'turn {text} ran without a TurnScope: {scope!r}'
|
||||
assert (scope.session, scope.turn) == (owner, rows[text]['admission_id'])
|
||||
assert scope.fence == Fence(authority.epoch, rows[text]['generation'])
|
||||
assert (scope.owner, scope.role) == (LOCAL_OWNER, 'owner')
|
||||
assert (scope.owner, scope.can_administer) == (LOCAL_OWNER, True)
|
||||
assert seen['B'].fence.generation == seen['A'].fence.generation + 1
|
||||
|
||||
@@ -122,16 +122,17 @@ via `copy_context()` and unwind deterministically — nothing is written to
|
||||
|
||||
The scope, the home override, the secret scope and the terminal policy are one
|
||||
immutable value, `hermes_scope.ScopeState`, in a single contextvar. The scope is
|
||||
`hermes_scope.Scope(tenant, agent, actor, owner=, role=)`:
|
||||
`hermes_scope.Scope(tenant, agent, actor, owner=, can_administer=)`:
|
||||
|
||||
- `actor` is `Principal(id)` (a person) or `System(reason)` (cron, kanban,
|
||||
housekeeping).
|
||||
- `owner` is the agent's one owner: a `Principal` for a personal agent, used only
|
||||
by that person, or a `Group` for a shared one.
|
||||
- `role` is what the activity may do on the agent: `owner` (personal agents),
|
||||
`manager` or `member` (group agents). `Scope.can_administer` is true for owners
|
||||
and managers. A hosted scope must name both; a local scope defaults to the local
|
||||
person as owner with role `owner`.
|
||||
- `owner` is the agent's one owner: a `Principal` for a personal agent or a
|
||||
`Group` for a shared one. Other people may use a personal agent when its owner
|
||||
shares it.
|
||||
- `can_administer` says whether the activity may change the agent itself (keys,
|
||||
settings, plugins, cron, deletion). Every turn still updates the agent's memory
|
||||
and skills. A hosted scope must name both, from the signed claim; a local scope
|
||||
defaults to the local person as owner, administering.
|
||||
- A `TurnScope` adds `session`, `turn` and `fence`: the `Fence(epoch, generation)`
|
||||
the turn's admission was claimed under (`agent.runtime_scope.claim_fence(row)`).
|
||||
|
||||
@@ -146,7 +147,8 @@ state:
|
||||
across calls (the TUI turn, the managed worker) or deliberately binds less.
|
||||
- `bind_turn(session_id, turn_id, fence)` marks a turn inside a bound scope.
|
||||
|
||||
Inside a hosted scope, a bind must keep the tenant, agent, actor, owner and role;
|
||||
Inside a hosted scope, a bind must keep the tenant, agent, actor, owner and
|
||||
administration right;
|
||||
anything else raises `ScopeSwitchRefused`.
|
||||
|
||||
A reset removes its own change and replays the later ones, except those made
|
||||
|
||||
Reference in New Issue
Block a user