Skip to content

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.

feat(board): rewrite the profile bio on board events, billed to the subscription

rubenluetke10-beep46fe7b94f92b
diff --git a/jarvis/board/bio_brain.py b/jarvis/board/bio_brain.py
new file mode 100644
index 0000000000..658940f152
--- /dev/null
+++ b/jarvis/board/bio_brain.py
@@ -0,0 +1,156 @@
+"""Which brain writes the Board bio — the background billing rule applied.
+
+The bio is background work: an unlocked achievement or a refresh click starts
+it, never a voice or chat turn. It therefore follows
+:mod:`jarvis.brain.background_policy` (maintainer rule 2026-09-30, "auf Abo
+auslegen"):
+
+* **Subscription mode** (a subscription is connected, or was within the
+ policy's memory window): the bio is written on a connected subscription with
+ the caller's contract forwarded (``resolve_subscription_brain``), else on a
+ free local model. When neither is usable the resolve raises
+ :class:`~jarvis.brain.background_policy.BackgroundDeferred`; the generator
+ keeps the old bio and the next board event tries again. It never slides onto
+ a per-token API key.
+* **Key-only install** (no subscription ever connected): today's frontier
+ chain, unchanged, so a single-key download keeps a working bio (AGENTS.md
+ "any single key must work").
+* ``[board.bio].override_provider/override_model`` is a deliberate power-user
+ pin and is honoured as-is in both modes. In subscription mode an override
+ that cannot be instantiated falls through to the subscription path, never to
+ the keyed chain.
+
+Provider membership comes from the provider cards' billing mode (through the
+policy), never from a provider name (AP-21).
+
+Blocking by design: the policy's login probes and a CLI brain's construction
+touch the filesystem or a vendor CLI, so callers run this in a worker thread
+(``BioGenerator`` does).
+"""
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+from jarvis.brain import background_policy
+from jarvis.brain import resolver as brain_resolver
+
+if TYPE_CHECKING:
+ from jarvis.core.bus import EventBus
+ from jarvis.core.config import JarvisConfig
+ from jarvis.core.protocols import Brain
+
+log = logging.getLogger(__name__)
+
+#: Budget for one bio generation, and the per-call CLI budget handed to a
+#: subscription brain. A subscription CLI pays a cold start before it writes a
+#: word; the old 30 s cap was sized for a warm HTTP API.
+BIO_TIMEOUT_S = 90.0
+
+
+def resolve_bio_brain(config: JarvisConfig, *, bus: EventBus | None = None) -> Brain:
+ """The brain the next bio may be written on.
+
+ Raises:
+ BackgroundDeferred: subscription mode, and no subscription or local
+ model is usable right now. Nothing was billed.
+ RuntimeError: key-only install whose frontier chain is exhausted
+ (``resolve_frontier_brain``'s own contract).
+ """
+ policy = background_policy.background_providers(_brain_provider_ids())
+ if not policy.subscription_mode:
+ return brain_resolver.resolve_frontier_brain(config, bus=bus)
+
+ override = _override_entry(config)
+ if override is not None:
+ brain = _instantiate(*override)
+ if brain is not None:
+ log.info("bio brain: power-user override %s", override[0])
+ return brain
+
+ if any(background_policy.subscription_capable(name) for name in policy.allowed):
+ brain = brain_resolver.resolve_subscription_brain(
+ config, bus=bus, cli_timeout_s=BIO_TIMEOUT_S,
+ )
+ if brain is not None:
+ name = str(getattr(brain, "name", "") or "")
+ if policy.permits(name):
+ log.info("bio brain: subscription %s", name)
+ return brain
+ log.info(
+ "bio brain: %s is not allowed to bill background work right now", name,
+ )
+
+ for provider, model in _local_candidates(config, policy):
+ brain = _instantiate(provider, model)
+ if brain is not None:
+ log.info("bio brain: local model on %s", provider)
+ return brain
+
+ raise background_policy.BackgroundDeferred(
+ f"No subscription or local model can write the bio right now ({policy.reason})."
+ )
+
+
+def _brain_provider_ids() -> list[str]:
+ """Every brain card id, in card order — the policy picks what may bill."""
+ from jarvis.ui.web.provider_spec import PROVIDERS
+
+ return [spec.id for spec in PROVIDERS if spec.tier == "brain"]
+
+
+def _override_entry(config: JarvisConfig) -> tuple[str, str | None] | None:
+ bio_cfg = getattr(getattr(config, "board", None), "bio", None)
+ provider = (getattr(bio_cfg, "override_provider", None) or "").strip()
+ if not provider:
+ return None
+ model = (getattr(bio_cfg, "override_model", None) or "").strip()
+ return provider, model or None
+
+
+def _local_candidates(
+ config: JarvisConfig, policy: background_policy.BackgroundProviders,
+) -> list[tuple[str, str | None]]:
+ """Keyless local brains the policy allows, the user's own picks first.
+
+ A local primary or ``local_fallback`` leads (with the model the user chose
+ for it); every other registered local runtime follows in card order, the
+ same membership as the resolver's local tail.
+ """
+ brain_cfg = config.brain
+ local_fallback = (brain_cfg.local_fallback or "").strip()
+ fallback_model = (brain_cfg.local_fallback_model or "").strip() or None
+ preferred = [brain_cfg.primary or "", local_fallback]
+ ordered = list(dict.fromkeys(
+ [name for name in preferred if name in policy.allowed] + list(policy.allowed)
+ ))
+ try:
+ available = set(brain_resolver._get_registry().available())
+ except Exception: # noqa: BLE001 - no registry means no local brain, not a crash
+ log.info("bio brain: brain registry unavailable", exc_info=True)
+ return []
+ candidates: list[tuple[str, str | None]] = []
+ for name in ordered:
+ if not background_policy.keyless_local(name) or name not in available:
+ continue
+ if name == local_fallback and fallback_model:
+ candidates.append((name, fallback_model))
+ else:
+ candidates.append((name, brain_resolver._deep_model_for(config, name)))
+ return candidates
+
+
+def _instantiate(provider: str, model: str | None) -> Any | None:
+ try:
+ return brain_resolver._get_registry().instantiate(
+ provider, **({"model": model} if model else {}),
+ )
+ except Exception as exc: # noqa: BLE001 - an unusable candidate is skipped, not fatal
+ log.info(
+ "bio brain: %s/%s not instantiable (%s)",
+ provider, model or "<default>", type(exc).__name__,
+ )
+ return None
+
+
+__all__ = ["BIO_TIMEOUT_S", "resolve_bio_brain"]
diff --git a/jarvis/board/profile.py b/jarvis/board/profile.py
index 3a73d9415a..550273378e 100644
--- a/jarvis/board/profile.py
+++ b/jarvis/board/profile.py
@@ -5,7 +5,8 @@ Brainstorm spec 2026-05-02 (ten axes):
- Voice: Jarvis as first-person narrator.
- Tone: sharp, biting with a wink.
- Format: 3-5 sentences, one paragraph, no CTA.
-- Update: evolutionarily on Sundays (delta from the previous week).
+- Update: evolutionarily, when a board milestone is reached or the user asks
+ (delta from the previous bio) — see ``scheduler.py``.
- Data sources: everything Jarvis sees (Board stats + awareness episodes +
missions + self-mod audit + previous bio + feedback vector).
- Cold-start: first quiet observation from day 1.
@@ -19,7 +20,9 @@ a ``brain_resolver: Callable[[], Brain]`` — called fresh on EVERY
``generate_bio()`` call. This way a provider switch at runtime (user
switches the UI from Gemini to Claude) takes effect immediately.
-Default resolver: ``jarvis.brain.resolver.resolve_frontier_brain(config)``.
+Production resolver: ``jarvis.board.bio_brain.resolve_bio_brain(config)`` —
+the background billing rule (subscription or local model once a subscription
+is connected, the frontier chain on a key-only install).
## Failure modes
@@ -41,6 +44,7 @@ from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Any
+from jarvis.brain.background_policy import BackgroundDeferred
from jarvis.brain.streaming import aggregate
from jarvis.core.protocols import BrainMessage, BrainRequest
@@ -237,6 +241,10 @@ class BioGenerator:
self._temperature = float(temperature)
self._max_tokens = int(max_tokens)
self._timeout_s = float(timeout_s)
+ #: Why the last ``generate_bio`` wrote nothing, when it knows better than
+ #: "brain unavailable" (a deferred subscription resolve). The refresh
+ #: route shows it to the user.
+ self.last_skip_reason: str | None = None
# --------------- Public API ---------------
@@ -254,13 +262,21 @@ class BioGenerator:
dict with bio fields on success; ``None`` when the old bio
should stay visible (brain gone, timeout, empty output).
"""
+ self.last_skip_reason = None
if self._resolver is None:
log.info("BioGenerator: no brain_resolver configured — skip")
+ self.last_skip_reason = "No brain is configured for the bio"
return None
- # Call the resolver here — provider switches at runtime take effect this way.
+ # Call the resolver here — provider switches at runtime take effect this
+ # way. In a worker thread: the background billing rule probes
+ # subscription logins and may construct a CLI brain, both blocking.
try:
- brain = self._resolver()
+ brain = await asyncio.to_thread(self._resolver)
+ except BackgroundDeferred as exc:
+ log.info("BioGenerator: %s Keeping the old bio.", exc)
+ self.last_skip_reason = str(exc)
+ return None
except Exception: # noqa: BLE001
log.exception(
"BioGenerator: brain_resolver failed — keeping old bio"
diff --git a/jarvis/board/prompts.py b/jarvis/board/prompts.py
index 3a24b9f94b..f67363c6f8 100644
--- a/jarvis/board/prompts.py
+++ b/jarvis/board/prompts.py
@@ -35,12 +35,12 @@ Tricks gegen Haerte:
- Mikro-Korrektur im zweiten Halbsatz: "Das ist effizient. Auch ein bisschen einsam."
- Pointiere am Verhalten, nicht am Defizit.
-Wenn frueheres Bio-Block vorhanden: zeige explizit ein Wochen-Delta ("Neu diese Woche...", "Das wird sich vermutlich nicht aendern").
+Wenn frueheres Bio-Block vorhanden: zeige explizit das Delta seit der letzten Bio ("Neu seit dem letzten Mal...", "Das wird sich vermutlich nicht aendern").
Wenn Feedback-Vector "haerter" enthaelt: senke die Hoeflichkeitsschwelle, behalte die Faktentreue.
Wenn Cold-Start-Hint vorhanden: schreibe kuerzer (2-3 Saetze), explizit zaghaft, Schluss mit "Mehr in {n} Tagen."
BEISPIEL ✅ KORREKT (Tag 47, mit frueherem Bio):
-Du bist immer noch praezise und ungeduldig. Das wird sich vermutlich nicht aendern. Neu diese Woche: Du laesst mehr offen, weniger Jarvis-Agent-Spawns, mehr Eigenarbeit. Ich lese das als Vertrauen in dich selbst, nicht in mich. Notiert.
+Du bist immer noch praezise und ungeduldig. Das wird sich vermutlich nicht aendern. Neu seit dem letzten Mal: Du laesst mehr offen, weniger Jarvis-Agent-Spawns, mehr Eigenarbeit. Ich lese das als Vertrauen in dich selbst, nicht in mich. Notiert.
BEISPIEL ✅ KORREKT (Cold-Start, Tag 3):
Ich kenne dich seit 3 Tagen. Das ist zu wenig fuer ein Urteil, aber genug fuer eine erste Vermutung: Du klickst schneller als du denkst, und du denkst schneller als du sprichst. Mehr in vier Tagen.
@@ -198,7 +198,7 @@ def _render_previous_bio(text: str) -> str:
return ""
snippet = text[:600] + ("..." if len(text) > 600 else "")
return (
- "\nFRUEHERE BIO (vorletzter Sonntag — zeige explizit das Wochen-Delta):\n"
+ "\nFRUEHERE BIO (zeige explizit, was sich seitdem geaendert hat):\n"
f"\"{snippet}\"\n"
)
diff --git a/jarvis/board/scheduler.py b/jarvis/board/scheduler.py
index c2e25612f7..68cb561016 100644
--- a/jarvis/board/scheduler.py
+++ b/jarvis/board/scheduler.py
@@ -1,238 +1,195 @@
-"""BioScheduler — triggers the BioGenerator on a regular schedule (phase B).
-
-Two trigger types:
-
-1. **Weekly** (default: Sunday 18:00 local time). An ``asyncio`` loop ticks
- every 60 s and checks: is it Sunday within the 18:00–18:05 window and
- has regeneration not yet run *today*? The date guard stored in
- ``aggregator_meta[last_bio_run_date]`` prevents double-runs even when
- the app is restarted inside the window.
-
-2. **Master achievement**: a second bus subscriber listens for
- ``AchievementUnlocked`` and triggers regeneration for every
- ``*_master`` ID — e.g. ``tool_master``.
-
-No APScheduler dependency (project pattern, see RECON.md §4).
+"""BioScheduler — rewrites the Board bio when something meaningful happens.
+
+There is no timer. The bio used to be regenerated every Sunday at 18:00, on
+every boot of an install without a bio, and on ``*_master`` achievements —
+on the primary provider's deep model, usually a paid key, whether or not
+anything had changed. Maintainer decision (2026-09-30): update the bio on real
+board events and bill it to the subscription (see ``bio_brain.py``).
+
+Hooks:
+
+1. **Achievement unlocked** — every ``AchievementUnlocked`` on the bus. The
+ evaluator publishes each achievement exactly once (``INSERT OR IGNORE``),
+ so these are the board's milestones.
+2. **Explicit refresh** — ``POST /api/board/bio/regenerate`` calls the
+ generator directly and is never held back by the spacing below.
+
+A burst of hooks (one tool call can unlock two achievements) is debounced into
+ONE generation, and a hook-driven generation keeps at least
+:attr:`BioScheduler.MIN_SPACING_S` after the newest bio. A hook inside that
+window is not dropped: the pending generation waits for the window to close.
+A bio written after the first pending hook — the user refreshed by hand —
+already covers it, so the pending run then ends without generating again.
+
+A failed or deferred generation (no subscription usable right now) is not
+retried on a timer; the next board event tries again. Pending work lives in
+memory only, and nothing is generated at boot: an install without a bio gets
+its first one at its first achievement or refresh click.
"""
from __future__ import annotations
import asyncio
import logging
-import sqlite3
-from datetime import datetime
-from pathlib import Path
-from typing import Any
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
from jarvis.core.bus import EventBus
-from jarvis.core.events import AchievementUnlocked, Event
+from jarvis.core.events import AchievementUnlocked
from .profile import BioGenerator, BioStore
-from .store import BoardStore
log = logging.getLogger(__name__)
class BioScheduler:
- """Orchestrates bio regeneration.
-
- Uses the same DB as the aggregator and evaluator — an additional
- ``meta`` key (``last_bio_run_date``) guarantees idempotency.
- """
+ """Turns board events into (at most) one bio generation at a time."""
- # Default config — can be overridden in the future via cfg.board.ai_profile
- # (plan §5-B Ultrathink #3).
- DEFAULT_WEEKDAY = 6 # Sonntag (Mon=0)
- DEFAULT_HOUR = 18
- WINDOW_MINUTES = 5
+ #: Quiet period that folds a burst of hooks into one generation.
+ DEBOUNCE_S = 30.0
+ #: Minimum distance between the newest bio and a hook-driven generation.
+ MIN_SPACING_S = 24 * 3600.0
def __init__(
self,
*,
generator: BioGenerator,
- db_path: Path,
+ bio_store: BioStore,
bus: EventBus | None = None,
- weekday: int | None = None,
- hour: int | None = None,
- tick_interval_s: float = 60.0,
- memory_text_provider: Any = None,
- soul_text_provider: Any = None,
- bio_store: BioStore | None = None,
- board_store: BoardStore | None = None,
- cold_start_min_days: int = 1,
+ debounce_s: float | None = None,
+ min_spacing_s: float | None = None,
+ clock: Callable[[], datetime] | None = None,
) -> None:
self._gen = generator
- self._db_path = Path(db_path)
+ self._bio_store = bio_store
self._bus = bus
- self._weekday = self.DEFAULT_WEEKDAY if weekday is None else weekday
- self._hour = self.DEFAULT_HOUR if hour is None else hour
- self._tick_s = tick_interval_s
- self._memory_provider = memory_text_provider
- self._soul_provider = soul_text_provider
- self._task: asyncio.Task[None] | None = None
+ self._debounce_s = self.DEBOUNCE_S if debounce_s is None else max(0.0, debounce_s)
+ self._min_spacing_s = (
+ self.MIN_SPACING_S if min_spacing_s is None else max(0.0, min_spacing_s)
+ )
+ self._clock = clock or (lambda: datetime.now(UTC))
self._subscribed = False
- # Cold-start: fires once when no bio exists AND the user already has
- # at least ``cold_start_min_days`` days of activity.
- self._bio_store = bio_store
- self._board_store = board_store
- self._cold_start_min_days = max(0, int(cold_start_min_days))
- self._cold_start_done = False
+ self._closed = False
+ self._pending: asyncio.Task[None] | None = None
+ self._reasons: list[str] = []
+ self._first_hook_at: datetime | None = None
# --------------- Lifecycle ---------------
def start(self) -> None:
+ """Subscribes to the hooks. Starts no task and generates nothing."""
+ self._closed = False
if self._bus is not None and not self._subscribed:
- self._bus.subscribe_all(self._on_event)
+ self._bus.subscribe(AchievementUnlocked, self._on_achievement)
self._subscribed = True
- if self._task is None or self._task.done():
- self._task = asyncio.create_task(self._loop(), name="bio-scheduler")
async def stop(self) -> None:
+ self._closed = True
if self._bus is not None and self._subscribed:
- try:
- self._bus._wildcard_subscribers.remove(self._on_event) # type: ignore[attr-defined]
- except (AttributeError, ValueError):
- pass
+ self._bus.unsubscribe(AchievementUnlocked, self._on_achievement)
self._subscribed = False
- if self._task is not None:
- self._task.cancel()
+ task, self._pending = self._pending, None
+ if task is not None and not task.done():
+ task.cancel()
try:
- await self._task
- except (asyncio.CancelledError, Exception):
- pass
- self._task = None
+ await task
+ except asyncio.CancelledError:
+ pass # the cancellation requested just above
+ self._reasons.clear()
+ self._first_hook_at = None
- # --------------- Weekly loop ---------------
+ # --------------- Hooks ---------------
- async def _loop(self) -> None:
- while True:
- try:
- await self._maybe_run_cold_start()
- except asyncio.CancelledError:
- raise
- except Exception: # noqa: BLE001
- log.exception("BioScheduler cold-start tick failed")
- try:
- await self._maybe_run_weekly()
- except asyncio.CancelledError:
- raise
- except Exception: # noqa: BLE001
- log.exception("BioScheduler weekly tick failed")
- try:
- await asyncio.sleep(self._tick_s)
- except asyncio.CancelledError:
- raise
-
- async def _maybe_run_cold_start(self) -> None:
- """Fires once when no bio exists yet.
-
- The check ticks every minute (cheap), but the flag ``_cold_start_done``
- prevents multiple triggers within the same app session.
- Persistent idempotency is inherited from ``last_bio_run_date`` — once
- the cold-start bio is written, ``BioStore.latest()`` is no longer
- ``None``, so the path does not trigger again.
- """
- if self._cold_start_done:
- return
- if self._bio_store is None or self._board_store is None:
- self._cold_start_done = True # Stack is incomplete, abort
- return
- latest = self._bio_store.latest()
- if latest is not None:
- self._cold_start_done = True # bio already exists
- return
- try:
- days = self._board_store.days_observed()
- except Exception: # noqa: BLE001
- return
- if days < self._cold_start_min_days:
- return
- today_iso = datetime.now().astimezone().date().isoformat()
- await self._run_and_mark(triggered_by="cold_start", today_iso=today_iso)
- self._cold_start_done = True
+ async def _on_achievement(self, event: AchievementUnlocked) -> None:
+ """Bus callback: only records the hook, never waits on a brain."""
+ achievement = (event.achievement_id or "").strip()
+ self.notify(f"milestone:{achievement}" if achievement else "milestone")
- async def _maybe_run_weekly(self) -> None:
- now = datetime.now().astimezone()
- if now.weekday() != self._weekday:
- return
- if now.hour != self._hour:
+ def notify(self, reason: str) -> None:
+ """Records one meaningful board event. Call on the event loop."""
+ if self._closed:
return
- if now.minute >= self.WINDOW_MINUTES:
- return
- today_iso = now.date().isoformat()
- if self._read_meta("last_bio_run_date") == today_iso:
- return
- await self._run_and_mark(triggered_by="weekly", today_iso=today_iso)
-
- async def _run_and_mark(self, *, triggered_by: str, today_iso: str) -> None:
- memory = await _call(self._memory_provider, default="")
- soul = await _call(self._soul_provider, default="")
- result = await self._gen.generate_bio(
- memory_text=memory,
- soul_text=soul,
- triggered_by=triggered_by,
- )
- if result is not None:
- self._write_meta("last_bio_run_date", today_iso)
- log.info("BioScheduler: Bio regeneriert (trigger=%s)", triggered_by)
+ if not self._reasons:
+ self._first_hook_at = self._clock()
+ self._reasons.append(reason)
+ if self._pending is None or self._pending.done():
+ self._pending = asyncio.create_task(
+ self._run_pending(), name="board-bio-refresh",
+ )
- # --------------- Achievement-driven trigger ---------------
+ # --------------- Pending generation ---------------
- async def _on_event(self, event: Event) -> None:
- """Bus callback for ``AchievementUnlocked`` events with id *_master."""
+ async def _run_pending(self) -> None:
try:
- if not isinstance(event, AchievementUnlocked):
- return
- if not event.achievement_id.endswith("_master"):
- return
- today_iso = datetime.now().astimezone().date().isoformat()
- # Milestone regeneration is NOT blocked by the date guard —
- # if the user reaches tool_master on a Sunday, they should
- # receive the fresh bio immediately, not next week.
- await self._gen.generate_bio(
- memory_text=await _call(self._memory_provider, default=""),
- soul_text=await _call(self._soul_provider, default=""),
- triggered_by=f"milestone:{event.achievement_id}",
+ await self._wait_then_generate()
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 - one failed run must not kill later hooks
+ log.exception("BioScheduler: hook-driven bio generation failed")
+ # Hooks that arrived while this run was generating get their own run;
+ # it finds the fresh bio and ends unless they came after it.
+ if self._reasons and not self._closed:
+ self._pending = asyncio.create_task(
+ self._run_pending(), name="board-bio-refresh",
)
- self._write_meta("last_bio_run_date", today_iso)
- except Exception: # noqa: BLE001
- log.exception("BioScheduler milestone trigger failed")
-
- # --------------- DB helpers ---------------
-
- def _conn(self) -> sqlite3.Connection:
- conn = sqlite3.connect(self._db_path, isolation_level=None)
- conn.row_factory = sqlite3.Row
- return conn
+ else:
+ self._pending = None
- def _read_meta(self, key: str) -> str | None:
- conn = self._conn()
- try:
- row = conn.execute(
- "SELECT value FROM aggregator_meta WHERE key = ?", (key,),
- ).fetchone()
- return row["value"] if row is not None else None
- finally:
- conn.close()
-
- def _write_meta(self, key: str, value: str) -> None:
- conn = self._conn()
- try:
- conn.execute(
- "INSERT INTO aggregator_meta (key, value) VALUES (?, ?) "
- "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
- (key, value),
+ async def _wait_then_generate(self) -> None:
+ if self._debounce_s > 0:
+ await asyncio.sleep(self._debounce_s)
+ while True:
+ wait_s = await asyncio.to_thread(self._seconds_until_due)
+ if wait_s is None:
+ log.info(
+ "BioScheduler: a newer bio already covers %s", ", ".join(self._reasons),
+ )
+ self._drain()
+ return
+ if wait_s <= 0:
+ break
+ log.info(
+ "BioScheduler: %s waits %.0f s for the %.0f h spacing",
+ ", ".join(self._reasons), wait_s, self._min_spacing_s / 3600,
+ )
+ await asyncio.sleep(wait_s)
+
+ reasons = self._drain()
+ result = await self._gen.generate_bio(triggered_by=reasons[0])
+ if result is None:
+ log.info(
+ "BioScheduler: bio not rewritten (trigger=%s); the next board event retries",
+ ", ".join(reasons),
)
- finally:
- conn.close()
-
-
-async def _call(provider: Any, *, default: str) -> str:
- """Accepts a callable, a coroutine-callable, or a plain string as provider."""
- if provider is None:
- return default
- if callable(provider):
- result = provider()
- if asyncio.iscoroutine(result):
- result = await result
- return str(result) if result is not None else default
- return str(provider)
+ else:
+ log.info("BioScheduler: bio rewritten (trigger=%s)", ", ".join(reasons))
+
+ def _seconds_until_due(self) -> float | None:
+ """Seconds until a generation may run; ``None`` if a newer bio covers it."""
+ latest = self._bio_store.latest()
+ generated_at = _parse_iso((latest or {}).get("generated_at"))
+ if generated_at is None:
+ return 0.0
+ first_hook_at = self._first_hook_at
+ if first_hook_at is not None and generated_at >= first_hook_at:
+ return None
+ due = generated_at + timedelta(seconds=self._min_spacing_s)
+ return max(0.0, (due - self._clock()).total_seconds())
+
+ def _drain(self) -> list[str]:
+ reasons = list(self._reasons) or ["milestone"]
+ self._reasons.clear()
+ self._first_hook_at = None
+ return reasons
+
+
+def _parse_iso(value: object) -> datetime | None:
+ """An aware datetime from a stored ISO timestamp, or None."""
+ if not value:
+ return None
+ try:
+ parsed = datetime.fromisoformat(str(value))
+ except ValueError:
+ log.warning("BioScheduler: unreadable bio timestamp %r, treating as no bio", value)
+ return None
+ # BioStore writes local time with its offset; a naive value is local too.
+ return parsed if parsed.tzinfo is not None else parsed.astimezone()
diff --git a/jarvis/board/store.py b/jarvis/board/store.py
index d67a97a279..ac0a6f5a55 100644
--- a/jarvis/board/store.py
+++ b/jarvis/board/store.py
@@ -322,9 +322,8 @@ class BoardStore:
def days_observed(self) -> int:
"""Days since the first day with activity (active_events_count > 0).
- Passed to the prompt by the BioGenerator as ``days_observed`` and
- used by the BioScheduler as the cold-start threshold. Returns 0 for
- an empty DB (no cold-start fires).
+ Passed to the prompt by the BioGenerator as ``days_observed`` (a young
+ install gets the shorter cold-start bio). Returns 0 for an empty DB.
"""
conn = self._connect()
try:
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index dee0797da2..f9487ab98a 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2495,14 +2495,18 @@ class BoardFederationConfig(BaseModel):
class BoardBioConfig(BaseModel):
"""Knobs for the AI profile generator (BioGenerator).
- Important: NO provider/model default. The bio dynamically uses the
- frontier model of the currently configured primary provider
- (see ``jarvis/brain/resolver.py:resolve_frontier_brain``). A user with
- only a Gemini API key gets a Gemini bio; a user with Claude configured gets
- Opus. Multi-provider compliance is mandatory.
+ Important: NO provider/model default. The bio is background work and
+ follows the background billing rule (``jarvis/board/bio_brain.py``): once
+ a subscription is connected it is written on a subscription or a free
+ local model, never a per-token key; a key-only install uses the frontier
+ model of its primary provider. Multi-provider compliance is mandatory.
``override_provider`` / ``override_model`` are power-user fields for
explicitly pinning a model for the bio only. Leave empty in 99% of cases.
+
+ The bio is rewritten on board events (achievements) and on request, never
+ on a timer. The retired ``cold_start_min_days`` key still loads from old
+ configs (``extra="allow"``) and is ignored.
"""
model_config = {"extra": "allow"}
@@ -2511,9 +2515,6 @@ class BoardBioConfig(BaseModel):
max_tokens: int = Field(default=400, ge=80, le=2000)
override_provider: str | None = None
override_model: str | None = None
- # Cold start: trigger the first bio after this minimum age in days
- # (instead of waiting until Sunday when no bio exists yet).
- cold_start_min_days: int = Field(default=1, ge=0, le=14)
class BoardConfig(BaseModel):
diff --git a/jarvis/ui/web/board_routes.py b/jarvis/ui/web/board_routes.py
index ab4ef37068..d1836829ae 100644
--- a/jarvis/ui/web/board_routes.py
+++ b/jarvis/ui/web/board_routes.py
@@ -365,9 +365,13 @@ async def regenerate_bio(
ok=False, generated_at=None, text=None, reason=str(exc),
)
if result is None:
+ skip_reason = getattr(gen, "last_skip_reason", None)
return BioRegenerateResponse(
ok=False, generated_at=None, text=None,
- reason="Brain not available — old bio stays",
+ reason=(
+ f"{skip_reason} The old bio stays." if skip_reason
+ else "Brain not available — old bio stays"
+ ),
)
return BioRegenerateResponse(
ok=True,
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index b032d8adc9..9c1f0fe41e 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -790,11 +790,11 @@ class WebServer:
"""
try:
from jarvis.board.aggregator import BoardAggregator
+ from jarvis.board.bio_brain import BIO_TIMEOUT_S, resolve_bio_brain
from jarvis.board.evaluator import AchievementEvaluator
from jarvis.board.profile import BioGenerator, BioStore
from jarvis.board.scheduler import BioScheduler
from jarvis.board.store import BoardStore
- from jarvis.brain.resolver import resolve_frontier_brain
from jarvis.core.paths import board_db_path, user_data_dir, user_logs_dir
db_path = board_db_path()
@@ -834,7 +834,9 @@ class WebServer:
# Lazy: capture cfg + bus from the closure, so a later
# provider switch via the UI takes effect immediately
# (the resolver invalidates its cache via ConfigReloaded).
- return resolve_frontier_brain(cfg, bus=self.bus)
+ # Background billing rule: subscription or local model once a
+ # subscription is connected, never a per-token key.
+ return resolve_bio_brain(cfg, bus=self.bus)
bio_generator = BioGenerator(
brain_resolver=_bio_brain_resolver,
@@ -846,14 +848,14 @@ class WebServer:
self_mod_log_path=self_mod_log,
temperature=bio_cfg.temperature,
max_tokens=bio_cfg.max_tokens,
+ timeout_s=BIO_TIMEOUT_S,
)
+ # Hook-driven: rewrites the bio on unlocked achievements, never on
+ # a timer or at boot.
scheduler = BioScheduler(
generator=bio_generator,
- db_path=db_path,
- bus=self.bus,
bio_store=bio_store,
- board_store=store,
- cold_start_min_days=bio_cfg.cold_start_min_days,
+ bus=self.bus,
)
self._board_aggregator = aggregator
@@ -2793,10 +2795,9 @@ class WebServer:
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("AchievementEvaluator.attach() failed")
- # Bio scheduler — weekly + master achievement trigger.
- # The brain isn't finalized here yet (app.state.brain usually
- # arrives later). BioGenerator.brain stays None until the caller
- # sets it — the scheduler handles a None brain gracefully.
+ # Bio scheduler — subscribes to achievement unlocks only. It starts no
+ # task and generates nothing here; the brain is resolved per
+ # generation, when a board event actually asks for one.
if self._bio_scheduler is not None:
try:
self._bio_scheduler.start()
diff --git a/tests/board/test_bio_brain.py b/tests/board/test_bio_brain.py
new file mode 100644
index 0000000000..6fb7d7f7ff
--- /dev/null
+++ b/tests/board/test_bio_brain.py
@@ -0,0 +1,217 @@
+"""The Board bio follows the background billing rule.
+
+Once a subscription is connected the bio is written on a subscription or a
+free local model; when neither is usable it waits for the next board event and
+never falls back to a per-token key. A key-only install keeps the frontier
+chain it always had.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.board import bio_brain
+from jarvis.board.profile import BioGenerator, BioStore
+from jarvis.board.store import BoardStore
+from jarvis.brain import background_policy as policy
+from jarvis.brain import resolver
+from jarvis.core.config import JarvisConfig
+
+
+class _Brain:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+
+class _FakeRegistry:
+ """Records every instantiation; a keyed one in subscription mode is the bug."""
+
+ def __init__(
+ self, available: list[str], connected: tuple[str, ...] = (), fail: tuple[str, ...] = (),
+ ) -> None:
+ self._available = list(available)
+ self._connected = set(connected)
+ self._fail = set(fail)
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def available(self) -> list[str]:
+ return list(self._available)
+
+ def get_class(self, name: str) -> type:
+ connected = name in self._connected
+ return type(
+ "FakeBrainClass",
+ (),
+ {
+ "native_system_prompt": True,
+ "subscription_connected": staticmethod(lambda: connected),
+ },
+ )
+
+ def instantiate(self, name: str, **kwargs: Any) -> _Brain:
+ self.calls.append((name, dict(kwargs)))
+ if name in self._fail:
+ raise RuntimeError("not instantiable")
+ return _Brain(name)
+
+ def names(self) -> list[str]:
+ return [name for name, _ in self.calls]
+
+
[email protected](autouse=True)
+def _isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "appdata"))
+ policy.reset_for_tests()
+ resolver._reset_for_tests()
+ yield
+ policy.reset_for_tests()
+ resolver._reset_for_tests()
+
+
+def _world(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ available: list[str],
+ connected: tuple[str, ...] = (),
+ fail: tuple[str, ...] = (),
+) -> _FakeRegistry:
+ registry = _FakeRegistry(available, connected, fail)
+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)
+ policy._probe_override = lambda name: name in connected
+ return registry
+
+
+def _frontier_must_not_run(monkeypatch: pytest.MonkeyPatch) -> None:
+ def _forbidden(*_args: Any, **_kwargs: Any) -> Any:
+ raise AssertionError("subscription mode walked the keyed frontier chain")
+
+ monkeypatch.setattr(resolver, "resolve_frontier_brain", _forbidden)
+
+
+def _keyed(names: list[str]) -> list[str]:
+ return [name for name in names if policy._billing(name) == "api"]
+
+
+def test_key_only_install_keeps_the_frontier_chain(monkeypatch: pytest.MonkeyPatch) -> None:
+ registry = _world(monkeypatch, available=["openai", "claude-cli", "ollama"])
+ frontier = _Brain("openai")
+ monkeypatch.setattr(resolver, "resolve_frontier_brain", lambda cfg, **kw: frontier)
+
+ assert bio_brain.resolve_bio_brain(JarvisConfig()) is frontier
+ assert registry.calls == []
+
+
+def test_connected_subscription_writes_the_bio_and_no_key_is_touched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ registry = _world(
+ monkeypatch,
+ available=["openai", "gemini", "claude-api", "claude-cli", "ollama"],
+ connected=("claude-cli",),
+ )
+ _frontier_must_not_run(monkeypatch)
+ cfg = JarvisConfig()
+ cfg.brain.primary = "openai"
+
+ brain = bio_brain.resolve_bio_brain(cfg)
+
+ assert brain.name == "claude-cli"
+ assert registry.names() == ["claude-cli"]
+ kwargs = registry.calls[0][1]
+ assert kwargs["structured_prompts"] is True
+ assert kwargs["cli_timeout_s"] == bio_brain.BIO_TIMEOUT_S
+
+
+def test_signed_out_subscription_falls_back_to_a_local_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ policy.note_connected("claude-cli") # seen connected earlier, signed out now
+ registry = _world(
+ monkeypatch, available=["openai", "gemini", "claude-cli", "ollama"],
+ )
+ _frontier_must_not_run(monkeypatch)
+
+ brain = bio_brain.resolve_bio_brain(JarvisConfig())
+
+ assert brain.name == "ollama"
+ assert _keyed(registry.names()) == []
+
+
+def test_no_usable_subscription_defers_without_touching_a_key(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ policy.note_connected("claude-cli")
+ registry = _world(
+ monkeypatch, available=["openai", "gemini", "claude-api", "claude-cli"],
+ )
+ _frontier_must_not_run(monkeypatch)
+
+ with pytest.raises(policy.BackgroundDeferred):
+ bio_brain.resolve_bio_brain(JarvisConfig())
+ assert registry.calls == []
+
+
+def test_override_is_honoured_as_is_in_subscription_mode(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ registry = _world(
+ monkeypatch, available=["openai", "claude-cli"], connected=("claude-cli",),
+ )
+ _frontier_must_not_run(monkeypatch)
+ cfg = JarvisConfig()
+ cfg.board.bio.override_provider = "openai"
+ cfg.board.bio.override_model = "picked-model"
+
+ brain = bio_brain.resolve_bio_brain(cfg)
+
+ assert brain.name == "openai"
+ assert registry.calls == [("openai", {"model": "picked-model"})]
+
+
+def test_broken_override_falls_through_to_the_subscription_not_to_keys(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ registry = _world(
+ monkeypatch,
+ available=["openai", "gemini", "claude-cli"],
+ connected=("claude-cli",),
+ fail=("openai",),
+ )
+ _frontier_must_not_run(monkeypatch)
+ cfg = JarvisConfig()
+ cfg.board.bio.override_provider = "openai"
+
+ brain = bio_brain.resolve_bio_brain(cfg)
+
+ assert brain.name == "claude-cli"
+ assert registry.names() == ["openai", "claude-cli"]
+
+
+async def test_generator_skips_a_deferred_bio_without_any_key_call(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ policy.note_connected("claude-cli")
+ registry = _world(monkeypatch, available=["openai", "gemini", "claude-cli"])
+ _frontier_must_not_run(monkeypatch)
+ cfg = JarvisConfig()
+ db = tmp_path / "personal.db"
+ bio_store = BioStore(db)
+ gen = BioGenerator(
+ brain_resolver=lambda: bio_brain.resolve_bio_brain(cfg),
+ store=BoardStore(db),
+ bio_store=bio_store,
+ )
+
+ assert await gen.generate_bio(triggered_by="milestone:first_mcp") is None
+ assert bio_store.latest() is None
+ assert registry.calls == []
+ assert gen.last_skip_reason and "subscription" in gen.last_skip_reason
+
+
+def test_retired_cold_start_key_still_loads() -> None:
+ cfg = JarvisConfig.model_validate({"board": {"bio": {"cold_start_min_days": 3}}})
+ assert cfg.board.bio.override_provider is None
+ assert "cold_start_min_days" not in type(cfg.board.bio).model_fields
diff --git a/tests/board/test_scheduler.py b/tests/board/test_scheduler.py
index 4422c6f434..c4d3c74549 100644
--- a/tests/board/test_scheduler.py
+++ b/tests/board/test_scheduler.py
@@ -1,8 +1,8 @@
-"""Tests for BioScheduler (Phase B)."""
+"""BioScheduler — the bio is rewritten on board events, never on a timer."""
from __future__ import annotations
import asyncio
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Callable
from pathlib import Path
import pytest
@@ -10,6 +10,7 @@ import pytest
from jarvis.board.profile import BioGenerator, BioStore, make_resolver_from_brain
from jarvis.board.scheduler import BioScheduler
from jarvis.board.store import BoardStore
+from jarvis.brain.background_policy import BackgroundDeferred
from jarvis.core.bus import EventBus
from jarvis.core.events import AchievementUnlocked
from jarvis.core.protocols import BrainDelta, BrainRequest
@@ -21,71 +22,172 @@ class _FakeBrain:
async def complete(self, request: BrainRequest) -> AsyncIterator[BrainDelta]:
self.calls += 1
- yield BrainDelta(content=f"Bio-Run #{self.calls}. Nur Daten. Nichts gross.")
+ yield BrainDelta(content=f"Bio run {self.calls}. Data only. Nothing big.")
yield BrainDelta(finish_reason="stop", usage={"input_tokens": 100, "output_tokens": 50})
-def _make_scheduler(tmp_path: Path, bus: EventBus | None = None) -> tuple[BioScheduler, BioStore, _FakeBrain]:
+def _unlocked(achievement_id: str) -> AchievementUnlocked:
+ return AchievementUnlocked(
+ achievement_id=achievement_id, title=achievement_id, description="",
+ tier="mastery", evidence={},
+ )
+
+
+def _make(
+ tmp_path: Path,
+ *,
+ bus: EventBus | None = None,
+ resolver: Callable[[], object] | None = None,
+ debounce_s: float = 0.05,
+ min_spacing_s: float = 3600.0,
+) -> tuple[BioScheduler, BioGenerator, BioStore, _FakeBrain]:
db = tmp_path / "personal.db"
bio_store = BioStore(db)
- store = BoardStore(db)
brain = _FakeBrain()
gen = BioGenerator(
- brain_resolver=make_resolver_from_brain(brain), store=store, bio_store=bio_store,
+ brain_resolver=resolver or make_resolver_from_brain(brain),
+ store=BoardStore(db),
+ bio_store=bio_store,
jsonl_dir=tmp_path / "flight_recorder",
)
sched = BioScheduler(
- generator=gen, db_path=db, bus=bus, tick_interval_s=0.05,
+ generator=gen, bio_store=bio_store, bus=bus,
+ debounce_s=debounce_s, min_spacing_s=min_spacing_s,
)
- return sched, bio_store, brain
+ return sched, gen, bio_store, brain
+
+
+async def _settle(sched: BioScheduler, timeout_s: float = 5.0) -> None:
+ """Wait until no generation is pending (a run may hand over to a follow-up)."""
+ for _ in range(5):
+ task = sched._pending
+ if task is None:
+ return
+ await asyncio.wait_for(task, timeout=timeout_s)
+ assert sched._pending is None, "pending bio generation never finished"
@pytest.mark.asyncio
-async def test_master_achievement_triggers_bio_regeneration(tmp_path: Path) -> None:
+async def test_burst_of_achievements_causes_one_generation(tmp_path: Path) -> None:
bus = EventBus()
- sched, bio_store, brain = _make_scheduler(tmp_path, bus=bus)
+ sched, _gen, bio_store, brain = _make(tmp_path, bus=bus)
sched.start()
try:
- await bus.publish(AchievementUnlocked(
- achievement_id="tool_master",
- title="Tool Master", description="",
- tier="mastery", evidence={"unique_tools": 30},
- ))
- await asyncio.sleep(0.1)
+ for achievement in ("tool_dabbler", "triple_combo", "first_mcp"):
+ await bus.publish(_unlocked(achievement))
+ await _settle(sched)
assert brain.calls == 1
latest = bio_store.latest()
assert latest is not None
- assert latest["triggered_by"] == "milestone:tool_master"
+ assert latest["triggered_by"] == "milestone:tool_dabbler"
+ finally:
+ await sched.stop()
+
+
+async def test_start_generates_nothing_without_a_hook(tmp_path: Path) -> None:
+ """No weekly tick, no boot-time cold start — even with no bio at all."""
+ bus = EventBus()
+ sched, _gen, bio_store, brain = _make(tmp_path, bus=bus, debounce_s=0.0)
+ sched.start()
+ try:
+ await asyncio.sleep(0.2)
+ assert sched._pending is None
+ assert brain.calls == 0
+ assert bio_store.latest() is None
finally:
await sched.stop()
@pytest.mark.asyncio
-async def test_non_master_achievement_does_not_trigger(tmp_path: Path) -> None:
+async def test_unrelated_events_are_not_hooks(tmp_path: Path) -> None:
+ from jarvis.core.events import BioFeedbackRecorded
+
bus = EventBus()
- sched, bio_store, brain = _make_scheduler(tmp_path, bus=bus)
+ sched, _gen, _bio_store, brain = _make(tmp_path, bus=bus, debounce_s=0.0)
sched.start()
try:
- await bus.publish(AchievementUnlocked(
- achievement_id="tool_dabbler",
- title="Tool Dabbler", description="",
- tier="mastery", evidence={},
- ))
+ await bus.publish(BioFeedbackRecorded(bio_generated_at="x", kind="haerter"))
await asyncio.sleep(0.1)
+ assert sched._pending is None
assert brain.calls == 0
+ finally:
+ await sched.stop()
+
+
+async def test_hook_inside_spacing_waits_for_the_window(tmp_path: Path) -> None:
+ sched, _gen, bio_store, brain = _make(tmp_path, min_spacing_s=0.4)
+ bio_store.insert("earlier bio", triggered_by="manual")
+ await asyncio.sleep(0.01)
+ sched.start()
+ try:
+ sched.notify("milestone:centennial")
+ await asyncio.sleep(0.2)
+ assert brain.calls == 0, "generated inside the spacing window"
+ await _settle(sched)
+ assert brain.calls == 1
+ assert bio_store.latest()["triggered_by"] == "milestone:centennial" # type: ignore[index]
+ finally:
+ await sched.stop()
+
+
+async def test_bio_written_after_the_hook_covers_the_pending_run(tmp_path: Path) -> None:
+ """A manual refresh after the hook already reflects it — no second run."""
+ sched, gen, bio_store, brain = _make(tmp_path, min_spacing_s=0.3)
+ bio_store.insert("earlier bio", triggered_by="manual")
+ await asyncio.sleep(0.01)
+ sched.start()
+ try:
+ sched.notify("milestone:kilo_club")
+ await gen.generate_bio(triggered_by="manual")
+ assert brain.calls == 1
+ await _settle(sched)
+ assert brain.calls == 1
+ assert bio_store.latest()["triggered_by"] == "manual" # type: ignore[index]
+ finally:
+ await sched.stop()
+
+
+async def test_deferred_generation_waits_for_the_next_hook(tmp_path: Path) -> None:
+ attempts: list[int] = []
+
+ def _deferred() -> object:
+ attempts.append(1)
+ raise BackgroundDeferred("No subscription or local model can write the bio right now.")
+
+ sched, gen, bio_store, _brain = _make(tmp_path, resolver=_deferred)
+ sched.start()
+ try:
+ sched.notify("milestone:first_mcp")
+ await _settle(sched)
+ assert len(attempts) == 1
assert bio_store.latest() is None
+ assert gen.last_skip_reason and "subscription" in gen.last_skip_reason
+
+ await asyncio.sleep(0.2)
+ assert len(attempts) == 1, "a deferred bio must not be retried on a timer"
+
+ sched.notify("milestone:tool_dabbler")
+ await _settle(sched)
+ assert len(attempts) == 2
finally:
await sched.stop()
@pytest.mark.asyncio
-async def test_weekly_date_guard_respected(tmp_path: Path) -> None:
- """Der Scheduler setzt ``last_bio_run_date`` — zweiter Lauf heute no-op."""
- sched, bio_store, brain = _make_scheduler(tmp_path)
- today = "2026-04-24"
- await sched._run_and_mark(triggered_by="weekly", today_iso=today)
- await sched._run_and_mark(triggered_by="weekly", today_iso=today)
- assert brain.calls == 2 # both calls ran, because _run_and_mark has no guard
- # But: _maybe_run_weekly would skip the second run because of the
- # last_bio_run_date check. Verify:
- assert sched._read_meta("last_bio_run_date") == today
+async def test_stop_cancels_pending_work_and_unsubscribes(tmp_path: Path) -> None:
+ bus = EventBus()
+ sched, _gen, _bio_store, brain = _make(tmp_path, bus=bus, debounce_s=10.0)
+ sched.start()
+ await bus.publish(_unlocked("tool_master"))
+ assert sched._pending is not None
+ await sched.stop()
+ assert sched._pending is None
+
+ await bus.publish(_unlocked("centennial"))
+ await asyncio.sleep(0.05)
+ assert sched._pending is None
+ assert brain.calls == 0