Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): agent memory reviews and skill learning run on the agent's own seat
rubenluetke10-beepa53097ffb64f
diff --git a/docs/agent-society/self-learning.md b/docs/agent-society/self-learning.mdindex aa225d2569..d128811234 100644--- a/docs/agent-society/self-learning.md+++ b/docs/agent-society/self-learning.md@@ -7,6 +7,13 @@> agents learn through their `USER.md`/`MEMORY.md` notebooks and the turn> review in `jarvis/society/review.py`. Jarvis' own learning is> `docs/jarvis-learning.md`.+>+> **Seat rule (2026-09-30):** an agent's turn review and skill learning run+> on exactly that agent's seat — the provider, model and auth mode its chat+> uses (`jarvis/society/seat_brain.py`). No other provider, subscription or+> key is asked. A review whose seat keeps failing gets its first attempt plus+> three spaced retries and is then dropped (status `dropped`) with one log+> line.Tier: **T3 capability**. Jarvis and every Society agent use the same portablelearning loop, with separate ownership, files, review locks and provider scopes.diff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.pyindex 4b4d064e0d..07492f1f85 100644--- a/jarvis/brain/resolver.py+++ b/jarvis/brain/resolver.py@@ -817,6 +817,8 @@ def resolve_browser_brain(CLI aliases are read from the chat catalog; capabilities are probed on theconstructor. Browser inference never changes the voice provider/cache.+ An agent's background memory work resolves its seat here too+ (``jarvis/society/seat_brain.py``)."""import inspect@@ -840,7 +842,10 @@ def resolve_browser_brain(kwargs["prefer_subscription"] = Trueif "subscription_text_only" in parameters:kwargs["subscription_text_only"] = True- cfg = config.brain.providers.get(name)+ # A bare config (a headless runtime, a test) has no provider table; the+ # plugin then resolves its endpoint itself.+ providers = getattr(getattr(config, "brain", None), "providers", None) or {}+ cfg = providers.get(name)if cfg and cfg.base_url and "base_url" in parameters:kwargs["base_url"] = cfg.base_urlreturn registry.instantiate(name, **kwargs)diff --git a/jarvis/skills/creator_service.py b/jarvis/skills/creator_service.pyindex c5767a97bd..13c7f8210f 100644--- a/jarvis/skills/creator_service.py+++ b/jarvis/skills/creator_service.py@@ -552,6 +552,7 @@ class SkillCreatorService:config: Any | None = None,user_skills_root: Path | None = None,context: AuthoringContext | None = None,+ seat_only: bool = False,) -> None:self._brain = brainself._registry = registry@@ -559,6 +560,12 @@ class SkillCreatorService:self._config = configself._user_skills_root = user_skills_rootself._context = context+ #: The injected ``brain`` is an agent's own seat and the ONLY rung: no+ #: operation pin, no active provider, no resolver ladder. A Society+ #: agent's skill is authored on the seat it chats on or not at all+ #: (``jarvis/society/seat_brain.py``). Every other caller keeps the+ #: ladder below.+ self._seat_only = seat_onlyasync def draft(self, inp: SkillCreatorInput) -> SkillCreatorResult:return await self._draft_or_refine(inp)@@ -738,6 +745,10 @@ class SkillCreatorService:return Truebm = self._brain+ if self._seat_only:+ if _fresh(bm):+ yield bm, "seat"+ return# A caller that pinned a model for this operation (a GPT-Live call pins# its thinking model) outranks the chat brain's active model: without# this, a skill drafted from a cheap voice session ran on the chatdiff --git a/jarvis/society/conversation.py b/jarvis/society/conversation.pyindex 4ce8534617..f8d237f9a6 100644--- a/jarvis/society/conversation.py+++ b/jarvis/society/conversation.py@@ -181,6 +181,15 @@ class ConversationArchive:"UPDATE reviews SET status='done' WHERE session=? AND turn_id=?", (session, turn_id))+ def drop_review(self, session: str, turn_id: str) -> None:+ """Give up on a pending review: it is kept, marked, and never retried."""+ with self._lock, self._db:+ self._db.execute(+ "UPDATE reviews SET status='dropped' WHERE session=? AND turn_id=? "+ "AND status='pending'",+ (session, turn_id),+ )+def review_counts(self, agent_id: str) -> dict[str, int]:"""Count direct chats and routine reviews without reading conversation contents."""session = f"society:{agent_id}"diff --git a/jarvis/society/learning.py b/jarvis/society/learning.pyindex 9431e9471a..a2d9f5898f 100644--- a/jarvis/society/learning.py+++ b/jarvis/society/learning.py@@ -13,6 +13,7 @@ durable review receipt for a later attempt.from __future__ import annotations+import inspectimport loggingimport osimport shutil@@ -165,25 +166,40 @@ class AgentSkills:return sorted(out, key=lambda s: s["slug"])-CreatorFactory = Callable[[AgentRecord, AgentSkills], Any | None]+#: ``(agent, skills) -> creator | None``, or an awaitable of that (the real+#: factory resolves the agent's seat off the event loop).+CreatorFactory = Callable[[AgentRecord, AgentSkills], Any]def default_creator_factory(cfg_getter: Callable[[], Any]) -> CreatorFactory:- """The real creator: Jarvis' brain + the agent's registry (None without a brain)."""+ """The real creator: the agent's OWN seat + its private registry.- def _factory(agent: AgentRecord, skills: AgentSkills) -> Any | None:+ The skill is authored on exactly the provider, model and auth mode the+ agent's chat runs on (``seat_brain``; maintainer decision 2026-09-30),+ never on Jarvis' active provider or the resolver ladder. ``None`` when+ that seat cannot be built: the agent then learns nothing this time.+ """++ async def _factory(agent: AgentRecord, skills: AgentSkills) -> Any | None:from jarvis.agent_chat.runner_brain import brain_managerfrom jarvis.skills.creator_service import SkillCreatorService, build_authoring_context- brain = brain_manager()- if brain is None:+ from .seat_brain import SeatUnavailable, agent_brain++ try:+ seat = await agent_brain(cfg_getter(), agent, caller="society-skill")+ except SeatUnavailable as exc:+ log.info("society learning: %s has no usable seat (%s)", agent.agent_id, exc)return Nonereturn SkillCreatorService(- brain=brain,+ brain=seat,registry=skills.registry,- config=cfg_getter(),user_skills_root=skills.root,- context=build_authoring_context(brain_manager=brain, registry=skills.registry),+ # The tool inventory only; no provider of Jarvis' own is asked.+ context=build_authoring_context(+ brain_manager=brain_manager(), registry=skills.registry+ ),+ seat_only=True,)return _factory@@ -232,6 +248,8 @@ class LearningPass:return Noneskills = rt.skills_for(agent.agent_id)creator = self._creator_factory(agent, skills)+ if inspect.isawaitable(creator):+ creator = await creatorif creator is None:log.info("society learning: no brain available; %s learns nothing", agent.agent_id)return Nonediff --git a/jarvis/society/review.py b/jarvis/society/review.pyindex 8aaa0480f9..744b22d128 100644--- a/jarvis/society/review.py+++ b/jarvis/society/review.py@@ -55,83 +55,45 @@ Importance: 8-10 enduring identity/requirements; 4-7 durable facts; 0-3 incidentasync def _ask(runtime: Any, agent: Any, prompt: str) -> dict[str, Any] | None:- from jarvis.agent_chat.runner_brain import brain_manager- from jarvis.brain.streaming import aggregate- from jarvis.core.config import get_jarvis_agent_secret, override_provider_secrets-- manager = brain_manager()- getter = getattr(manager, "_get_brain", None)- if not callable(getter):- return None- from .chat_binding import pair_for+ """Ask the reviewed agent's OWN seat, and nothing else.- provider_name, model, _ = pair_for(runtime.config(), agent)- secret = await asyncio.to_thread(get_jarvis_agent_secret, provider_name)- with override_provider_secrets({provider_name: secret} if secret else {}):-- def candidates():- try:- yield getter(provider_name, model or None, scope=f"society-review:{agent.agent_id}")- except Exception:- log.info("society: selected seat has no review provider", exc_info=True)- # A review is background work nobody waits on: a connected- # subscription answers before any per-token key (mandate- # 2026-09-29), and the keyed chain below stays the fallback.- from jarvis.brain.resolver import resolve_subscription_brain-- subscription = resolve_subscription_brain(runtime.config())- if subscription is not None:- yield subscription- # Reuse the established authoring fallback chain, but allocate a- # separate scoped instance so native engines never share callers.- from .learning import default_creator_factory+ The provider, model and auth mode are the ones the agent's chat runs on+ (``seat_brain``; maintainer decision 2026-09-30). ``None`` when the seat+ cannot answer: the review stays pending, ``review_queue`` retries it a+ bounded number of times and then drops it. No other provider, no+ subscription the agent does not sit on and no other key is asked instead.+ """+ from jarvis.brain.streaming import aggregate- creator = default_creator_factory(runtime.config)(- agent, runtime.skills_for(agent.agent_id)- )- if creator is not None:- for candidate, _ in creator._candidate_brains():- try:- yield getter(- candidate.name,- getattr(candidate, "_model", None),- scope=f"society-review:{agent.agent_id}",- )- except Exception:- log.info("society: fallback review provider unavailable", exc_info=True)+ from .seat_brain import SeatUnavailable, agent_brain- seen = set()- providers = candidates()- while True:- # Provider construction may read catalogs, credentials and local- # models. Never run that synchronous work on the desktop event loop.- # next(..., None) also avoids propagating StopIteration into a Future.- provider = await asyncio.to_thread(next, providers, None)- if provider is None:- break- identity = (getattr(provider, "name", ""), str(getattr(provider, "_model", "")))- if identity in seen:- continue- seen.add(identity)- try:- request = BrainRequest(- system=_SYSTEM,- messages=(BrainMessage(role="user", content=prompt),),- temperature=0.1,- max_tokens=4096,- )- response = await asyncio.wait_for(aggregate(provider.complete(request)), timeout=90)- raw = response.text.strip()- if raw.startswith("```"):- raw = raw.split("\n", 1)[1].rsplit("```", 1)[0]- result = json.loads(raw)- if isinstance(result, dict):- return result- except Exception:- log.warning(- "society: review provider failed; trying the configured fallback", exc_info=True- )+ try:+ brain = await agent_brain(runtime.config(), agent, caller="society-review")+ except SeatUnavailable as exc:+ log.info("society review: %s has no usable seat (%s)", agent.agent_id, exc)+ return None+ request = BrainRequest(+ system=_SYSTEM,+ messages=(BrainMessage(role="user", content=prompt),),+ temperature=0.1,+ max_tokens=4096,+ )+ try:+ response = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=90)+ raw = response.text.strip()+ if raw.startswith("```"):+ raw = raw.split("\n", 1)[1].rsplit("```", 1)[0]+ result = json.loads(raw)+ except Exception as exc: # noqa: BLE001 - one failed attempt; the queue retries it+ # The type only: a provider's error body never reaches a log (AP-34).+ log.warning(+ "society review: %s's seat %s did not answer (%s)",+ agent.agent_id,+ brain.seat.describe(),+ type(exc).__name__,+ )return None+ return result if isinstance(result, dict) else Noneasync def review_turn(runtime: Any, pending: dict[str, Any]) -> bool:diff --git a/jarvis/society/review_queue.py b/jarvis/society/review_queue.pyindex eff8776b00..e00bf04d23 100644--- a/jarvis/society/review_queue.py+++ b/jarvis/society/review_queue.py@@ -1,28 +1,68 @@-"""Bounded automatic retries for durable post-turn memory reviews."""+"""Bounded automatic retries for durable post-turn memory reviews.++A review runs on the reviewed agent's own seat and nothing else+(``seat_brain``). When that seat keeps failing, the review gets its first+attempt plus ``MAX_RETRIES`` spaced retries and is then dropped with one log+line, instead of being retried on every later turn or answered by another+provider.+"""from __future__ import annotationsimport asyncioimport loggingimport random-from typing import Any+from typing import Any, Finalfrom .review import review_turnlog = logging.getLogger(__name__)+#: Spaced retries after the first attempt (45-60 s, doubled per round).+MAX_RETRIES: Final[int] = 3+#: Failed attempts after which a review is dropped: the first plus the retries.+MAX_ATTEMPTS: Final[int] = MAX_RETRIES + 1+++def _failures(runtime: Any) -> dict[tuple[str, str], int]:+ """Failed attempts per pending review in this process."""+ failures = getattr(runtime, "_review_failures", None)+ if failures is None:+ failures = {}+ runtime._review_failures = failures+ return failures+async def drain_reviews(runtime: Any, *, retry: int = 0) -> None:+ failures = _failures(runtime)async with runtime._review_lock:for pending in runtime.conversations.pending_reviews():+ key = (pending["session"], pending["turn_id"])try:- if await review_turn(runtime, pending):- runtime.conversations.finish_review(pending["session"], pending["turn_id"])+ done = await review_turn(runtime, pending)except Exception:log.exception("society review remains pending for %s", pending["turn_id"])+ done = False+ if done:+ runtime.conversations.finish_review(*key)+ failures.pop(key, None)+ continue+ failures[key] = failures.get(key, 0) + 1+ # Only the last round of a retry chain drops, so a burst of turns+ # never uses up a review's attempts before the spaced retries ran.+ if retry >= MAX_RETRIES and failures[key] >= MAX_ATTEMPTS:+ runtime.conversations.drop_review(*key)+ attempts = failures.pop(key)+ log.warning(+ "society review of turn %s (%s) dropped after %d failed attempts; "+ "only the agent's own seat is ever asked",+ pending["turn_id"],+ pending["session"],+ attempts,+ )if (not runtime.conversations.pending_reviews()- or retry >= 3+ or retry >= MAX_RETRIESor getattr(runtime, "_closing", False)):returndiff --git a/jarvis/society/seat_brain.py b/jarvis/society/seat_brain.pynew file mode 100644index 0000000000..7fd6892b35--- /dev/null+++ b/jarvis/society/seat_brain.py@@ -0,0 +1,277 @@+"""An agent's own seat as the brain for its background memory work.++Maintainer decision (2026-09-30): an agent's memory updates run on exactly the+provider, model and auth mode that agent's chat runs on. An agent on the+Claude API key with a chosen model reviews on that key and that model; one on+the Claude subscription reviews on that subscription; one on the ChatGPT+subscription on that one. Nothing else is ever asked. Before, reviews walked+a chain of other providers and landed on keys nobody chose for that work: one+agent's own key answered 401 and its reviews fell through to an unrelated+per-token key for a month.++A seat that cannot be resolved, or that fails, raises here and the caller's+own bounded retry applies (the Society review queue, the learning loop's+backoff); after that the work is dropped. There is no fallback to another+provider, another model, a subscription the agent does not sit on, or a key+the agent does not use.++Three callers share this module: the Society turn review+(``society/review.py``), Society skill learning (``society/learning.py``)+and Jarvis' own learning loop (``memory/learning``), whose seat is the Jarvis+lead's: the front-page chat's pick.++"The seat" is read from the same places the chat reads it, so the two cannot+disagree:++* the provider/model pair: ``chat_binding.pair_for`` for an agent;+ ``model_selection.worker_selection`` + ``task_agent.subscription_seat`` for+ Jarvis, exactly as ``AgentChatService.send`` reseats the front-page chat;+* the runner: ``agent_chat.service.resolve_runner``. A vendor CLI seat answers+ through that CLI's brain in structured mode; an API seat through the+ provider's own brain plugin behind the Agents-tab key+ (``get_jarvis_agent_secret``, as ``runner_brain`` does for the chat);+* the instance: ``brain.resolver.resolve_browser_brain``, the resolver of an+ agent's existing access with a structured-output contract.++Everything that may block (a login probe, the keyring, plugin construction)+runs in a worker thread, off the desktop event loop.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import AsyncIterator, Iterator, Mapping+from contextlib import contextmanager+from dataclasses import dataclass+from typing import Any, Final++log = logging.getLogger(__name__)++__all__ = [+ "Seat",+ "SeatBrain",+ "SeatCallFailed",+ "SeatUnavailable",+ "agent_brain",+ "agent_seat",+ "jarvis_seat",+ "seat_brain",+]++#: Runners that are a provider's own API behind a key, not a vendor CLI.+_KEYED_RUNNERS: Final[frozenset[str]] = frozenset({"brain", "api"})+++class SeatUnavailable(RuntimeError):+ """The seat cannot be built right now; no other provider is asked instead.++ The message is app-authored (never a provider's error body, AP-34).+ """+++class SeatCallFailed(RuntimeError):+ """A call on the seat failed. Carries the exception type, never its text:+ a provider error body must not reach a log line (AP-34)."""+++@dataclass(frozen=True, slots=True)+class Seat:+ """What a chat runs on: provider, model and the runner behind them."""++ provider: str+ #: ``""`` = the seat's own default (the CLI's, or the provider's+ #: router-tier model, exactly as the chat picks it).+ model: str = ""+ #: ``brain``/``api`` = the provider API behind a key; else a CLI runner id.+ runner: str = "brain"+ #: Whether the Agents-tab key slot applies. ``False`` for an explicit+ #: ``[memory.learning]`` provider override, which uses the provider's+ #: ordinary credential chain.+ agent_key: bool = True++ @property+ def keyed(self) -> bool:+ return self.runner in _KEYED_RUNNERS++ def describe(self) -> str:+ return f"{self.provider}/{self.model or 'default model'}"+++def agent_seat(config: Any, agent: Any) -> Seat:+ """The seat of a Society agent's own chat. Blocking: call it in a thread."""+ from jarvis.agent_chat.service import resolve_runner++ from .chat_binding import pair_for++ try:+ provider, model, _effort = pair_for(config, agent)+ except PermissionError as exc:+ raise SeatUnavailable(str(exc) or "no provider can run this agent's chat") from None+ if not provider:+ raise SeatUnavailable("this agent's chat names no provider")+ return Seat(provider, model or "", resolve_runner(provider, surface="society"))+++def jarvis_seat(config: Any) -> Seat:+ """The Jarvis lead's seat: what the front-page chat answers on right now.++ The Agents selection (``[brain.worker]``) when one is set, mapped onto its+ subscription seat the way ``AgentChatService.send`` maps it; otherwise the+ Agents tier, which is what a chat with no provider of its own runs on.+ Blocking (the Claude login probe, the credential probes): call it in a+ thread.+ """+ from jarvis.core.model_selection import worker_selection+ from jarvis.core.task_agent import subscription_seat++ selection = worker_selection(config)+ if selection is not None:+ provider, runner = subscription_seat(selection.provider) or (selection.provider, "brain")+ return Seat(provider, selection.model or "", runner)+ from jarvis.agent_chat.service import resolve_runner+ from jarvis.local_models.assistant_session import agents_tier++ tier = agents_tier(config)+ if not tier.ready or not tier.provider:+ raise SeatUnavailable(tier.reason or "no provider can run the Jarvis chat")+ return Seat(tier.provider, tier.model or "", resolve_runner(tier.provider, surface="jarvis"))+++def _chat_default_model(config: Any, provider: str) -> str:+ """The model an API seat's chat runs when it names none.++ ``runner_brain`` asks ``BrainManager._fast_model``: the provider's+ configured model, else its router-tier default. Read from the config here+ so a review drained before the brain manager exists never falls to a+ plugin's hardcoded default (for a gateway that can be a paid frontier+ model the person never picked).+ """+ from jarvis.brain.manager import get_tier_default_model++ providers = getattr(getattr(config, "brain", None), "providers", None) or {}+ configured = str(getattr(providers.get(provider), "model", "") or "")+ return configured or get_tier_default_model("router", provider) or ""+++def _cli_adapter(seat: Seat, model: str) -> Any:+ """A CLI seat with no brain plugin of its own, adapted like the browser does."""+ from jarvis.agent_chat.catalog import provider_row++ row = provider_row(seat.provider)+ if row is None or row.runner != "grok-cli":+ raise SeatUnavailable(f"the {seat.provider} seat has no background model in this app")+ from jarvis.agent_chat.browser_model import GrokBrowserModel+ from jarvis.brain.usage_meter import meter_brain++ return meter_brain(GrokBrowserModel(model), seat.provider)+++def _build(config: Any, seat: Seat, caller: str) -> SeatBrain:+ """Instantiate exactly ``seat``. Blocking: call it in a thread."""+ from jarvis.brain.resolver import resolve_browser_brain++ model = seat.model+ if seat.keyed and not model:+ model = _chat_default_model(config, seat.provider)+ try:+ inner = resolve_browser_brain(config, seat.provider, model, runner=seat.runner)+ except LookupError:+ inner = _cli_adapter(seat, model)+ except Exception as exc: # noqa: BLE001 - reported by type; the text may be a provider's+ raise SeatUnavailable(+ f"the {seat.provider} seat could not be built ({type(exc).__name__})"+ ) from None+ secrets: dict[str, str] = {}+ if seat.keyed and seat.agent_key:+ from jarvis.core.config import get_jarvis_agent_secret++ try:+ secret = get_jarvis_agent_secret(seat.provider)+ except Exception as exc: # noqa: BLE001 - no dedicated key: the family key answers+ # Same as the chat (``runner_brain._agent_secret``): without an+ # Agents-tab key the provider resolves its ordinary credential.+ log.debug(+ "seat brain: no Agents-tab key for %s (%s)", seat.provider, type(exc).__name__+ )+ secret = None+ if secret:+ secrets[seat.provider] = secret+ return SeatBrain(inner, seat, secrets=secrets, caller=caller)+++async def seat_brain(config: Any, seat: Seat, *, caller: str) -> SeatBrain:+ """``seat`` as a Brain, built off the event loop. Raises ``SeatUnavailable``."""+ return await asyncio.to_thread(_build, config, seat, caller)+++async def agent_brain(config: Any, agent: Any, *, caller: str) -> SeatBrain:+ """A Society agent's own seat as a Brain. Raises ``SeatUnavailable``."""++ def resolve() -> SeatBrain:+ return _build(config, agent_seat(config, agent), caller)++ return await asyncio.to_thread(resolve)+++class SeatBrain:+ """One seat's brain: every call runs under that seat's credential and is+ written to the usage ledger under ``caller``.++ The credential override is entered around each step of the stream, never+ across a ``yield``, so it is always reset in the context that set it,+ however the consumer ends the stream. Attributes other than ``complete``+ forward to the seat's own brain (``name``, ``context_window``, ...).+ """++ __slots__ = ("_caller", "_inner", "_secrets", "seat")++ def __init__(+ self, inner: Any, seat: Seat, *, secrets: Mapping[str, str], caller: str+ ) -> None:+ self._inner = inner+ self.seat = seat+ self._secrets = dict(secrets)+ self._caller = caller++ def __getattr__(self, name: str) -> Any:+ if name in SeatBrain.__slots__ or name.startswith("__"):+ raise AttributeError(name)+ return getattr(self._inner, name)++ def __repr__(self) -> str: # pragma: no cover - logging nicety+ return f"SeatBrain({self.seat.describe()}, runner={self.seat.runner})"++ @contextmanager+ def _scope(self) -> Iterator[None]:+ from jarvis.core.config import override_provider_secrets+ from jarvis.costs.ledger import usage_context++ # Exactly this seat's credentials: an override inherited from whatever+ # task scheduled this work never reaches the call.+ with usage_context(self._caller), override_provider_secrets(self._secrets):+ yield++ def complete(self, request: Any) -> AsyncIterator[Any]:+ return self._stream(request)++ async def _stream(self, request: Any) -> AsyncIterator[Any]:+ iterator: Any = None+ try:+ with self._scope():+ iterator = self._inner.complete(request).__aiter__()+ while True:+ with self._scope():+ try:+ delta = await iterator.__anext__()+ except StopAsyncIteration:+ return+ yield delta+ except Exception as exc: # noqa: BLE001 - re-raised without the provider's text+ raise SeatCallFailed(+ f"the {self.seat.describe()} seat failed ({type(exc).__name__})"+ ) from None+ finally:+ close = getattr(iterator, "aclose", None)+ if close is not None:+ await close()diff --git a/tests/fakes/fake_seat_registry.py b/tests/fakes/fake_seat_registry.pynew file mode 100644index 0000000000..04ea7f97f7--- /dev/null+++ b/tests/fakes/fake_seat_registry.py@@ -0,0 +1,132 @@+"""A brain-provider registry that records every instance it builds.++Stands in for ``BrainProviderRegistry`` behind ``jarvis.brain.resolver.+_get_registry`` so the agent-seat contract can be proven: which provider was+built, with which model and constructor flags, and what credential override+and usage tag were live when the seat answered. No network, no subprocess.+"""++from __future__ import annotations++from collections.abc import Callable, Iterable+from dataclasses import dataclass, field+from typing import Any++from jarvis.core.protocols import BrainDelta++REVIEW_REPLY = '{"memories": [], "skill": null}'+++@dataclass+class Built:+ """One instantiation: provider name and the constructor keyword arguments."""++ name: str+ kwargs: dict[str, Any]+++@dataclass+class Answered:+ """One answered call: who answered, and the context it answered in."""++ name: str+ model: str+ secrets: dict[str, Any]+ caller: str+ system: str+++@dataclass+class RecordingRegistry:+ """``available`` / ``get_class`` / ``instantiate`` like the real registry.++ ``cli`` names take ``structured_prompts`` (and ``prefer_subscription``+ for ``codex``) like the CLI brains; the rest take only ``model``.+ ``failing`` names raise a RuntimeError carrying a fake provider body when+ they answer; ``replies`` overrides the text a name answers with.+ """++ names: Iterable[str]+ cli: Iterable[str] = ("claude-cli", "codex", "antigravity")+ failing: Iterable[str] = ()+ replies: dict[str, str] = field(default_factory=dict)+ on_instantiate: Callable[[str], None] | None = None+ built: list[Built] = field(default_factory=list)+ answered: list[Answered] = field(default_factory=list)++ def __post_init__(self) -> None:+ self.names = tuple(self.names)+ self.cli = frozenset(self.cli)+ self.failing = frozenset(self.failing)++ def available(self) -> list[str]:+ return sorted(self.names)++ def get_class(self, name: str) -> type:+ if name not in self.names:+ raise KeyError(f"Brain provider '{name}' not found.")+ return _brain_class(self, name)++ def instantiate(self, name: str, **kwargs: Any) -> Any:+ cls = self.get_class(name)+ if self.on_instantiate is not None:+ self.on_instantiate(name)+ self.built.append(Built(name, dict(kwargs)))+ return cls(**kwargs)++ def built_names(self) -> list[str]:+ return [item.name for item in self.built]+++class _Brain:+ def __init__(self, registry: RecordingRegistry, name: str, model: str | None) -> None:+ self._registry = registry+ self.name = name+ self._model = model or ""++ async def complete(self, request: Any):+ from jarvis.core import config+ from jarvis.costs.ledger import current_caller++ overrides = config._PROVIDER_SECRET_OVERRIDES.get()+ self._registry.answered.append(+ Answered(+ self.name,+ self._model,+ dict(overrides or {}),+ current_caller(),+ str(getattr(request, "system", "") or ""),+ )+ )+ if self.name in self._registry.failing:+ raise RuntimeError(f"{self.name}: 401 private provider body sk-leak")+ yield BrainDelta(content=self._registry.replies.get(self.name, REVIEW_REPLY))+++def _brain_class(registry: RecordingRegistry, name: str) -> type:+ if name == "codex":++ class CodexLike(_Brain):+ def __init__(+ self,+ model: str | None = None,+ structured_prompts: bool = False,+ prefer_subscription: bool = False,+ subscription_text_only: bool = False,+ ) -> None:+ super().__init__(registry, name, model)++ return CodexLike+ if name in registry.cli:++ class CliLike(_Brain):+ def __init__(self, model: str | None = None, structured_prompts: bool = False) -> None:+ super().__init__(registry, name, model)++ return CliLike++ class ApiLike(_Brain):+ def __init__(self, model: str | None = None) -> None:+ super().__init__(registry, name, model)++ return ApiLikediff --git a/tests/unit/skills/test_creator_service.py b/tests/unit/skills/test_creator_service.pyindex f76923ba19..265bab763e 100644--- a/tests/unit/skills/test_creator_service.py+++ b/tests/unit/skills/test_creator_service.py@@ -354,6 +354,36 @@ async def test_brain_ladder_crosses_a_dead_active_provider(registry, monkeypatchassert result.draft["name"] == "Brain Made Skill"+async def test_a_seat_only_creator_never_climbs_the_ladder(registry, monkeypatch) -> None:+ """A Society agent's skill is authored on its own seat or not at all: no+ operation pin and no resolver rung answers when that seat is dead, even+ with a config present. Other callers keep the ladder above."""+ from types import SimpleNamespace++ from jarvis.brain import resolver as resolver_mod+ from jarvis.core.model_selection import ModelSelection, use_operation_model++ def ladder(cfg, bus=None): # noqa: ANN001+ raise AssertionError("a seat-only creator climbed the resolver ladder")++ for name in ("resolve_tool_model_brain", "resolve_quality_brain", "resolve_frontier_brain"):+ monkeypatch.setattr(resolver_mod, name, ladder)+ svc = SkillCreatorService(+ brain=_DeadBrain(), registry=registry, config=SimpleNamespace(), seat_only=True+ )+ with use_operation_model(ModelSelection("openai", "pinned")):+ result = await svc.draft(SkillCreatorInput(intent="something"))+ assert result.brain_used is False++ seat = SkillCreatorService(+ brain=_RecordingBrain(_GOOD_BRAIN_JSON), registry=registry, seat_only=True+ )+ answered = await seat.draft(SkillCreatorInput(intent="something"))+ assert answered.brain_used is True+ assert answered.brain_source == "seat"++@pytest.mark.asyncioasync def test_prompt_carries_the_live_inventory_and_the_skill_contract(registry) -> None:"""What makes the draft a WORKING skill: the model sees which connectorsdiff --git a/tests/unit/society/test_review_responsiveness.py b/tests/unit/society/test_review_responsiveness.pyindex 60db530670..9a39b6ab2c 100644--- a/tests/unit/society/test_review_responsiveness.py+++ b/tests/unit/society/test_review_responsiveness.py@@ -1,4 +1,4 @@-"""Slow review provider initialization must not stall the desktop event loop."""+"""Slow review seat construction must not stall the desktop event loop."""import asyncioimport contextvars@@ -7,132 +7,58 @@ from types import SimpleNamespaceimport pytest-from jarvis.core.protocols import BrainDeltafrom jarvis.society.review import _ask+from tests.fakes.fake_seat_registry import RecordingRegistry+++def no_agent_key(monkeypatch):+ from jarvis.core import config++ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)@pytest.mark.asyncio[email protected]("fallback", [False, True])-async def test_review_provider_resolution_keeps_loop_responsive(monkeypatch, fallback):- from jarvis.agent_chat import runner_brain+async def test_review_seat_construction_keeps_loop_responsive(monkeypatch, no_agent_key):from jarvis.brain import resolver- from jarvis.core import config- from jarvis.society import learning- monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg: None)loop = asyncio.get_running_loop()loop_thread = threading.get_ident()entered = asyncio.Event()release = threading.Event()context = contextvars.ContextVar("review-test-context", default="missing")context.set("inherited")- calls = []-- class Provider:- def __init__(self, name):- self.name = name- self._model = "test-model"- async def complete(self, request):- assert threading.get_ident() == loop_thread- if self.name == "primary" and fallback:- raise RuntimeError("primary unavailable")- yield BrainDelta(content='{"memories": [], "skill": null}')+ def slow_build(name):+ assert threading.get_ident() != loop_thread+ assert context.get() == "inherited"+ loop.call_soon_threadsafe(entered.set)+ assert release.wait(timeout=3), "event loop could not release seat construction"- def getter(name, model, *, scope):- calls.append((name, scope))- if name == ("fallback" if fallback else "primary"):- assert threading.get_ident() != loop_thread- assert context.get() == "inherited"- loop.call_soon_threadsafe(entered.set)- assert release.wait(timeout=3), "event loop could not release provider initialization"- return Provider(name)-- class Creator:- def _candidate_brains(self):- assert threading.get_ident() != loop_thread- yield Provider("fallback"), "fallback"-- monkeypatch.setattr(runner_brain, "brain_manager", lambda: SimpleNamespace(_get_brain=getter))- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)- monkeypatch.setattr(learning, "default_creator_factory", lambda cfg: lambda *args: Creator())+ registry = RecordingRegistry(["openai"], on_instantiate=slow_build)+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)runtime = SimpleNamespace(config=lambda: None, skills_for=lambda agent_id: None)- agent = SimpleNamespace(provider="primary", model="test-model", effort="low", agent_id="test")+ agent = SimpleNamespace(provider="openai", model="test-model", effort="low", agent_id="test")task = asyncio.create_task(_ask(runtime, agent, "Evidence"))try:await asyncio.wait_for(entered.wait(), timeout=2)- # This callback runs while synchronous provider construction is blocked.+ # This callback runs while synchronous seat construction is blocked.await asyncio.sleep(0)assert not task.done()finally:release.set()assert await asyncio.wait_for(task, timeout=2) == {"memories": [], "skill": None}- assert calls == [("primary", "society-review:test")] + (- [("fallback", "society-review:test")] if fallback else []- )+ assert registry.built_names() == ["openai"]@pytest.mark.asyncio-async def test_unavailable_review_providers_finish_without_stop_iteration(monkeypatch):- from jarvis.agent_chat import runner_brain+async def test_unavailable_review_seat_finishes_without_stop_iteration(monkeypatch, no_agent_key):from jarvis.brain import resolver- from jarvis.core import config- from jarvis.society import learning- def unavailable(*args, **kwargs):- raise RuntimeError("no usable provider")-- monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg: None)-- monkeypatch.setattr(- runner_brain, "brain_manager", lambda: SimpleNamespace(_get_brain=unavailable)- )- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)- monkeypatch.setattr(learning, "default_creator_factory", lambda cfg: lambda *args: None)+ registry = RecordingRegistry(["openai", "gemini"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)runtime = SimpleNamespace(config=lambda: None, skills_for=lambda agent_id: None)- agent = SimpleNamespace(provider="primary", model="test", effort="low", agent_id="test")+ # A coding CLI with no background brain in this app: nothing can answer.+ agent = SimpleNamespace(provider="cursor", model="", effort="low", agent_id="test")assert await asyncio.wait_for(_ask(runtime, agent, "Evidence"), timeout=2) is None---async def test_connected_subscription_reviews_before_the_keyed_chain(monkeypatch):- """Background review spends a subscription before any per-token key."""- from jarvis.agent_chat import runner_brain- from jarvis.brain import resolver- from jarvis.core import config- from jarvis.society import learning-- answered = []-- class Provider:- def __init__(self, name, *, fails=False):- self.name = name- self._model = ""- self._fails = fails-- async def complete(self, request):- answered.append(self.name)- if self._fails:- raise RuntimeError(f"{self.name} unavailable")- yield BrainDelta(content='{"memories": [], "skill": null}')-- class Creator:- def _candidate_brains(self):- yield Provider("paid-key"), "paid-key"-- def getter(name, model, *, scope):- return Provider(name, fails=name == "seat")-- monkeypatch.setattr(runner_brain, "brain_manager", lambda: SimpleNamespace(_get_brain=getter))- monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)- monkeypatch.setattr(learning, "default_creator_factory", lambda cfg: lambda *args: Creator())- subscription = Provider("subscription")- monkeypatch.setattr(resolver, "resolve_subscription_brain", lambda cfg: subscription)- runtime = SimpleNamespace(config=lambda: None, skills_for=lambda agent_id: None)- agent = SimpleNamespace(provider="seat", model="", effort="low", agent_id="test")-- assert await asyncio.wait_for(_ask(runtime, agent, "Evidence"), timeout=2) == {- "memories": [],- "skill": None,- }- assert answered == ["seat", "subscription"]+ assert registry.built == []diff --git a/tests/unit/society/test_seat_memory.py b/tests/unit/society/test_seat_memory.pynew file mode 100644index 0000000000..dcd4f67905--- /dev/null+++ b/tests/unit/society/test_seat_memory.py@@ -0,0 +1,303 @@+"""An agent's memory updates run on exactly that agent's seat, and nothing else.++Maintainer decision (2026-09-30): the Society turn review, Society skill+learning and Jarvis' own learning loop use the provider, model and auth mode+the agent's chat runs on. A seat that cannot answer makes the work wait and+finally drop; it never falls through to another provider. The registry here+records every brain it builds, so "nothing else was asked" is checked by what+was instantiated, not by what answered.+"""++from __future__ import annotations++import asyncio+import json+import logging+from types import SimpleNamespace++import pytest++from jarvis.society.review import _ask+from tests.fakes.fake_seat_registry import RecordingRegistry++ALL = ["openai", "gemini", "claude-api", "claude-cli", "codex", "antigravity", "vertex"]+++def registry(monkeypatch) -> RecordingRegistry:+ from jarvis.brain import resolver++ reg = RecordingRegistry(ALL)+ monkeypatch.setattr(resolver, "_get_registry", lambda: reg)+ return reg++[email protected](autouse=True)+def agent_keys(monkeypatch):+ """The Agents-tab key of each family, and a trap for the old fallbacks."""+ from jarvis.brain import resolver+ from jarvis.core import config, runtime_refs++ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: f"agent-key-{provider}")+ monkeypatch.setattr(runtime_refs, "get_brain_manager", lambda: None)++ def forbidden(*args, **kwargs):+ raise AssertionError("a background memory update asked a subscription resolver")++ monkeypatch.setattr(resolver, "resolve_subscription_brain", forbidden)+++def _agent(provider: str, model: str = "", agent_id: str = "scout") -> SimpleNamespace:+ return SimpleNamespace(provider=provider, model=model, effort="", agent_id=agent_id)+++def _runtime(cfg=None) -> SimpleNamespace:+ return SimpleNamespace(config=lambda: cfg, skills_for=lambda agent_id: None)+++# ── Society turn review ──────────────────────────────────────────────────────+++async def test_review_runs_on_the_agents_api_key_and_model(registry):+ result = await _ask(_runtime(), _agent("gemini", "gemini-chosen"), "Evidence")+ assert result == {"memories": [], "skill": None}+ assert [(b.name, b.kwargs) for b in registry.built] == [+ ("gemini", {"model": "gemini-chosen"})+ ]+ [answer] = registry.answered+ assert answer.secrets == {"gemini": "agent-key-gemini"}+ assert answer.caller == "society-review"+++async def test_review_on_a_subscription_seat_uses_that_cli_in_structured_mode(registry):+ await _ask(_runtime(), _agent("openai-codex", "gpt-5.5"), "Evidence")+ [built] = registry.built+ assert built.name == "codex"+ assert built.kwargs["model"] == "gpt-5.5"+ assert built.kwargs["structured_prompts"] is True+ assert built.kwargs["prefer_subscription"] is True+ # A subscription seat is not billed to a key: no key override is set.+ assert registry.answered[0].secrets == {}+++ ("cli_installed", "expected"),+ [(True, "claude-cli"), (False, "claude-api")],+)+async def test_the_claude_row_reviews_where_its_chat_runs(+ registry, monkeypatch, cli_installed, expected+):+ from jarvis.agent_chat import service++ monkeypatch.setattr(service, "_claude_cli_installed", lambda: cli_installed)+ await _ask(_runtime(), _agent("claude-api", "claude-sonnet-5-5"), "Evidence")+ assert [(b.name, b.kwargs.get("model")) for b in registry.built] == [+ (expected, "claude-sonnet-5-5")+ ]+++async def test_a_failing_seat_never_reaches_another_provider(registry, caplog):+ registry.failing = frozenset({"openai"})+ with caplog.at_level(logging.DEBUG):+ assert await _ask(_runtime(), _agent("openai", "gpt-chosen"), "Evidence") is None+ assert registry.built_names() == ["openai"]+ assert [a.name for a in registry.answered] == ["openai"]+ # AP-34: the provider's error body never reaches a log line.+ assert "private provider body" not in caplog.text+ assert "sk-leak" not in caplog.text+++async def test_an_agent_on_a_cli_without_a_background_brain_asks_nothing(registry):+ assert await _ask(_runtime(), _agent("cursor"), "Evidence") is None+ assert registry.built == []+++async def test_an_unset_agent_follows_the_agents_tier_it_chats_on(registry, monkeypatch):+ from jarvis.local_models import assistant_session++ tier = SimpleNamespace(provider="vertex", model="tier-model", ready=True, reason="")+ monkeypatch.setattr(assistant_session, "agents_tier", lambda cfg: tier)+ await _ask(_runtime(), _agent(""), "Evidence")+ assert [(b.name, b.kwargs) for b in registry.built] == [("vertex", {"model": "tier-model"})]+++async def test_a_seat_without_a_model_uses_the_chats_router_tier_model(registry):+ from jarvis.brain.manager import get_tier_default_model++ cfg = SimpleNamespace(brain=SimpleNamespace(providers={}))+ await _ask(_runtime(cfg), _agent("gemini"), "Evidence")+ [built] = registry.built+ assert built.kwargs == {"model": get_tier_default_model("router", "gemini")}+++# ── the bounded review queue ────────────────────────────────────────────────+++async def rt(tmp_path):+ from jarvis.society.runtime import SocietyRuntime++ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))+ runtime = SocietyRuntime(tmp_path, cfg=lambda: cfg, seed_starter_team=False)+ await runtime.ensure_started()+ await runtime.roster.create(name="Scout", description="Draft only.")+ try:+ yield runtime+ finally:+ await runtime.close()+++def _queue(rt, turn_id: str = "turn-1") -> None:+ events = [+ {"kind": "user_message", "payload": {"text": "A normal completed task."}},+ {"kind": "assistant_text", "payload": {"text": "Done."}},+ {"kind": "turn_finished", "payload": {"status": "done"}},+ ]+ rt.conversations.queue_review("society:scout", turn_id, events, direct_user=True)+++async def _settle(rt) -> None:+ for _ in range(10):+ retry = rt._memory_review_retry+ if retry is None:+ return+ await asyncio.wait_for(retry, 5)+++async def test_a_seat_that_keeps_failing_drops_the_review_after_bounded_retries(+ rt, monkeypatch, caplog+):+ from jarvis.society import review_queue++ attempts = []++ async def seat_down(*args):+ attempts.append(True)+ return None++ rt.turn_reviewer = seat_down+ monkeypatch.setattr(review_queue.random, "uniform", lambda *args: 0)+ _queue(rt)+ with caplog.at_level(logging.WARNING, logger="jarvis.society.review_queue"):+ await rt.recover_reviews()+ await _settle(rt)+ assert len(attempts) == review_queue.MAX_ATTEMPTS+ assert rt.conversations.review_counts("scout") == {"pending": 0, "done": 0, "dropped": 1}+ assert [r for r in caplog.records if "dropped" in r.getMessage()]+ # A dropped review is never retried again.+ await rt.recover_reviews()+ assert len(attempts) == review_queue.MAX_ATTEMPTS+++async def test_a_burst_of_turns_does_not_use_up_the_spaced_retries(rt, monkeypatch):+ from jarvis.society import review_queue++ async def seat_down(*args):+ return None++ rt.turn_reviewer = seat_down+ # The retry chain waits; only turn-triggered drains run.+ monkeypatch.setattr(review_queue.random, "uniform", lambda *args: 3600)+ _queue(rt)+ for _ in range(review_queue.MAX_ATTEMPTS + 2):+ await rt.recover_reviews()+ assert rt.conversations.review_counts("scout") == {"pending": 1, "done": 0}+++# ── Society skill learning ──────────────────────────────────────────────────+++SKILL_DRAFT = json.dumps(+ {+ "name": "Source check",+ "description": "Check the dates of sources before comparing them.",+ "category": "general",+ "tags": ["research", "sources", "dates"],+ "triggers": [{"type": "voice", "pattern": "(source check)", "language": ["en"]}],+ "requires_tools": [],+ "risk_policy": {"default_tier": "monitor"},+ "body": "Check dates.\n\n## Steps\n1. Read each source's date.\n2. Compare.",+ }+)+++class _Skills:+ def __init__(self, root) -> None:+ from jarvis.skills.registry import SkillRegistry++ self.root = root+ root.mkdir(parents=True, exist_ok=True)+ self.registry = SkillRegistry(root, bus=None)+ self.registry.reload_sync()+++async def test_skill_learning_authors_on_the_agents_seat_only(registry, monkeypatch, tmp_path):+ from jarvis.agent_chat import runner_brain+ from jarvis.core.model_selection import ModelSelection, use_operation_model+ from jarvis.skills.creator_service import SkillCreatorInput+ from jarvis.society.learning import default_creator_factory++ def jarvis_brain(*args, **kwargs):+ raise AssertionError("society skill learning asked Jarvis' own provider")++ manager = SimpleNamespace(+ _tools={},+ _get_brain=jarvis_brain,+ _get_or_create=jarvis_brain,+ active_provider="openai",+ )+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: manager)+ registry.replies["antigravity"] = SKILL_DRAFT+ cfg = SimpleNamespace(brain=SimpleNamespace(providers={}))+ creator = await default_creator_factory(lambda: cfg)(+ _agent("antigravity", "agy-chosen"), _Skills(tmp_path / "skills")+ )+ # A pinned operation model (a GPT-Live call) must not outrank the seat.+ with use_operation_model(ModelSelection("openai", "pinned", "")):+ result = await creator.draft(SkillCreatorInput(intent="Check source dates"))+ assert result.brain_used and result.brain_source == "seat"+ assert [(b.name, b.kwargs["model"]) for b in registry.built] == [("antigravity", "agy-chosen")]+ assert registry.answered[0].caller == "society-skill"+++async def test_a_failing_skill_seat_asks_no_other_provider(registry, monkeypatch, tmp_path):+ from jarvis.agent_chat import runner_brain+ from jarvis.brain import resolver as brain_resolver+ from jarvis.skills.creator_service import SkillCreatorInput+ from jarvis.society.learning import default_creator_factory++ def ladder(*args, **kwargs):+ raise AssertionError("society skill learning climbed the resolver ladder")++ for name in ("resolve_tool_model_brain", "resolve_quality_brain", "resolve_frontier_brain"):+ monkeypatch.setattr(brain_resolver, name, ladder)+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: None)+ registry.failing = frozenset({"gemini"})+ creator = await default_creator_factory(lambda: None)(+ _agent("gemini", "gemini-chosen"), _Skills(tmp_path / "skills")+ )+ result = await creator.draft(SkillCreatorInput(intent="Check source dates"))+ assert not result.brain_used+ assert registry.built_names() == ["gemini"]+++async def test_the_learning_pass_awaits_the_seat_factory(tmp_path):+ from jarvis.society.learning import LearningPass, TurnDigest+ from jarvis.society.runtime import SocietyRuntime++ runtime = SocietyRuntime(tmp_path, cfg=lambda: None, seed_starter_team=False)+ await runtime.ensure_started()+ try:+ agent, _ = await runtime.roster.create(name="Scout")+ seen = []++ async def factory(agent, skills):+ seen.append(agent.agent_id)+ return None # The seat could not be built: nothing is learned.++ learner = LearningPass(runtime, creator_factory=factory)+ digest = TurnDigest(task="t", final_text="f", tool_steps=["a", "b"])+ assert await learner.run(agent, digest) is None+ assert seen == [agent.agent_id]+ finally:+ await runtime.close()